-
-
Notifications
You must be signed in to change notification settings - Fork 107
/
generator.js
53 lines (42 loc) · 1.43 KB
/
generator.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
'use strict';
const nunjucks = require('nunjucks');
const env = new nunjucks.Environment();
const { join } = require('path');
const { readFileSync } = require('fs');
const { encodeURL, gravatar } = require('hexo-util');
env.addFilter('uriencode', str => {
return encodeURL(str);
});
env.addFilter('noControlChars', str => {
return str.replace(/[\x00-\x1F\x7F]/g, ''); // eslint-disable-line no-control-regex
});
const atomTmplSrc = join(__dirname, '../atom.xml');
const atomTmpl = nunjucks.compile(readFileSync(atomTmplSrc, 'utf8'), env);
const rss2TmplSrc = join(__dirname, '../rss2.xml');
const rss2Tmpl = nunjucks.compile(readFileSync(rss2TmplSrc, 'utf8'), env);
module.exports = function(locals) {
const config = this.config;
const feedConfig = config.feed;
const template = feedConfig.type === 'rss2' ? rss2Tmpl : atomTmpl;
let posts = locals.posts.sort(feedConfig.order_by || '-date');
posts = posts.filter(post => {
return post.draft !== true;
});
if (feedConfig.limit) posts = posts.limit(feedConfig.limit);
let url = config.url;
if (url[url.length - 1] !== '/') url += '/';
let icon = '';
if (feedConfig.icon) icon = url + encodeURI(feedConfig.icon);
else if (config.email) icon = gravatar(config.email);
const xml = template.render({
config: config,
url: url,
icon: icon,
posts: posts,
feed_url: config.root + feedConfig.path
});
return {
path: feedConfig.path,
data: xml
};
};