You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

89 lines
2.6 KiB

// venue.js
// Copyright (C) 2022 Digital Telepresence, LLC
// License: Apache-2.0
'use strict';
const fetch = require('node-fetch'); // jshint ignore:line
const CACHE_DURATION = 60 * 5;
const { SiteService, SiteError } = require('../../lib/site-lib');
class VenueService extends SiteService {
constructor (dtp) {
super(dtp, module.exports);
}
channelMiddleware ( ) {
return async (req, res, next) => {
try {
if (!res.locals.site || !res.locals.site.shingChannelSlug) {
return next();
}
res.locals.shingChannelFeed = await this.getChannelFeed(res.locals.site.shingChannelSlug, { allowCache: true });
res.locals.shingChannelStatus = await this.getChannelStatus(res.locals.site.shingChannelSlug, { allowCache: true });
this.log.debug('channel status', { status: res.locals.shingChannelStatus });
return next();
} catch (error) {
this.log.error('failed to populate Shing.tv channel feed', { error });
return next();
}
};
}
async getChannelFeed (channelSlug, options) {
const { cache: cacheService } = this.dtp.services;
const cacheKey = `venue:ch:${channelSlug}`;
options = Object.assign({ allowCache: true }, options);
let json;
if (options.allowCache) {
json = await cacheService.getObject(cacheKey);
if (json) { return json; }
}
this.log.info('fetching Shing channel feed', { channelSlug });
const response = await fetch(`https://shing.tv/channel/${channelSlug}/feed/json`);
if (!response.ok) {
throw new SiteError(500, 'Failed to fetch Shing channel feed');
}
json = await response.json();
await cacheService.setObjectEx(cacheKey, CACHE_DURATION, json);
return json;
}
async getChannelStatus (channelSlug, options) {
const { cache: cacheService } = this.dtp.services;
const cacheKey = `venue:ch:${channelSlug}:status`;
options = Object.assign({ allowCache: true }, options);
let json;
if (options.allowCache) {
json = await cacheService.getObject(cacheKey);
if (json) { return json; }
}
this.log.info('fetching Shing channel status', { channelSlug });
const response = await fetch(`https://shing.tv/channel/${channelSlug}/status`);
if (!response.ok) {
throw new SiteError(500, 'Failed to fetch Shing channel status');
}
json = await response.json();
const { channel } = json;
await cacheService.setObjectEx(cacheKey, 10, channel);
return channel;
}
}
module.exports = {
slug: 'venue',
name: 'venue',
create: (dtp) => { return new VenueService(dtp); },
};