Parse date format correctly in Atom feeds
[citadel.git] / citadel / modules / rssclient / serv_rssclient.c
1 /*
2  * Bring external RSS feeds into rooms.
3  *
4  * Copyright (c) 2007-2017 by the citadel.org team
5  *
6  * This program is open source software; you can redistribute it and/or modify
7  * it under the terms of the GNU General Public License version 3.
8  *
9  * This program is distributed in the hope that it will be useful,
10  * but WITHOUT ANY WARRANTY; without even the implied warranty of
11  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.See the
12  * GNU General Public License for more details.
13  */
14
15 #include <stdlib.h>
16 #include <unistd.h>
17 #include <stdio.h>
18
19 #if TIME_WITH_SYS_TIME
20 # include <sys/time.h>
21 # include <time.h>
22 #else
23 # if HAVE_SYS_TIME_H
24 #include <sys/time.h>
25 # else
26 #include <time.h>
27 # endif
28 #endif
29
30 #include <ctype.h>
31 #include <string.h>
32 #include <errno.h>
33 #include <sys/types.h>
34 #include <sys/stat.h>
35 #include <expat.h>
36 #include <curl/curl.h>
37 #include <libcitadel.h>
38 #include "citadel.h"
39 #include "server.h"
40 #include "citserver.h"
41 #include "support.h"
42 #include "config.h"
43 #include "threads.h"
44 #include "ctdl_module.h"
45 #include "msgbase.h"
46 #include "parsedate.h"
47 #include "database.h"
48 #include "citadel_dirs.h"
49 #include "md5.h"
50 #include "context.h"
51 #include "internet_addressing.h"
52
53 struct rssroom {
54         struct rssroom *next;
55         char *room;
56 };
57
58 struct rssurl {
59         struct rssurl *next;
60         char *url;
61         struct rssroom *rooms;
62 };
63
64 struct rssparser {
65         StrBuf *CData;
66         struct CtdlMessage *msg;
67         char *link;
68         char *description;
69         char *item_id;
70         struct rssroom *rooms;
71 };
72
73 time_t last_run = 0L;
74 struct CitContext rss_CC;
75 struct rssurl *rsstodo = NULL;
76
77
78 // This handler is called whenever an XML tag opens.
79 //
80 void rss_start_element(void *data, const char *el, const char **attribute)
81 {
82         struct rssparser *r = (struct rssparser *)data;
83         int i;
84
85         if (
86                 (!strcasecmp(el, "entry"))
87                 || (!strcasecmp(el, "item"))
88         ) {
89                 // this is the start of a new item(rss) or entry(atom)
90                 if (r->msg != NULL) {
91                         CM_Free(r->msg);
92                         r->msg = NULL;
93                 }
94                 r->msg = malloc(sizeof(struct CtdlMessage));
95                 memset(r->msg, 0, sizeof(struct CtdlMessage));
96                 r->msg->cm_magic = CTDLMESSAGE_MAGIC;
97                 r->msg->cm_anon_type = MES_NORMAL;
98                 r->msg->cm_format_type = FMT_RFC822;
99         }
100
101         else if (!strcasecmp(el, "link")) {                     // atom feeds have the link as an attribute
102                 for(i = 0; attribute[i]; i += 2) {
103                         if (!strcasecmp(attribute[i], "href")) {
104                                 if (r->link != NULL) {
105                                         free(r->link);
106                                         r->link = NULL;
107                                 }
108                                 r->link = strdup(attribute[i+1]);
109                                 striplt(r->link);
110                         }
111                 }
112         }
113 }
114
115
116 // This handler is called whenever an XML tag closes.
117 //
118 void rss_end_element(void *data, const char *el)
119 {
120         struct rssparser *r = (struct rssparser *)data;
121
122         if (                                                    // end of a new item(rss) or entry(atom)
123                 (!strcasecmp(el, "entry"))
124                 || (!strcasecmp(el, "item"))
125         ) {
126
127                 if (r->msg != NULL) {                           // Save the message to the rooms
128
129                         // use the link as an item id if nothing else is available
130                         if ((r->item_id == NULL) && (r->link != NULL)) {
131                                 r->item_id = strdup(r->link);
132                         }
133
134                         // check the use table
135                         StrBuf *u = NewStrBuf();
136                         StrBufAppendPrintf(u, "rss/%s", r->item_id);
137                         time_t already_seen = CheckIfAlreadySeen("rss", u, time(NULL), 604800, eUpdate, 0, 0);
138                         FreeStrBuf(&u);
139
140                         if (already_seen == 0) {
141
142                                 // Compose the message text
143                                 StrBuf *TheMessage = NewStrBuf();
144                                 StrBufAppendPrintf(TheMessage,
145                                         "Content-type: text/html\n\n"
146                                         "\n\n"
147                                         "<html><head></head><body>"
148                                 );
149                 
150                                 if (r->description != NULL) {
151                                         StrBufAppendPrintf(TheMessage, "%s<br><br>\r\n", r->description);
152                                         free(r->description);
153                                         r->description = NULL;
154                                 }
155                 
156                                 if (r->link != NULL) {
157                                         StrBufAppendPrintf(TheMessage, "<a href=\"%s\">%s</a>\r\n", r->link, r->link);
158                                         free(r->link);
159                                         r->link = NULL;
160                                 }
161         
162                                 StrBufAppendPrintf(TheMessage, "</body></html>\r\n");
163                                 CM_SetField(r->msg, eMesageText, ChrPtr(TheMessage), StrLength(TheMessage));
164                                 FreeStrBuf(&TheMessage);
165         
166                                 if (CM_IsEmpty(r->msg, eAuthor)) {
167                                         CM_SetField(r->msg, eAuthor, HKEY("rss"));
168                                 }
169         
170                                 if (CM_IsEmpty(r->msg, eTimestamp)) {
171                                         CM_SetFieldLONG(r->msg, eTimestamp, time(NULL));
172                                 }
173         
174                                 // Save it to the room(s)
175                                 struct rssroom *rr = NULL;
176                                 long msgnum = (-1);
177                                 for (rr=r->rooms; rr!=NULL; rr=rr->next) {
178                                         if (rr == r->rooms) {
179                                                 msgnum = CtdlSubmitMsg(r->msg, NULL, rr->room, 0);
180                                         }
181                                         else {
182                                                 CtdlSaveMsgPointerInRoom(rr->room, msgnum, 0, NULL);
183                                         }
184                                         syslog(LOG_DEBUG, "Saved message %ld to %s", msgnum, rr->room);
185                                 }
186                         }
187                         else {
188                                 syslog(LOG_DEBUG, "%s was already seen %ld seconds ago", r->item_id, already_seen);
189                         }
190         
191                         CM_Free(r->msg);
192                         r->msg = NULL;
193                 }
194
195                 if (r->item_id != NULL) {
196                         free(r->item_id);
197                         r->item_id = NULL;
198                 }
199         }
200
201         else if (!strcasecmp(el, "title")) {                    // item subject (rss and atom)
202                 if ((r->msg != NULL) && (CM_IsEmpty(r->msg, eMsgSubject))) {
203                         CM_SetField(r->msg, eMsgSubject, ChrPtr(r->CData), StrLength(r->CData));
204                         striplt(r->msg->cm_fields[eMsgSubject]);
205                 }
206         }
207
208         else if (!strcasecmp(el, "author")) {                   // author of item (rss and maybe atom)
209                 if ((r->msg != NULL) && (CM_IsEmpty(r->msg, eAuthor))) {
210                         CM_SetField(r->msg, eAuthor, ChrPtr(r->CData), StrLength(r->CData));
211                         striplt(r->msg->cm_fields[eAuthor]);
212                 }
213         }
214
215         else if (!strcasecmp(el, "pubdate")) {                  // date/time stamp (rss) Sat, 25 Feb 2017 14:28:01 EST
216                 if ((r->msg)&&(r->msg->cm_fields[eTimestamp]==NULL)) {
217                         CM_SetFieldLONG(r->msg, eTimestamp, parsedate(ChrPtr(r->CData)));
218                 }
219         }
220
221         else if (!strcasecmp(el, "updated")) {                  // date/time stamp (atom) 2003-12-13T18:30:02Z
222                 if ((r->msg)&&(r->msg->cm_fields[eTimestamp]==NULL)) {
223                         struct tm t;
224                         char zulu;
225                         memset(&t, 0, sizeof t);
226                         sscanf(ChrPtr(r->CData), "%d-%d-%dT%d:%d:%d%c", &t.tm_year, &t.tm_mon, &t.tm_mday, &t.tm_hour, &t.tm_min, &t.tm_sec, &zulu);
227                         t.tm_year -= 1900;
228                         t.tm_mon -= 1;
229                         CM_SetFieldLONG(r->msg, eTimestamp, mktime(&t));
230                 }
231         }
232
233         else if (!strcasecmp(el, "link")) {                     // link to story (rss)
234                 if (r->link != NULL) {
235                         free(r->link);
236                         r->link = NULL;
237                 }
238                 r->link = strdup(ChrPtr(r->CData));
239                 striplt(r->link);
240         }
241
242         else if (
243                 (!strcasecmp(el, "guid"))                       // unique item id (rss)
244                 || (!strcasecmp(el, "id"))                      // unique item id (atom)
245         ) {
246                 if (r->item_id != NULL) {
247                         free(r->item_id);
248                         r->item_id = NULL;
249                 }
250                 r->item_id = strdup(ChrPtr(r->CData));
251                 striplt(r->item_id);
252         }
253
254         else if (
255                 (!strcasecmp(el, "description"))                // message text (rss)
256                 || (!strcasecmp(el, "summary"))                 // message text (atom)
257         ) {
258                 if (r->description != NULL) {
259                         free(r->description);
260                         r->description = NULL;
261                 }
262                 r->description = strdup(ChrPtr(r->CData));
263                 striplt(r->description);
264         }
265
266         if (r->CData != NULL) {
267                 FreeStrBuf(&r->CData);
268                 r->CData = NULL;
269         }
270 }
271
272
273 // This handler is called whenever data appears between opening and closing tags.
274 //
275 void rss_handle_data(void *data, const char *content, int length)
276 {
277         struct rssparser *r = (struct rssparser *)data;
278
279         if (r->CData == NULL) {
280                 r->CData = NewStrBuf();
281         }
282
283         StrBufAppendBufPlain(r->CData, content, length, 0);
284 }
285
286
287 // Feed has been downloaded, now parse it.
288 //
289 void rss_parse_feed(StrBuf *Feed, struct rssroom *rooms)
290 {
291         struct rssparser r;
292
293         memset(&r, 0, sizeof r);
294         r.rooms = rooms;
295         XML_Parser p = XML_ParserCreate("UTF-8");
296         XML_SetElementHandler(p, rss_start_element, rss_end_element);
297         XML_SetCharacterDataHandler(p, rss_handle_data);
298         XML_SetUserData(p, (void *)&r);
299         XML_Parse(p, ChrPtr(Feed), StrLength(Feed), XML_TRUE);
300         XML_ParserFree(p);
301 }
302
303
304 // Add a feed/room pair into the todo list
305 //
306 void rssclient_push_todo(char *rssurl, char *roomname)
307 {
308         struct rssurl *r = NULL;
309         struct rssurl *thisone = NULL;
310         struct rssroom *newroom = NULL;
311
312         syslog(LOG_DEBUG, "rssclient_push_todo(%s, %s)", rssurl, roomname);
313
314         for (r=rsstodo; r!=NULL; r=r->next) {
315                 if (!strcasecmp(r->url, rssurl)) {
316                         thisone = r;
317                 }
318         }
319         if (thisone == NULL) {
320                 thisone = malloc(sizeof(struct rssurl));
321                 thisone->url = strdup(rssurl);
322                 thisone->rooms = NULL;
323                 thisone->next = rsstodo;
324                 rsstodo = thisone;
325         }
326
327         newroom = malloc(sizeof(struct rssroom));
328         newroom->room = strdup(roomname);
329         newroom->next = thisone->rooms;
330         thisone->rooms = newroom;
331 }
332
333
334 // Callback function for curl
335 //
336 size_t rss_pof_write_data(void *buffer, size_t size, size_t nmemb, void *userp)
337 {
338         StrBuf *Downloaded = (StrBuf *)userp;
339         size_t bytes = size * nmemb;
340         StrBufAppendBufPlain(Downloaded, buffer, bytes, 0);
341         return(bytes);
342 }
343
344
345 // pull one feed (possibly multiple rooms)
346 //
347 void rss_pull_one_feed(struct rssurl *url)
348 {
349         CURL *curl;
350         CURLcode res;
351         StrBuf *Downloaded = NULL;
352
353         syslog(LOG_DEBUG, "rss_pull_one_feed(%s)", url->url);
354
355         curl = curl_easy_init();
356         if (!curl) {
357                 return;
358         }
359
360         Downloaded = NewStrBuf();
361
362         curl_easy_setopt(curl, CURLOPT_URL, url->url);
363         curl_easy_setopt(curl, CURLOPT_FOLLOWLOCATION, 1L);                     // Follow redirects
364         curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, rss_pof_write_data);      // What to do with downloaded data
365         curl_easy_setopt(curl, CURLOPT_WRITEDATA, Downloaded);                  // Give it our StrBuf to work with
366         curl_easy_setopt(curl, CURLOPT_TIMEOUT, 20L);                           // Time out after 20 seconds
367         res = curl_easy_perform(curl);                                          // Perform the request
368         if (res != CURLE_OK) {
369                 syslog(LOG_WARNING, "Failed to load feed: %s", curl_easy_strerror(res));
370         }
371         curl_easy_cleanup(curl);
372
373         rss_parse_feed(Downloaded, url->rooms);                                 // parse the feed
374         FreeStrBuf(&Downloaded);                                                // free the downloaded feed data
375 }
376
377
378 // We have a list, now download the feeds
379 //
380 void rss_pull_feeds(void)
381 {
382         struct rssurl *r;
383         struct rssroom *rr;
384
385         while (rsstodo != NULL) {
386                 rss_pull_one_feed(rsstodo);
387                 r = rsstodo;
388                 rsstodo = rsstodo->next;
389                 while (r->rooms != NULL) {
390                         rr = r->rooms;
391                         r->rooms = r->rooms->next;
392                         free(rr->room);
393                         free(rr);
394                 }
395                 free(r->url);
396                 free(r);
397         }
398 }
399
400
401 // Scan a room's netconfig looking for RSS feed parsing requests
402 //
403 void rssclient_scan_room(struct ctdlroom *qrbuf, void *data)
404 {
405         char *serialized_config = NULL;
406         int num_configs = 0;
407         char cfgline[SIZ];
408         int i = 0;
409
410         serialized_config = LoadRoomNetConfigFile(qrbuf->QRnumber);
411         if (!serialized_config) {
412                 return;
413         }
414
415         num_configs = num_tokens(serialized_config, '\n');
416         for (i=0; i<num_configs; ++i) {
417                 extract_token(cfgline, serialized_config, i, '\n', sizeof cfgline);
418                 if (!strncasecmp(cfgline, HKEY("rssclient|"))) {
419                         strcpy(cfgline, &cfgline[10]);
420                         char *vbar = strchr(cfgline, '|');
421                         if (vbar != NULL) {
422                                 *vbar = 0;
423                         }
424                         rssclient_push_todo(cfgline, qrbuf->QRname);
425                 }
426         }
427
428         free(serialized_config);
429 }
430
431
432 /*
433  * Scan for rooms that have RSS client requests configured
434  */
435 void rssclient_scan(void) {
436         time_t now = time(NULL);
437
438         /* Run no more than once every 15 minutes. */
439         if ((now - last_run) < 900) {
440                 syslog(LOG_DEBUG,
441                         "Client: polling interval not yet reached; last run was %ldm%lds ago",
442                         ((now - last_run) / 60),
443                         ((now - last_run) % 60)
444                 );
445                 return;
446         }
447
448         become_session(&rss_CC);
449         syslog(LOG_DEBUG, "rssclient started");
450         CtdlForEachRoom(rssclient_scan_room, NULL);
451         rss_pull_feeds();
452         syslog(LOG_DEBUG, "rssclient ended");
453         last_run = time(NULL);
454         return;
455 }
456
457
458 CTDL_MODULE_INIT(rssclient)
459 {
460         if (!threading)
461         {
462                 syslog(LOG_INFO, "%s", curl_version());
463                 CtdlRegisterSessionHook(rssclient_scan, EVT_TIMER, PRIO_AGGR + 300);
464         }
465         else
466         {
467                 CtdlFillSystemContext(&rss_CC, "rssclient");
468         }
469         return "rssclient";
470 }
471