forked from jvalen/pixel-art-react
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathapp.js
231 lines (202 loc) · 6.4 KB
/
app.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
/**
* Module dependencies.
*/
import { renderToString } from 'react-dom/server'
import { Provider } from 'react-redux'
import undoable from 'redux-undo'
import reducer from './src/reducer'
import {AppContainer} from './src/components/App'
import gm from 'gm'
import express from 'express'
import bodyParser from 'body-parser'
import cookieParser from 'cookie-parser'
import temp from 'temp'
import fs from 'fs'
import path from 'path'
import Twitter from 'twitter'
import {OAuth} from 'oauth'
import session from 'express-session'
import React from 'react'
import { createStore } from 'redux'
import Jade from 'jade'
import {Map, fromJS} from 'immutable';
let app = module.exports = express(),
configData,
portServer = 3000;
/**
* Configuration
*/
var env = process.env.NODE_ENV || 'development';
if ('development' == env) {
configData = JSON.parse(fs.readFileSync('config.json', 'utf8')).dev;
} else {
configData = process.env;
}
var oa = new OAuth(
"https://api.twitter.com/oauth/request_token",
"https://api.twitter.com/oauth/access_token",
configData.TWITTER_CONSUMER_KEY,
configData.TWITTER_CONSUMER_SECRET,
"1.0A",
configData.TWITTER_CALLBACK_URL,
"HMAC-SHA1"
);
app.set('views', __dirname + '/views');
app.set('view engine', 'jade');
app.use(express.static(__dirname + '/deploy'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
app.use(cookieParser());
app.use(session({ secret: configData.EXPRESS_SESSION_SECRET, resave: true, saveUninitialized: true }));
/**
* Routes
*/
app.get('/', handleRender);
app.post('/auth/twitter', function(req, res) {
oa.getOAuthRequestToken(function(error, oauth_token, oauth_token_secret, results){
if (error) {
console.log(error);
res.send("auth twitter: error")
}
else {
req.session.oauthRequestToken = oauth_token;
req.session.oauthRequestTokenSecret = oauth_token_secret;
req.body.boxShadow = JSON.parse(req.body.boxShadow);
req.session.cssData = req.body;
res.contentType('application/json');
var data = JSON.stringify('https://twitter.com/oauth/authenticate?oauth_token='+oauth_token);
res.header('Content-Length', data.length);
res.end(data);
}
});
});
app.get('/auth/twitter/callback', function(req, res, next){
if (req.query) {
oa.getOAuthAccessToken(req.session.oauthRequestToken, req.session.oauthRequestTokenSecret, req.query.oauth_verifier,
function(error, oauthAccessToken, oauthAccessTokenSecret, results){
if (error){
console.log(error);
res.send("auth twitter callback: error");
} else {
req.session.oauthAccessToken = oauthAccessToken;
req.session.oauthAccessTokenSecret = oauthAccessTokenSecret;
var client = new Twitter({
consumer_key: configData.TWITTER_CONSUMER_KEY,
consumer_secret: configData.TWITTER_CONSUMER_SECRET,
access_token_key: oauthAccessToken,
access_token_secret: oauthAccessTokenSecret
});
var randomName = temp.path({suffix: '.png'}),
imgPath = 'images' + randomName;
drawFromCss(req.session.cssData, imgPath, function() {
// Tweet message and drawing
var data = require('fs').readFileSync(imgPath);
client.post('media/upload', {media: data}, function(error, media, response){
if (!error) {
// If successful, a media object will be returned.
var status = {
status: req.session.cssData.text,
media_ids: media.media_id_string // Pass the media id string
}
client.post('statuses/update', status, function(error, tweet, response){
if (!error) {
// Success
console.log(tweet);
res.redirect('/')
}
fs.unlinkSync(imgPath);
});
} else {
console.log(error);
fs.unlinkSync(imgPath);
}
});
});
}
}
);
} else
next(new Error("auth twitter callback: error"))
});
app.post('/auth/download', function(req, res) {
let randomName = temp.path({suffix: '.png'}),
imgPath = 'images' + randomName;
req.body.boxShadow = JSON.parse(req.body.boxShadow);
drawFromCss(req.body, imgPath, function() {
res.send('/download' + randomName);
});
});
app.get('/download/tmp/:filename', function(req, res) {
console.log('downloaded file: ' + req.params.filename);
let filePath = __dirname + '/images/tmp/' + req.params.filename;
//Stream and delete the file
let stream = fs.createReadStream(filePath, {bufferSize: 64 * 1024});
stream.pipe(res);
let had_error = false;
stream.on('error', function(err){
had_error = true;
});
stream.on('close', function(){
if (!had_error) fs.unlink(filePath);
});
});
app.listen(process.env.PORT || portServer, function(){
console.log("Express server listening on port %d in %s mode", process.env.PORT || portServer, app.settings.env);
});
/**
* Redux helper functions
*/
function handleRender(req, res) {
// Create a new Redux store instance
const store = createStore(undoable(reducer, {
debug: false
}));
//Dispatch initial state
store.dispatch({
type: 'SET_INITIAL_STATE',
state: {}
});
store.dispatch({
type: 'SHOW_SPINNER'
});
// Render the component to a string
const html = renderToString(
<Provider store={store}>
<AppContainer />
</Provider>
);
const initialState = store.getState();
// Send the rendered page back to the client
res.render('index.jade', {reactOutput: html, initialState: JSON.stringify(initialState)});
}
/**
* Draw image with CSS data
*/
function drawFromCss(data, path, callback){
var width = data.cols * data.pixelSize,
height = data.rows * data.pixelSize,
opacity = 0;
data.boxShadow = data.boxShadow.map(function(elem){
return (
{
x: elem[0],
y:elem[1],
color:elem[3]}
)
}
);
let gmImg = gm(width, height, '#000000' + ('0' + Math.round( (1 - opacity) * 255 ).toString(16)).slice(-2));
for (var i = 0; i < data.boxShadow.length; i++) {
var aux = data.boxShadow[i];
gmImg.fill(aux.color).drawRectangle(
aux.x - data.pixelSize, aux.y - data.pixelSize, aux.x, aux.y
);
}
gmImg.write(
path,
function (err) {
if (err) console.log(err);
callback();
}
);
}