cdbrelease/cdbscreens.js

114 lines
2.9 KiB
JavaScript
Raw Normal View History

2020-03-28 11:23:38 -04:00
'use strict';
const util = require('util');
const fs = require('fs');
const crypto = require('crypto');
const config = require('./config');
const cdblib = require('./cdblib');
async function cdbscreens() {
let screens = config.screenshots;
if(typeof screens === 'string' || screens instanceof String)
screens = screens.split(',');
if(!Array.isArray(screens))
screens = [screens];
const loading = [];
screens = screens
.map(x => (typeof x === 'string' || x instanceof String) ? { name: x } : x)
.map(x => {
if(x.data)
x.data = Buffer.from(x.data);
else
loading.push(new Promise((r, j) => fs.readFile(x.name,
(e, d) => e ? j(e) : r(x.data = d))));
return x;
});
await Promise.all(loading);
screens.forEach(x => x.id = crypto.createHash('sha256')
.update(x.data)
.digest('hex'));
const uri = config.root + '/packages/' + config.user + '/' + config.pkg + '/';
console.log('checking existing screenshots...');
const $ = await cdblib.fetch(uri);
const exist = [];
$('.screenshot_list img')
.each((i, e) => exist.push($(e)
.attr('alt')));
let dirty;
let epos = 0;
let spos = 0;
const deletes = [];
while(epos < exist.length && spos < screens.length) {
if(exist[epos] === screens[spos].id)
spos++;
else
deletes.push(epos);
epos++;
}
while(epos < exist.length) {
deletes.push(epos);
epos++;
}
while(spos < screens.length) {
dirty = true;
const scr = screens[spos];
console.log(`uploading ${scr.name || scr.id}...`);
await cdblib.login();
const newuri = uri + 'screenshots/new/';
const $$ = await cdblib.fetch(newuri);
const fields = cdblib.getfields($$);
fields.title = scr.id;
fields.fileUpload = {
buffer: scr.data,
filename: scr.name || scr.id,
content_type: 'application/octet-stream'
};
if(config.dryrun) {
console.log('dry run; not uploading');
console.log(util.inspect(fields));
} else
await cdblib.fetch(newuri, 'post', fields, { multipart: true });
spos++
}
if(deletes.length) {
await cdblib.login();
const $$ = await cdblib.fetch(uri);
const imgids = [];
$$('.screenshot_list a')
.each((i, e) => {
const href = $$(e)
.attr('href');
if(/screenshots\/new/.test(href))
return;
imgids.push(href.match(/screenshots\/(\d+)\/edit/)[1])
});
await Promise.all(deletes
.map(i => imgids[i])
.map(async id => {
dirty = true;
console.log(`deleting screenshot ${id}...`)
const edituri = uri + 'screenshots/' + id + '/edit/';
const $$$ = await cdblib.fetch(edituri);
const fields = cdblib.getfields($$$);
fields.delete = 'y';
delete fields.approved;
console.log(fields);
if(config.dryrun) {
console.log('dry run; not deleting');
console.log(util.inspect(fields));
} else
await cdblib.fetch(edituri, 'post', fields, { multipart: true });
}));
}
console.log('screenshots synced');
return dirty;
}
module.exports = cdbscreens;