Repository navigation
Expand file tree
/
Copy pathexamples-ml5.js
More file actions
415 lines (354 loc) · 10.9 KB
/
Copy pathexamples-ml5.js
File metadata and controls
415 lines (354 loc) · 10.9 KB
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
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
import fs from 'fs';
import axios from 'axios';
import Q from 'q';
import { ok } from 'assert';
const branchName = 'main';
const branchRef = `?ref=${branchName}`;
const baseUrl = 'https://api.github.com/repos/ml5js/ml5-library/contents';
const clientId = process.env.GITHUB_ID;
const clientSecret = process.env.GITHUB_SECRET;
const editorUsername = process.env.ML5_LIBRARY_USERNAME;
const personalAccessToken = process.env.EDITOR_API_ACCESS_TOKEN;
const editorApiUrl = process.env.EDITOR_API_URL;
const headers = {
'User-Agent': 'p5js-web-editor/0.0.1'
};
ok(clientId, 'GITHUB_ID is required');
ok(clientSecret, 'GITHUB_SECRET is required');
ok(editorUsername, 'ML5_LIBRARY_USERNAME is required');
ok(personalAccessToken, 'EDITOR_API_ACCESS_TOKEN is required');
ok(editorApiUrl, 'EDITOR_API_URL is required');
//
const githubRequestOptions = {
url: baseUrl,
method: 'GET',
headers: {
...headers,
Authorization: `Basic ${Buffer.from(`${clientId}:${clientSecret}`).toString(
'base64'
)}`
}
};
const editorRequestOptions = {
url: `${editorApiUrl}/${editorUsername}`,
method: 'GET',
headers: {
...headers,
Authorization: `Basic ${Buffer.from(
`${editorUsername}:${personalAccessToken}`
).toString('base64')}`
}
};
/**
* ---------------------------------------------------------
* --------------------- helper functions --------------------
* ---------------------------------------------------------
*/
/**
* fatten a nested array
*/
function flatten(list) {
return list.reduce((a, b) => a.concat(Array.isArray(b) ? flatten(b) : b), []);
}
/**
* Fetch data for a single HTML/JS file, or return
* an url to the file's CDN location
*/
async function fetchFileContent(item) {
const { name } = item;
const file = { url: item.url };
// if it is an html or js file
if ((file.url != null && name.endsWith('.html')) || name.endsWith('.js')) {
const options = Object.assign({}, githubRequestOptions);
options.url = `${file.url}`;
if (
options.url !== undefined ||
options.url !== null ||
options.url !== ''
) {
const { data } = await axios.request(options);
file.content = data;
// NOTE: remove the URL property if there's content
// Otherwise the p5 editor will try to pull from that url
if (file.content !== null) delete file.url;
// Replace localhost references with references to the currently published version.
file.content = file.content.replace(
/http:\/\/localhost(:[0-9]+)\/ml5.js/g,
'https://unpkg.com/ml5@latest/dist/ml5.min.js'
);
}
return file;
// if it is NOT an html or js file
}
if (file.url) {
const cdnRef = `https://cdn.jsdelivr.net/gh/ml5js/ml5-library@${branchName}${
file.url.split(branchName)[1]
}`;
file.url = cdnRef;
}
return file;
}
/**
* STEP 1: Get the top level categories
*/
async function getCategories() {
const options = Object.assign({}, githubRequestOptions);
options.url = `${options.url}/examples/p5js${branchRef}`;
const { data } = await axios.request(options);
return data;
}
/**
* STEP 2: Get the examples for each category
* e.g. Posenet:
* - /posenet_image_single
* - /posenet_part_selection
*/
async function getCategoryExamples(sketchRootList) {
const output = [];
const sketchRootCategories = sketchRootList.map(async (categories) => {
// let options = Object.assign({url: `${requestOptions.url}/${categories.path}${branchRef}`}, requestOptions)
const options = Object.assign({}, githubRequestOptions);
options.url = `${options.url}${categories.path}${branchRef}`;
// console.log(options)
try {
const { data } = await axios.request(options);
const result = flatten(data);
return result;
} catch (err) {
return [];
}
});
const sketchList = await Q.all(sketchRootCategories);
sketchList.forEach((sketch) => {
sketch.forEach((item) => {
if (item.type === 'dir') output.push(item);
});
});
return output;
}
/**
* STEP 3.1: Recursively get the tree of files for each directory
* @param parentObject - one sketch directory object
*/
async function traverseSketchTree(parentObject) {
const output = Object.assign({}, parentObject);
if (parentObject.type !== 'dir') {
return output;
}
// let options = `https://api.github.com/repos/ml5js/ml5-library/contents/examples/p5js/${sketches.path}${branchRef}`
const options = Object.assign({}, githubRequestOptions);
options.url = `${options.url}${parentObject.path}${branchRef}`;
const { data } = await axios.request(options);
output.tree = data;
output.tree = output.tree.map((file) => traverseSketchTree(file));
output.tree = await Q.all(output.tree);
return output;
}
/**
* STEP 3.2: Traverse the sketchtree for all of the sketches
* @param {*} categoryExamples - all of the categories in an array
*/
async function traverseSketchTreeAll(categoryExamples) {
const sketches = categoryExamples.map(async (sketch) =>
traverseSketchTree(sketch)
);
const result = await Q.all(sketches);
return result;
}
/**
* Traverse the tree and format into parent child relation
* @param {*} parentObject
*/
function traverseAndFormat(parentObject) {
const parent = Object.assign({}, parentObject);
if (!parentObject.tree) {
// returns the files
return {
name: parent.name,
url: parent.download_url
};
}
const subdir = parentObject.tree.map((item) => {
if (!item.tree) {
// returns the files
return {
name: item.name,
url: item.download_url
};
}
const feat = {
name: item.name,
children: traverseAndFormat(item)
};
return feat;
});
return subdir;
}
/**
* Traverse the tree and download all the content,
* transforming into an object keyed by file/directory name
* @param {*} projectFileTree
*/
async function traverseAndDownload(projectFileTree) {
return projectFileTree.reduce(async (previousPromise, item, idx) => {
const result = await previousPromise;
if (Array.isArray(item.children)) {
result[item.name] = {
files: await traverseAndDownload(item.children)
};
} else {
result[item.name] = await fetchFileContent(item);
}
return result;
}, {});
}
/**
* STEP 4
* Take a parent directory and prepare it for injestion!
* @param {*} sketch
* @param {*} user
*/
async function formatSketchForStorage(sketch, user) {
const newProject = {
name: sketch.name,
files: {} // <== add files to this object
};
let projectFiles = traverseAndFormat(sketch);
projectFiles = await traverseAndDownload(projectFiles);
newProject.files = projectFiles;
return newProject;
}
/**
* format all the sketches using the formatSketchForStorage()
*/
function formatSketchForStorageAll(sketchWithItems, user) {
let sketchList = sketchWithItems.slice(0);
sketchList = sketchList.map((sketch) => formatSketchForStorage(sketch, user));
return Promise.all(sketchList);
}
/**
* Fetch a list of all projects from the API
*/
async function getProjectsList() {
const options = Object.assign({}, editorRequestOptions);
options.url = `${options.url}/sketches`;
const { data } = await axios.request(options);
return data.sketches;
}
/**
* Delete a project
*/
async function deleteProject(project) {
const options = Object.assign({}, editorRequestOptions);
options.method = 'DELETE';
options.url = `${options.url}/sketches/${project.id}`;
const { data } = await axios.request(options);
return data;
}
/**
* Create a new project
*/
async function createProject(project) {
const options = Object.assign({}, editorRequestOptions);
options.method = 'POST';
options.url = `${options.url}/sketches`;
options.data = project;
const { data } = await axios.request(options);
return data;
}
/**
* STEP 6
* Remove existing projects, then fill the db
* @param {*} filledProjectList
* @param {*} user
*/
async function createProjectsInP5User(filledProjectList, user) {
console.log('Finding existing projects...');
const existingProjects = await getProjectsList();
console.log(`Will delete ${existingProjects.length} projects`);
try {
await Q.all(existingProjects.map(deleteProject));
console.log('deleted old projects!');
} catch (error) {
console.log('Problem deleting projects');
console.log(error);
process.exit(1);
}
try {
const newProjects = filledProjectList.map(async (project) => {
console.log(`saving ${project.name}`);
await createProject(project);
});
await Q.all(newProjects);
console.log(`Projects saved to User: ${editorUsername}!`);
} catch (error) {
console.log('Error saving projects');
console.log(error);
}
}
/**
* ---------------------------------------------------------
* --------------------- main ------------------------------
* ---------------------------------------------------------
*/
/**
* MAKE
* Get all the sketches from the ml5-library repo
* Get the p5 examples
* Dive down into each sketch and get all the files
* Format the sketch files to be save to the db
* Delete existing and save
*/
async function make() {
// Get the categories and their examples
const categories = await getCategories();
const categoryExamples = await getCategoryExamples(categories);
const examplesWithResourceTree = await traverseSketchTreeAll(
categoryExamples
);
const formattedSketchList = await formatSketchForStorageAll(
examplesWithResourceTree
);
await createProjectsInP5User(formattedSketchList);
console.log('done!');
process.exit();
}
/**
* TEST - same as make except reads from file for testing purposes
* Get all the sketches from the ml5-library repo
* Get the p5 examples
* Dive down into each sketch and get all the files
* Format the sketch files to be save to the db
* Delete existing and save
*/
// eslint-disable-next-line no-unused-vars
async function test() {
// read from file while testing
const examplesWithResourceTree = JSON.parse(
fs.readFileSync('./ml5-examplesWithResourceTree.json')
);
const formattedSketchList = await formatSketchForStorageAll(
examplesWithResourceTree
);
await createProjectsInP5User(formattedSketchList);
console.log('done!');
process.exit();
}
/**
* ---------------------------------------------------------
* --------------------- Run -------------------------------
* ---------------------------------------------------------
* Usage:
* If you're testing, change the make() function to test()
* ensure when testing that you've saved some JSON outputs to
* read from so you don't have to make a billion requests all the time
*
* $ GITHUB_ID=<....> GITHUB_SECRET=<...> NODE_ENV=development npm run fetch-examples-ml5
* $ GITHUB_ID=<....> GITHUB_SECRET=<...> npm run fetch-examples-ml5
*/
if (process.env.NODE_ENV === 'development') {
// test();
make(); // replace with test() if you don't want to run all the fetch functions over and over
} else {
make();
}