v2.0.-1 of newsriver
[rss-reader.git] / src / parsers / rss.ts
1 import Parser from 'rss-parser';
2 import {Feed} from './base';
3
4 function timestamp(str: string): number {
5   const date = +(new Date(str));
6   return Math.floor(date / 1000);
7 }
8
9 function reasonable(dateStr: string): string {
10   const date = new Date(dateStr);
11   const month = date.getMonth() < 10 ? `0${date.getMonth()}` : date.getMonth();
12   const day = date.getDate() < 10 ? `0${date.getDate()}` : date.getDate();
13   return `${date.getFullYear()}-${month}-${day}`;
14 }
15
16 export class RSSParser {
17   parser: Parser;
18   constructor() {
19     this.parser = new Parser;
20   }
21
22   async parse(url: string): Promise<Feed> {
23     const feed = await this.parser.parseURL(url);
24
25     return {
26       title: feed.title || 'Unknown',
27       link: feed.link || 'Unknown',
28       items: feed.items.map(i => {
29         const content = i.content ? i.content : i.description;
30         const title = i.title ? i.title : `Posted on ${reasonable(i.pubDate || (new Date().toString()))}`;
31         return {
32           title: title || 'Unknown',
33           link: i.link || 'Unknown',
34           guid: i.guid || 'Uknown',
35           content: content || 'Unknown',
36           pubDate: (timestamp(i.pubDate || (new Date().toString())))
37         }
38       })
39     }
40   }
41 }