2 * Bring external RSS feeds into rooms.
4 * Copyright (c) 2007-2010 by the citadel.org team
6 * This program is free software; you can redistribute it and/or modify
7 * it under the terms of the GNU General Public License as published by
8 * the Free Software Foundation; either version 3 of the License, or
9 * (at your option) any later version.
11 * This program is distributed in the hope that it will be useful,
12 * but WITHOUT ANY WARRANTY; without even the implied warranty of
13 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 * GNU General Public License for more details.
16 * You should have received a copy of the GNU General Public License
17 * along with this program; if not, write to the Free Software
18 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
25 #if TIME_WITH_SYS_TIME
26 # include <sys/time.h>
30 # include <sys/time.h>
39 #include <sys/types.h>
42 #include <curl/curl.h>
43 #include <libcitadel.h>
46 #include "citserver.h"
50 #include "ctdl_module.h"
52 #include "parsedate.h"
54 #include "citadel_dirs.h"
57 #include "event_client.h"
58 #include "rss_atom_parser.h"
61 #define TMP_MSGDATA 0xFF
62 #define TMP_SHORTER_URL_OFFSET 0xFE
63 #define TMP_SHORTER_URLS 0xFD
67 pthread_mutex_t RSSQueueMutex; /* locks the access to the following vars: */
68 HashList *RSSQueueRooms = NULL; /* rss_room_counter */
69 HashList *RSSFetchUrls = NULL; /* -> rss_aggregator; ->RefCount access to be locked too. */
71 eNextState RSSAggregatorTerminate(AsyncIO *IO);
73 struct CitContext rss_CC;
75 struct rssnetcfg *rnclist = NULL;
76 void AppendLink(StrBuf *Message, StrBuf *link, StrBuf *LinkTitle, const char *Title)
78 if (StrLength(link) > 0)
80 StrBufAppendBufPlain(Message, HKEY("<a href=\""), 0);
81 StrBufAppendBuf(Message, link, 0);
82 StrBufAppendBufPlain(Message, HKEY("\">"), 0);
83 if (StrLength(LinkTitle) > 0)
84 StrBufAppendBuf(Message, LinkTitle, 0);
85 else if ((Title != NULL) && !IsEmptyStr(Title))
86 StrBufAppendBufPlain(Message, Title, -1, 0);
88 StrBufAppendBuf(Message, link, 0);
89 StrBufAppendBufPlain(Message, HKEY("</a><br>\n"), 0);
92 typedef struct __networker_save_message {
94 struct CtdlMessage *Msg;
95 struct recptypes *recp;
100 } networker_save_message;
103 void DeleteRoomReference(long QRnumber)
109 rss_room_counter *pRoomC;
111 At = GetNewHashPos(RSSQueueRooms, 0);
113 GetHashPosFromKey(RSSQueueRooms, LKEY(QRnumber), At);
114 GetHashPos(RSSQueueRooms, At, &HKLen, &HK, &vData);
117 pRoomC = (rss_room_counter *) vData;
119 if (pRoomC->count == 0)
120 DeleteEntryFromHash(RSSQueueRooms, At);
125 void UnlinkRooms(rss_aggregator *Cfg)
128 DeleteRoomReference(Cfg->QRnumber);
129 if (Cfg->OtherQRnumbers != NULL)
136 At = GetNewHashPos(Cfg->OtherQRnumbers, 0);
137 while (GetNextHashPos(Cfg->OtherQRnumbers, At, &HKLen, &HK, &vData) &&
140 long *lData = (long*) vData;
141 DeleteRoomReference(*lData);
144 if (server_shutting_down)
151 void UnlinkRSSAggregator(rss_aggregator *Cfg)
157 At = GetNewHashPos(RSSFetchUrls, 0);
158 if (GetHashPosFromKey(RSSFetchUrls, SKEY(Cfg->Url), At) == 0)
160 DeleteEntryFromHash(RSSFetchUrls, At);
163 last_run = time(NULL);
166 eNextState FreeNetworkSaveMessage (AsyncIO *IO)
168 networker_save_message *Ctx = (networker_save_message *) IO->Data;
170 pthread_mutex_lock(&RSSQueueMutex);
171 Ctx->Cfg->RefCount --;
173 if (Ctx->Cfg->RefCount == 0)
175 UnlinkRSSAggregator(Ctx->Cfg);
178 pthread_mutex_unlock(&RSSQueueMutex);
180 CtdlFreeMessage(Ctx->Msg);
181 free_recipients(Ctx->recp);
182 FreeStrBuf(&Ctx->Message);
183 FreeStrBuf(&Ctx->MsgGUID);
185 last_run = time(NULL);
189 eNextState AbortNetworkSaveMessage (AsyncIO *IO)
191 return eAbort; ///TODO
194 eNextState RSSSaveMessage(AsyncIO *IO)
196 networker_save_message *Ctx = (networker_save_message *) IO->Data;
198 Ctx->Msg->cm_fields['M'] = SmashStrBuf(&Ctx->Message);
200 CtdlSubmitMsg(Ctx->Msg, Ctx->recp, NULL, 0);
202 /* write the uidl to the use table so we don't store this item again */
203 cdb_store(CDB_USETABLE, SKEY(Ctx->MsgGUID), &Ctx->ut, sizeof(struct UseTable) );
205 return eTerminateConnection;
208 eNextState RSS_FetchNetworkUsetableEntry(AsyncIO *IO)
210 struct cdbdata *cdbut;
211 networker_save_message *Ctx = (networker_save_message *) IO->Data;
213 /* Find out if we've already seen this item */
214 strcpy(Ctx->ut.ut_msgid, ChrPtr(Ctx->MsgGUID)); /// TODO
215 Ctx->ut.ut_timestamp = time(NULL);
217 cdbut = cdb_fetch(CDB_USETABLE, SKEY(Ctx->MsgGUID));
220 /* Item has already been seen */
221 syslog(LOG_DEBUG, "%s has already been seen\n", ChrPtr(Ctx->MsgGUID));
224 /* rewrite the record anyway, to update the timestamp */
225 cdb_store(CDB_USETABLE,
227 &Ctx->ut, sizeof(struct UseTable) );
233 NextDBOperation(IO, RSSSaveMessage);
237 void RSSQueueSaveMessage(struct CtdlMessage *Msg, struct recptypes *recp, StrBuf *MsgGUID, StrBuf *MessageBody, rss_aggregator *Cfg)
239 networker_save_message *Ctx;
241 Ctx = (networker_save_message *) malloc(sizeof(networker_save_message));
242 memset(Ctx, 0, sizeof(networker_save_message));
244 Ctx->MsgGUID = MsgGUID;
245 Ctx->Message = MessageBody;
250 Ctx->IO.CitContext = CloneContext(&rss_CC);
251 Ctx->IO.Terminate = FreeNetworkSaveMessage;
252 Ctx->IO.ShutdownAbort = AbortNetworkSaveMessage;
253 QueueDBOperation(&Ctx->IO, RSS_FetchNetworkUsetableEntry);
258 * Commit a fetched and parsed RSS item to disk
260 void rss_save_item(rss_item *ri, rss_aggregator *Cfg)
263 struct MD5Context md5context;
264 u_char rawdigest[MD5_DIGEST_LEN];
265 struct CtdlMessage *msg;
266 struct recptypes *recp = NULL;
272 recp = (struct recptypes *) malloc(sizeof(struct recptypes));
273 if (recp == NULL) return;
274 memset(recp, 0, sizeof(struct recptypes));
275 Buf = NewStrBufDup(Cfg->rooms);
276 recp->recp_room = SmashStrBuf(&Buf);
277 recp->num_room = Cfg->roomlist_parts;
278 recp->recptypes_magic = RECPTYPES_MAGIC;
281 /* Construct a GUID to use in the S_USETABLE table.
282 * If one is not present in the item itself, make one up.
284 if (ri->guid != NULL) {
285 StrBufSpaceToBlank(ri->guid);
286 StrBufTrim(ri->guid);
287 guid = NewStrBufPlain(HKEY("rss/"));
288 StrBufAppendBuf(guid, ri->guid, 0);
291 MD5Init(&md5context);
292 if (ri->title != NULL) {
293 MD5Update(&md5context, (const unsigned char*)ChrPtr(ri->title), StrLength(ri->title));
295 if (ri->link != NULL) {
296 MD5Update(&md5context, (const unsigned char*)ChrPtr(ri->link), StrLength(ri->link));
298 MD5Final(rawdigest, &md5context);
299 guid = NewStrBufPlain(NULL, MD5_DIGEST_LEN * 2 + 12 /* _rss2ctdl*/);
300 StrBufHexEscAppend(guid, NULL, rawdigest, MD5_DIGEST_LEN);
301 StrBufAppendBufPlain(guid, HKEY("_rss2ctdl"), 0);
304 /* translate Item into message. */
305 syslog(LOG_DEBUG, "RSS: translating item...\n");
306 if (ri->description == NULL) ri->description = NewStrBufPlain(HKEY(""));
307 StrBufSpaceToBlank(ri->description);
308 msg = malloc(sizeof(struct CtdlMessage));
309 memset(msg, 0, sizeof(struct CtdlMessage));
310 msg->cm_magic = CTDLMESSAGE_MAGIC;
311 msg->cm_anon_type = MES_NORMAL;
312 msg->cm_format_type = FMT_RFC822;
314 if (ri->guid != NULL) {
315 msg->cm_fields['E'] = strdup(ChrPtr(ri->guid));
318 if (ri->author_or_creator != NULL) {
320 StrBuf *Encoded = NULL;
323 From = html_to_ascii(ChrPtr(ri->author_or_creator),
324 StrLength(ri->author_or_creator),
326 StrBufPlain(ri->author_or_creator, From, -1);
327 StrBufTrim(ri->author_or_creator);
330 FromAt = strchr(ChrPtr(ri->author_or_creator), '@') != NULL;
331 if (!FromAt && StrLength (ri->author_email) > 0)
333 StrBufRFC2047encode(&Encoded, ri->author_or_creator);
334 msg->cm_fields['A'] = SmashStrBuf(&Encoded);
335 msg->cm_fields['P'] = SmashStrBuf(&ri->author_email);
341 msg->cm_fields['A'] = SmashStrBuf(&ri->author_or_creator);
342 msg->cm_fields['P'] = strdup(msg->cm_fields['A']);
346 StrBufRFC2047encode(&Encoded, ri->author_or_creator);
347 msg->cm_fields['A'] = SmashStrBuf(&Encoded);
348 msg->cm_fields['P'] = strdup("rss@localhost");
351 if (ri->pubdate <= 0) {
352 ri->pubdate = time(NULL);
357 msg->cm_fields['A'] = strdup("rss");
360 msg->cm_fields['N'] = strdup(NODENAME);
361 if (ri->title != NULL) {
364 StrBuf *Encoded, *QPEncoded;
367 StrBufSpaceToBlank(ri->title);
368 len = StrLength(ri->title);
369 Sbj = html_to_ascii(ChrPtr(ri->title), len, 512, 0);
371 if (Sbj[len - 1] == '\n')
376 Encoded = NewStrBufPlain(Sbj, len);
380 StrBufRFC2047encode(&QPEncoded, Encoded);
382 msg->cm_fields['U'] = SmashStrBuf(&QPEncoded);
383 FreeStrBuf(&Encoded);
385 msg->cm_fields['T'] = malloc(64);
386 snprintf(msg->cm_fields['T'], 64, "%ld", ri->pubdate);
387 if (ri->channel_title != NULL) {
388 if (StrLength(ri->channel_title) > 0) {
389 msg->cm_fields['O'] = strdup(ChrPtr(ri->channel_title));
392 if (ri->link == NULL)
393 ri->link = NewStrBufPlain(HKEY(""));
395 #if 0 /* temporarily disable shorter urls. */
396 msg->cm_fields[TMP_SHORTER_URLS] = GetShorterUrls(ri->description);
399 msglen += 1024 + StrLength(ri->link) + StrLength(ri->description) ;
401 Message = NewStrBufPlain(NULL, StrLength(ri->description));
403 StrBufPlain(Message, HKEY(
404 "Content-type: text/html; charset=\"UTF-8\"\r\n\r\n"
406 #if 0 /* disable shorter url for now. */
407 msg->cm_fields[TMP_SHORTER_URL_OFFSET] = StrLength(Message);
409 StrBufAppendBuf(Message, ri->description, 0);
410 StrBufAppendBufPlain(Message, HKEY("<br><br>\n"), 0);
412 AppendLink(Message, ri->link, ri->linkTitle, NULL);
413 AppendLink(Message, ri->reLink, ri->reLinkTitle, "Reply to this");
414 StrBufAppendBufPlain(Message, HKEY("</body></html>\n"), 0);
416 RSSQueueSaveMessage(msg, recp, guid, Message, Cfg);
424 int rss_do_fetching(rss_aggregator *Cfg)
433 if ((Cfg->next_poll != 0) && (now < Cfg->next_poll))
437 ri = (rss_item*) malloc(sizeof(rss_item));
438 memset(ri, 0, sizeof(rss_item));
441 IO->CitContext = CloneContext(&rss_CC);
445 syslog(LOG_DEBUG, "Fetching RSS feed <%s>\n", ChrPtr(Cfg->Url));
446 ParseURL(&IO->ConnectMe, Cfg->Url, 80);
447 CurlPrepareURL(IO->ConnectMe);
449 if (! evcurl_init(IO,
452 "Citadel RSS Client",
454 RSSAggregatorTerminate))
456 syslog(LOG_DEBUG, "Unable to initialize libcurl.\n");
460 evcurl_handle_start(IO);
465 void DeleteRssCfg(void *vptr)
467 rss_aggregator *rncptr = (rss_aggregator *)vptr;
469 FreeStrBuf(&rncptr->Url);
470 FreeStrBuf(&rncptr->rooms);
471 FreeStrBuf(&rncptr->CData);
472 FreeStrBuf(&rncptr->Key);
473 FreeStrBuf(&rncptr->IO.HttpReq.ReplyData);
474 DeleteHash(&rncptr->OtherQRnumbers);
475 FreeURL(&rncptr->IO.ConnectMe);
477 if (rncptr->Item != NULL)
479 FreeStrBuf(&rncptr->Item->guid);
480 FreeStrBuf(&rncptr->Item->title);
481 FreeStrBuf(&rncptr->Item->link);
482 FreeStrBuf(&rncptr->Item->linkTitle);
483 FreeStrBuf(&rncptr->Item->reLink);
484 FreeStrBuf(&rncptr->Item->reLinkTitle);
485 FreeStrBuf(&rncptr->Item->description);
486 FreeStrBuf(&rncptr->Item->channel_title);
487 FreeStrBuf(&rncptr->Item->author_or_creator);
488 FreeStrBuf(&rncptr->Item->author_url);
489 FreeStrBuf(&rncptr->Item->author_email);
496 eNextState RSSAggregatorTerminate(AsyncIO *IO)
498 rss_aggregator *rncptr = (rss_aggregator *)IO->Data;
505 pthread_mutex_lock(&RSSQueueMutex);
507 if (rncptr->RefCount == 0)
509 UnlinkRSSAggregator(rncptr);
512 pthread_mutex_unlock(&RSSQueueMutex);
514 At = GetNewHashPos(RSSFetchUrls, 0);
516 pthread_mutex_lock(&RSSQueueMutex);
517 GetHashPosFromKey(RSSFetchUrls, SKEY(rncptr->Url), At);
518 GetHashPos(RSSFetchUrls, At, &HKLen, &HK, &vData);
519 DeleteEntryFromHash(RSSFetchUrls, At);
520 pthread_mutex_unlock(&RSSQueueMutex);
528 * Scan a room's netconfig to determine whether it is requesting any RSS feeds
530 void rssclient_scan_room(struct ctdlroom *qrbuf, void *data)
532 StrBuf *CfgData=NULL;
535 rss_room_counter *Count = NULL;
537 char filename[PATH_MAX];
540 rss_aggregator *rncptr = NULL;
541 rss_aggregator *use_this_rncptr = NULL;
543 const char *CfgPtr, *lPtr;
546 pthread_mutex_lock(&RSSQueueMutex);
547 if (GetHash(RSSQueueRooms, LKEY(qrbuf->QRnumber), &vptr))
550 "rssclient: [%ld] %s already in progress.\n",
553 pthread_mutex_unlock(&RSSQueueMutex);
556 pthread_mutex_unlock(&RSSQueueMutex);
558 assoc_file_name(filename, sizeof filename, qrbuf, ctdl_netcfg_dir);
560 if (server_shutting_down)
563 /* Only do net processing for rooms that have netconfigs */
564 fd = open(filename, 0);
566 //syslog(LOG_DEBUG, "rssclient: %s no config.\n", qrbuf->QRname);
570 if (server_shutting_down)
573 if (fstat(fd, &statbuf) == -1) {
574 syslog(LOG_DEBUG, "ERROR: could not stat configfile '%s' - %s\n",
575 filename, strerror(errno));
579 if (server_shutting_down)
582 CfgData = NewStrBufPlain(NULL, statbuf.st_size + 1);
584 if (StrBufReadBLOB(CfgData, &fd, 1, statbuf.st_size, &Err) < 0) {
586 FreeStrBuf(&CfgData);
587 syslog(LOG_DEBUG, "ERROR: reading config '%s' - %s<br>\n",
588 filename, strerror(errno));
592 if (server_shutting_down)
596 CfgType = NewStrBuf();
597 Line = NewStrBufPlain(NULL, StrLength(CfgData));
601 Done = StrBufSipLine(Line, CfgData, &CfgPtr) == 0;
602 if (StrLength(Line) > 0)
605 StrBufExtract_NextToken(CfgType, Line, &lPtr, '|');
606 if (!strcasecmp("rssclient", ChrPtr(CfgType)))
610 Count = malloc(sizeof(rss_room_counter));
614 rncptr = (rss_aggregator *) malloc(sizeof(rss_aggregator));
615 memset (rncptr, 0, sizeof(rss_aggregator));
616 rncptr->roomlist_parts = 1;
617 rncptr->Url = NewStrBuf();
618 StrBufExtract_NextToken(rncptr->Url, Line, &lPtr, '|');
620 pthread_mutex_lock(&RSSQueueMutex);
621 GetHash(RSSFetchUrls, SKEY(rncptr->Url), &vptr);
622 use_this_rncptr = (rss_aggregator *)vptr;
623 if (use_this_rncptr != NULL)
625 /* mustn't attach to an active session */
626 if (use_this_rncptr->RefCount > 0)
628 DeleteRssCfg(rncptr);
634 StrBufAppendBufPlain(use_this_rncptr->rooms,
637 if (use_this_rncptr->roomlist_parts == 1)
639 use_this_rncptr->OtherQRnumbers = NewHash(1, lFlathash);
641 QRnumber = (long*)malloc(sizeof(long));
642 *QRnumber = qrbuf->QRnumber;
643 Put(use_this_rncptr->OtherQRnumbers, LKEY(qrbuf->QRnumber), QRnumber, NULL);
644 use_this_rncptr->roomlist_parts++;
646 pthread_mutex_unlock(&RSSQueueMutex);
649 FreeStrBuf(&rncptr->Url);
654 pthread_mutex_unlock(&RSSQueueMutex);
656 rncptr->ItemType = RSS_UNSET;
658 rncptr->rooms = NewStrBufPlain(qrbuf->QRname, -1);
660 pthread_mutex_lock(&RSSQueueMutex);
661 Put(RSSFetchUrls, SKEY(rncptr->Url), rncptr, DeleteRssCfg);
662 pthread_mutex_unlock(&RSSQueueMutex);
668 Count->QRnumber = qrbuf->QRnumber;
669 pthread_mutex_lock(&RSSQueueMutex);
670 syslog(LOG_DEBUG, "rssclient: [%ld] %s now starting.\n",
671 qrbuf->QRnumber, qrbuf->QRname);
672 Put(RSSQueueRooms, LKEY(qrbuf->QRnumber), Count, NULL);
673 pthread_mutex_unlock(&RSSQueueMutex);
675 FreeStrBuf(&CfgData);
676 FreeStrBuf(&CfgType);
681 * Scan for rooms that have RSS client requests configured
683 void rssclient_scan(void) {
684 static int doing_rssclient = 0;
685 rss_aggregator *rptr = NULL;
691 /* Run no more than once every 15 minutes. */
692 if ((time(NULL) - last_run) < 900) {
697 * This is a simple concurrency check to make sure only one rssclient run
698 * is done at a time. We could do this with a mutex, but since we
699 * don't really require extremely fine granularity here, we'll do it
700 * with a static variable instead.
702 if (doing_rssclient) return;
705 syslog(LOG_DEBUG, "rssclient started\n");
706 CtdlForEachRoom(rssclient_scan_room, NULL);
708 pthread_mutex_lock(&RSSQueueMutex);
710 it = GetNewHashPos(RSSFetchUrls, 0);
711 while (!server_shutting_down &&
712 GetNextHashPos(RSSFetchUrls, it, &len, &Key, &vrptr) &&
714 rptr = (rss_aggregator *)vrptr;
715 if (rptr->RefCount == 0)
716 if (!rss_do_fetching(rptr))
717 UnlinkRSSAggregator(rptr);
720 pthread_mutex_unlock(&RSSQueueMutex);
722 syslog(LOG_DEBUG, "rssclient ended\n");
727 void rss_cleanup(void)
729 /* citthread_mutex_destroy(&RSSQueueMutex); TODO */
730 DeleteHash(&RSSFetchUrls);
731 DeleteHash(&RSSQueueRooms);
735 CTDL_MODULE_INIT(rssclient)
739 CtdlFillSystemContext(&rss_CC, "rssclient");
740 pthread_mutex_init(&RSSQueueMutex, NULL);
741 RSSQueueRooms = NewHash(1, lFlathash);
742 RSSFetchUrls = NewHash(1, NULL);
743 syslog(LOG_INFO, "%s\n", curl_version());
744 CtdlRegisterSessionHook(rssclient_scan, EVT_TIMER);
745 CtdlRegisterCleanupHook(rss_cleanup);