'use strict'; const fsx = require('fs-extra'); const crypto = require('crypto'); const config = require('./config'); const mylog = require('./mylog'); const cdbfetch = require('./cdbfetch'); async function cdbscreens() { let screens = config.screenshots; screens = await Promise.all(screens .map(x => (typeof x === 'string' || x instanceof String) ? { name: x } : x) .map(async x => { if(x.data) x.data = Buffer.from(x.data); else x.data = await fsx.readFile(x.name); return x; })); screens.forEach(x => x.hash = crypto.createHash('sha256') .update(x.data) .digest('base64') .replace(/[^A-Za-z0-9]/g, '') .substr(0, 16)); const shoturl = `${config.root}/packages/${config.user}/${config.pkg}/screenshots/`; mylog('fetching screenshots...'); const resp = await cdbfetch(shoturl); const existing = resp.body; if(JSON.stringify(screens.map(x => x.hash)) === JSON.stringify(existing.map(x => x.title))) return mylog('screenshots up to date'); const tasks = []; const existhash = {}; existing.forEach(s => existhash[s.title] = s); for(let s of screens) if(!existhash[s.hash]) tasks.push((async send => { if(config.dryrun) return mylog(`upload screenshot ${send.hash} DRY RUN`); mylog(`uploading screenshot ${send.hash}...`); await cdbfetch(`${shoturl}new/`, 'post', { title: send.hash, file: { buffer: send.data, filename: send.name, content_type: 'application/octet-stream' } }, { multipart: true }); })(s)); const keephash = {}; screens.forEach(s => keephash[s.hash] = s); for(let s of existing) if(!keephash[s.title]) tasks.push((async rm => { if(config.dryrun) return mylog(`delete screenshot ${rm.id} DRY RUN`); mylog(`delete screenshot ${rm.id}...`) await cdbfetch(`${shoturl}${rm.id}/`, 'delete'); })(s)); if(tasks.length) { await Promise.all(tasks); const resp2 = await cdbfetch(shoturl); Object.keys(existhash) .forEach(k => delete existhash[k]); resp2.body.forEach(s => existhash[s.title] = s); } const ordids = screens.map(s => existhash[s.hash].id); if(config.dryrun) return mylog(`reorder screenshots DRY RUN`); mylog(`reordering screenshots ${JSON.stringify(ordids)}...`); await cdbfetch(`${shoturl}order/`, 'post', ordids, { json: true }); } module.exports = cdbscreens;