-
Notifications
You must be signed in to change notification settings - Fork 5
/
index.js
321 lines (296 loc) · 9.12 KB
/
index.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
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
const express = require('express');
const https = require('https');
const http = require('http');
const fs = require('fs');
const bodyParser = require('body-parser');
const app = express();
const request = require('request');
// create application/json parser
const jsonParser = bodyParser.json();
const dropboxApiUrl = 'https://api.dropboxapi.com/2';
const dropboxContentUrl = 'https://content.dropboxapi.com/2';
const compatibleExtensions = {
'Image' : ['jpg', 'jpeg', 'png'],
'Video': ['mp4'],
'AnimatedGif': ['gif'],
'Folder': [],
// GIFs are currently not supported by Dropbox
// Videos are currently not support by Hootsuite
'': ['jpg', 'jpeg', 'png']
};
const mimeTypes = {
'jpeg': 'image/jpeg',
'jpg': 'image/jpeg',
'png': 'image/png',
'gif': 'image/gif',
'mp4': 'video/mp4'
};
const mediaTypes = {
'jpeg': 'Image',
'jpg': 'Image',
'png': 'Image',
'mp4': 'Video',
'gif': 'AnimatedGif',
};
class Media {
constructor (height = 0, width = 0, url = '', name = '') {
this.id = '';
this.name = name;
var extension = getExtension(name);
this.mediaType = mediaTypes[extension];
this.mimeType = mimeTypes[extension];
this.original = {
url: url,
width: height,
height: width,
sizeInBytes: 0
};
this.thumbnail = {
url: url,
width: width,
height: height,
};
}
}
class Metadata {
constructor (next = '', previous ='') {
this.cursor = {
next: next,
previous: previous
};
}
}
var flatten = arr => {
return arr.reduce((flat, toFlatten) => {
return flat.concat(Array.isArray(toFlatten) ? flatten(toFlatten) : toFlatten);
}, []);
};
var getExtension = fileName => {
var re = /(?:\.([^.]+))?$/;
return re.exec(fileName)[1];
};
var getDropboxDirectUrl = (fileId, authHeader) => {
return new Promise((resolve, reject) => {
var options = {
url: `${dropboxApiUrl}/files/get_temporary_link`,
json: true,
body: {
path: fileId
},
headers: {
'Authorization': authHeader
}
};
request.post(options, (err, response, body) => {
resolve({
id: fileId,
sharedLink: body.link
});
});
});
};
var innerDropboxThumbnails = (fileIds, width, height, authHeader, promises) => {
var currSlice = fileIds.slice(0, 24);
var nextSlice = fileIds.slice(25);
var entries = currSlice.map( fileId => {
return {
path: fileId,
format: 'jpeg',
size: `w${width}h${height}`
};
});
var options = {
url: `${dropboxContentUrl}/files/get_thumbnail_batch`,
json: true,
body: {
entries: entries
},
headers: {
'Authorization': authHeader
}
};
promises.push(new Promise((resolve, reject) => {
request.post(options, (err, response, body) => {
resolve(body.entries.map(entry => {
return {
id: entry.metadata.id,
thumbnail: entry.thumbnail
};
}));
});
}));
if (nextSlice.length == 0) {
return Promise.all(promises).then();
} else {
return innerDropboxThumbnails(nextSlice, width, height, authHeader, promises);
}
};
var flatten = arr => {
return arr.reduce(function (flat, toFlatten) {
return flat.concat(Array.isArray(toFlatten) ? flatten(toFlatten) : toFlatten);
}, []);
};
var getExtension = fileName => {
var re = /(?:\.([^.]+))?$/;
return re.exec(fileName)[1];
};
var getDropboxThumbnails = (fileIds, width, height, authHeader) => {
return new Promise((resolve, reject) => {
resolve(innerDropboxThumbnails(fileIds, width, height, authHeader, []).then());
});
};
var getItemsWithFilter = (folderName = '', authHeader = '', query = '', mediaType = '', cursor) => {
return new Promise((resolve, reject) => {
var options = {
url: `${dropboxApiUrl}/files/list_folder`,
json: true,
body: { },
headers: {
'Authorization': authHeader
}
};
if (cursor) {
options.body = {
cursor: cursor
};
options.url += '/continue';
} else {
options.body = {
path: folderName,
recursive: false,
include_media_info: true,
include_deleted: false,
include_has_explicit_shared_members: false,
include_mounted_folders: true,
};
if (query !== '') {
// search all folders/files if there is a query because you can't currently specify folders
options.body.recursive = true;
} else {
// load a maximum of 20 items at at time
options.body.limit = 20;
}
}
request.post(options, (err, response, body) => {
var folders = body.entries
.filter(item => {
return item['.tag'] === 'folder' && (mediaType === 'Folder' || mediaType === '');
})
// filter for query
.filter(item => {
return item.name.toLowerCase().includes(query.toLowerCase());
});
var compatibleFiles = body.entries
// filter out files with filesizes larger than 5 MB
.filter(item => {
return item.size <= 5 * 1000 * 1000;
})
// filter for mediaType
.filter(item => {
return compatibleExtensions[mediaType].includes(getExtension(item.name));
})
// filter for query
.filter(item => {
return item.name.toLowerCase().includes(query.toLowerCase());
})
// check if it has media_info
.filter(item => {
return item.media_info;
});
var promises = [];
compatibleFiles.forEach(file => {
promises.push(getDropboxDirectUrl(file.id, authHeader));
});
promises.push(getDropboxThumbnails(compatibleFiles.map(file => { return file.path_lower; }), 640, 480, authHeader));
Promise.all(promises).then(data => {
var flatData = flatten(data);
var fileData = folders.map(folderData => {
var folder = new Media();
folder.id = folderData.id;
folder.name = folderData.name;
folder.mediaType = 'Folder';
folder.mimeType = 'application/vnd.hootsuite.folder';
return folder;
});
fileData.push(...compatibleFiles.map(file => {
var filteredData = flatData.filter(item => {
return file.id === item.id;
});
const fileData = Object.assign({}, ...filteredData);
var media = new Media(
(file.media_info) ? file.media_info.metadata.dimensions.height : 0,
(file.media_info) ? file.media_info.metadata.dimensions.width : 0,
fileData.sharedLink,
file.name
);
media.id = file.id;
media.original.sizeInBytes = file.size;
media.thumbnail.url = 'data:image/jpeg;base64, ' + fileData.thumbnail;
return media;
}));
// body.cursor is the next cursor, cursor is the current cursor
var metadata = new Metadata(body.cursor, cursor);
// don't set another cursor if it points to nothing
if (fileData.length === 0 || body.has_more === false) {
metadata.cursor.next = '';
}
resolve({
fileData: fileData,
metadata: metadata
});
});
});
});
};
app.use((req, res, next) => {
console.log(`${req.protocol}://${req.get('host')}${req.originalUrl}`);
return next();
});
app.use(express.static('static'));
app.use(jsonParser);
app.get('/v1/status', (req, res) => {
res.status(200).end();
});
app.post('/webhooks', (req, res) => {
console.log("Webhook content:\n\n%s", JSON.stringify(req.body));
res.status(200).end();
});
app.get('/v1/media', (req, res) => {
var dropboxAuthHeader = req.headers.authorization;
try {
// Once OAuth 2 w/ Dropbox redirect is fixed uncomment this if statement
// if (!dropboxAuthHeader) {
dropboxAuthHeader = 'Bearer ' + process.env.DROPBOX_ACCESS_TOKEN;
// }
} catch (err) {
console.log(err);
}
if (dropboxAuthHeader) {
try {
getItemsWithFilter(req.query.parentId, dropboxAuthHeader, req.query.query, req.query.mediaType, req.query.cursor).then(data => {
res.json({
data: data.fileData,
metadata: data.metadata
});
});
} catch (err) {
res.status(500).send({error: 'error occurred while fetching items'});
}
} else {
res.status(500).send({error: 'dropbox auth header not found'});
}
});
// All Hoosuite apps require HTTPS, so in order to host locally
// you must have some certs. They don't need to be issued by a CA for development,
// but for production they definitely do! Heroku adds its own TLS,
// so you don't have to worry about it as long as TLS is enabled on your Heroku app.
if (fs.existsSync('certs/server.crt') && fs.existsSync('certs/server.key')) {
const certificate = fs.readFileSync('certs/server.crt').toString();
const privateKey = fs.readFileSync('certs/server.key').toString();
const options = {key: privateKey, cert: certificate};
var server = https.createServer(options, app).listen(process.env.PORT || 5000);
console.log(`Example app listening on port ${process.env.PORT || 5000} using HTTPS`);
} else {
var server = http.createServer(app).listen(process.env.PORT || 5000);
console.log(`Example app listening on port ${process.env.PORT || 5000}`);
}