/** @module root/router */ 'use strict'; // vim: set ts=2 sw=2 et tw=80: const express = require('express'); const router = express.Router(); const mongoose = require('mongoose'); const Favorite = mongoose.model('Favorite'); const fetch = require('node-fetch'); const querystring = require('querystring'); const { error } = require('../utils'); router.get('/', (req, res) => { Favorite.find({}, (err, favs) => { if (err) { return error(err, res); } res.render('index.dust', { favs }); }); }); router.get('/imgur', (req, res) => { if (req.query.access_token) { req.app.locals.imgur = req.query; res.redirect('/'); } else { res.status(200, {'Content-Type': 'text/html'}); res.end(`
`); } }); async function fetchImgur(req, res, method, url, body) { const endpoint = 'https://api.imgur.com/3'; const uploadRes = await fetch(endpoint + url, { method: method, headers: { 'Content-Type': 'application/x-www-form-urlencoded', 'Authorization' : 'Bearer ' + req.app.locals.imgur.access_token }, body: querystring.stringify(body) }); const uploadJson = await uploadRes.json(); if (Math.floor(uploadJson.status / 100) != 2) { res.status(uploadJson.status).json(uploadJson); return false; } console.log(url, uploadJson); return uploadJson; } router.post('/imgur/ordeal', async (req, res) => { try { const uploadData = { image: req.body.dataURL.substring('data:image/png;base64,'.length), type: 'base64', name: req.body.name + '.png', }; const uploadJson = await fetchImgur(req, res, 'POST', '/upload', uploadData); if (!uploadJson) { return; } const imageId = uploadJson.data.id; const albumData = { 'ids[]': imageId, }; if (req.body.album) { albumData.title = req.body.album; } const albumJson = await fetchImgur(req, res, 'POST', '/album', albumData); if (!albumJson) { return; } console.log(req.body.favorites); if (req.body.favorites) { if (!await fetchImgur(req, res, 'POST', '/album/' + albumJson.data.id + '/favorite', {})) { return; } } if (!await fetchImgur(req, res, 'POST', '/gallery/album/' + albumJson.data.id, { title: req.body.album ? req.body.album : req.body.name })) { return; } if (req.body.tags) { const tagsData = { 'tags': req.body.tags }; if (!await fetchImgur(req, res, 'POST', '/gallery/tags/' + albumJson.data.id, tagsData)) { return; } for (const tag of req.body.tags.split(',')) { if (!await fetchImgur(req, res, 'POST', '/account/me/follow/tag/' + tag, {})) { return; } } } res.json({ordealSuccess: true}); } catch(e) { console.error(e); res.status(500).json(e); } }); /** router for /root */ module.exports = router;