cdbrelease/cdblib.js
2020-03-27 22:22:51 -04:00

91 lines
1.8 KiB
JavaScript

'use strict';
const needle = require('needle');
const cheerio = require('cheerio');
const config = require('./config');
const cookiejar = {};
async function fetch(uri, meth, data, opts, ...rest) {
meth = meth || 'get';
opts = opts || {};
opts.headers = opts.headers || {};
opts.headers.Referer = uri;
opts.cookies = cookiejar;
const r = await needle(meth, uri, data, opts, ...rest);
if(r.cookies)
Object.keys(r.cookies)
.forEach(k => cookiejar[k] = r.cookies[k]);
const $ = cheerio.load(r.body.toString());
let err;
$('h1')
.each(function() {
const t = $(this)
.text();
if(/^\s*Oops!/.test(t))
err = t;
});
if(err)
throw Error(`${uri} returned oops: ${err}`);
return $;
}
function getfields($) {
const fields = {};
$('input')
.each(function() {
const e = $(this);
const n = e.attr('name');
if(!n) return;
const v = e.attr('value');
if(v) fields[n] = v;
});
return fields;
}
async function login_core() {
const uri = config.root + '/user/sign-in';
console.log('fetching sign-in page...');
let $ = await fetch(uri);
const fields = getfields($);
fields.username = config.user;
fields.password = config.pass;
console.log('submitting sign-in form...');
$ = await fetch(uri, 'post', fields);
let success;
$('h1')
.each(function() {
success = success || /^\s*Redirecting\b/i.test($(this)
.text());
});
if(!success)
throw Error('sign-in no redirect: ' + $('body')
.text());
}
let loginprom;
async function login() {
if(!loginprom)
loginprom = login_core();
return await loginprom;
}
function findopt($, sel, name) {
let v;
$(sel)
.each(function() {
const o = $(this);
const t = o.text();
if(t.toLowerCase()
.startsWith(name.toLowerCase()))
v = o.attr('value');
});
return v;
}
module.exports = {
fetch,
getfields,
login,
findopt
};