const fetch = require("node-fetch") const {render} = require("pinski/plugins") const db = require("../utils/db") const {getToken, getUser} = require("../utils/getuser") const pug = require("pug") const converters = require("../utils/converters") class InstanceError extends Error { constructor(error, identifier) { super(error) this.identifier = identifier } } function formatOrder(format) { // most significant to least significant // key, max, order, transform // asc: lower number comes first, desc: higher number comes first const spec = [ ["second__height", 8000, "desc", x => x ? Math.floor(x/96) : 0], ["fps", 100, "desc", x => x ? Math.floor(x/10) : 0], ["type", " ".repeat(60), "asc", x => x.length], ] let total = 0 for (let i = 0; i < spec.length; i++) { const s = spec[i] let diff = s[3](format[s[0]]) if (s[2] === "asc") diff = s[3](s[1]) - diff total += diff if (i+1 < spec.length) { s2 = spec[i+1] total *= s2[3](s2[1]) } } return -total } module.exports = [ { route: "/watch", methods: ["GET"], code: async ({req, url}) => { const id = url.searchParams.get("v") const user = getUser(req) const settings = user.getSettingsOrDefaults() const outURL = `${settings.instance}/api/v1/videos/${id}` try { const video = await fetch(outURL).then(res => res.json()) if (!video) throw new Error("The instance returned null.") if (video.error) throw new InstanceError(video.error, video.identifier) // video data additional processing for (const format of video.formatStreams.concat(video.adaptiveFormats)) { if (!format.second__height && format.resolution) format.second__height = +format.resolution.slice(0, -1) if (!format.second__order) format.second__order = formatOrder(format) } for (const rec of video.recommendedVideos) { if (!rec.second__lengthText && rec.lengthSeconds > 0) { rec.second__lengthText = converters.lengthSecondsToLengthText(rec.lengthSeconds) } } const subscribed = user.isSubscribed(video.authorId) return render(200, "pug/video.pug", {video, subscribed}) } catch (e) { let message = pug.render("pre= error", {error: e.stack || e.toString()}) if (e instanceof fetch.FetchError) { const template = ` p The selected instance, #[code= instance], did not respond correctly. p Requested URL: #[a(href=url)= url] ` message = pug.render(template, {instance: settings.instance, url: outURL}) } else if (e instanceof InstanceError) { const template = ` p #[strong= error.message] if error.identifier p #[code= error.identifier] p That error was generated by #[code= instance]. ` message = pug.render(template, {instance: settings.instance, error: e}) } return render(500, "pug/video.pug", {video: {videoId: id}, error: true, message}) } } } ]