Professional Documents
Culture Documents
promises;
const RSS = require('rss');
const moment = require('moment');
const _ = require('lodash');
class RSSFeedsService {
constructor(site, options = {}) {
const { baseTargetPath, ttl } = {
baseTargetPath: GENERATED_FILES_PATHS.RSS,
ttl: 30,
...options,
};
if (!site) {
throw new Error('RSSFeedsService: Missing site');
}
if (!site.config) {
throw new Error('RSSFeedsService: Missing site config');
}
if (!site.config.options) {
throw new Error('RSSFeedsService: Missing site options');
}
this.site = site;
this.siteId = site._id;
this.domain = site.domain;
this.siteOptions = site.config.options;
this.rootDirectory = baseTargetPath;
this.targetPath = `${baseTargetPath}/${site._id}.xml`;
this.rssConfiguration = {
isActive: false,
managingEditor: this.siteOptions.siteTitle,
copyright: `${this.siteOptions?.siteTitle}. L’utilisation des flux RSS du
site ${this.domain} est réservée à un usage strictement personnel, non
professionnel et non collectif. Toute autre exploitation doit faire l’objet d’une
autorisation. Contact : ${this.siteOptions?.contactEmail}`,
categories: [],
contentTypes: [],
...(site.config.rssConfiguration || {}),
};
this.contents = [];
async generate() {
if (!this.rssConfiguration.isActive) return;
try {
await fs.access(this.rootDirectory);
} catch (e) {
await fs.mkdir(this.rootDirectory, { recursive: true });
}
contents = _.orderBy(
contents,
['publishStartTs', 'createTs'],
['desc', 'desc']
).slice(0, 20);
await this.#writeRSSFeedsFile();
console.log(
`RSS feed for ${this.siteId} written at path : ${this.targetPath}`
);
}
async #generateContentRSSFeedsItem(content) {
const { label, publishStartTs, image } = content;
this.feed.item({
title: label,
description: content.getDescriptionFormattedHtml
? content.getDescriptionFormattedHtml({ forHeading: true })
: content.description?.html,
url: `${this.site.getFrontUrl()}${path}?utm_medium=rss`,
guid: content._id,
categories: categoryLabels,
author: authorsLabel,
date: moment.unix(publishStartTs),
enclosure: image
? { url: ImageService.getUrl(this.site, image.file) }
: null,
});
}
async #writeRSSFeedsFile() {
try {
await fs.writeFile(this.targetPath, this.feed.xml());
console.log(
`RSS feeds written for ${this.siteId} at path : ${this.targetPath}`
);
return true;
} catch (err) {
console.error(err);
}
}
}
module.exports = RSSFeedsService;