Skip to content

Instantly share code, notes, and snippets.

@kuu
Last active August 21, 2020 07:22
Show Gist options
  • Save kuu/6eeeec31cd27eb33af5358db840a9dd0 to your computer and use it in GitHub Desktop.
Save kuu/6eeeec31cd27eb33af5358db840a9dd0 to your computer and use it in GitHub Desktop.
Node example for downloading event XMLs

Usage:

$ npx {url of this gist} {hostname} {user} {password} {absolute dir path}

Example:

$ npx https://gist.github.com/kuu/6eeeec31cd27eb33af5358db840a9dd0 192.168.100.230 elemental 'E1ementa!5' `pwd`

File wrote to: /home/kuu/live_event_1.xml
File wrote to: /home/kuu/live_event_2.xml
File wrote to: /home/kuu/live_event_3.xml
#!/usr/bin/env node
const fs = require('fs');
const path = require('path');
const {URL} = require('url');
const qs = require('querystring');
const ElementalApi = require('elemental-api');
const xmlJs = require('xml-js');
const HOST = process.argv[2];
const USER = process.argv[3];
const PASS = process.argv[4];
const DEST = process.argv[5];
const api = new ElementalApi(HOST, USER, PASS);
main();
function main() {
fetchEvents(`http://${HOST}/live_events?per_page=10`)
.then(() => {
console.log('Done');
})
.catch(err => {
console.error(err.stack);
});
}
function unescape(xml) {
xml = decodeURIComponent(xml);
xml = xml.replace('&lt;', '<');
xml = xml.replace('&gt;', '>');
xml = xml.replace('&amp;', '&');
xml = xml.replace('&nbsp;', ' ');
return xml;
}
function fetchEvents(urlStr, promises) {
const {pathname, search} = new URL(urlStr);
const params = search ? qs.parse(search.slice(1)) : {};
return api.get(pathname, params)
.then(xml => {
const unescapedXml = unescape(xml);
const {live_event_list: list} = JSON.parse(xmlJs.xml2json(unescapedXml, {compact: true, sanitize: true}));
if (!promises) {
promises = [];
}
if (list.live_event) {
let itor = list.live_event;
if (typeof itor[Symbol.iterator] !== 'function') {
itor = [itor];
}
for (const {_attributes: event} of itor) {
promises.push(api.get(event.href, {clean: true}).then(writeFile));
}
}
if (list.next) {
return fetchEvents(list.next._attributes.href, promises);
}
return Promise.all(promises);
});
}
function writeFile(xml) {
return new Promise((resolve, reject) => {
const {live_event: event} = JSON.parse(xmlJs.xml2json(xml, {compact: true, sanitize: true}));
const arr = event._attributes.href.split('/');
const id = arr[arr.length - 1];
const filePath = path.join(DEST, `live_event_${id}.xml`);
fs.writeFile(filePath, xml, err => {
if (err) {
return reject(err);
}
console.log(`File wrote to: ${filePath}`);
return resolve();
});
});
}
{
"name": "get-xml",
"version": "1.0.0",
"description": "Node example for downloading event XMLs",
"bin": "./get-xml.js",
"dependencies": {
"elemental-api": "0.0.5",
"xml-js": "^1.6.11"
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment