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);
94 void DeleteRoomReference(long QRnumber)
100 rss_room_counter *pRoomC;
102 At = GetNewHashPos(RSSQueueRooms, 0);
104 GetHashPosFromKey(RSSQueueRooms, LKEY(QRnumber), At);
105 GetHashPos(RSSQueueRooms, At, &HKLen, &HK, &vData);
108 pRoomC = (rss_room_counter *) vData;
110 if (pRoomC->count == 0)
111 DeleteEntryFromHash(RSSQueueRooms, At);
116 void UnlinkRooms(rss_aggregator *Cfg)
119 DeleteRoomReference(Cfg->QRnumber);
120 if (Cfg->OtherQRnumbers != NULL)
127 At = GetNewHashPos(Cfg->OtherQRnumbers, 0);
128 while (GetNextHashPos(Cfg->OtherQRnumbers, At, &HKLen, &HK, &vData) &&
131 long *lData = (long*) vData;
132 DeleteRoomReference(*lData);
135 if (server_shutting_down)
142 void UnlinkRSSAggregator(rss_aggregator *Cfg)
148 At = GetNewHashPos(RSSFetchUrls, 0);
149 if (GetHashPosFromKey(RSSFetchUrls, SKEY(Cfg->Url), At) == 0)
151 DeleteEntryFromHash(RSSFetchUrls, At);
154 last_run = time(NULL);
157 eNextState FreeNetworkSaveMessage (AsyncIO *IO)
159 networker_save_message *Ctx = (networker_save_message *) IO->Data;
161 pthread_mutex_lock(&RSSQueueMutex);
162 Ctx->Cfg->RefCount --;
164 if (Ctx->Cfg->RefCount == 0)
166 UnlinkRSSAggregator(Ctx->Cfg);
169 pthread_mutex_unlock(&RSSQueueMutex);
171 CtdlFreeMessage(Ctx->Msg);
172 free_recipients(Ctx->recp);
173 FreeStrBuf(&Ctx->Message);
174 FreeStrBuf(&Ctx->MsgGUID);
175 ((struct CitContext*)IO->CitContext)->state = CON_IDLE;
176 ((struct CitContext*)IO->CitContext)->kill_me = 1;
178 last_run = time(NULL);
182 void FreeNetworkSaveMessage (void *vMsg)
184 networker_save_message *Msg = (networker_save_message *) vMsg;
186 CtdlFreeMessage(Msg->Msg);
187 FreeStrBuf(&Msg->Message);
188 FreeStrBuf(&Msg->MsgGUID);
192 eNextState AbortNetworkSaveMessage (AsyncIO *IO)
194 return eAbort; ///TODO
197 eNextState RSSSaveMessage(AsyncIO *IO)
201 rss_aggregator *Ctx = (rss_aggregator *) IO->Data;
203 Ctx->ThisMsg->Msg->cm_fields['M'] = SmashStrBuf(&Ctx->ThisMsg->Message);
205 CtdlSubmitMsg(Ctx->ThisMsg->Msg, &Ctx->recp, NULL, 0);
207 /* write the uidl to the use table so we don't store this item again */
208 cdb_store(CDB_USETABLE, SKEY(Ctx->ThisMsg->MsgGUID), &Ctx->ThisMsg->ut, sizeof(struct UseTable) );
210 if (GetNextHashPos(Ctx->Messages, Ctx->Pos, &len, &Key, (void**) &Ctx->ThisMsg))
211 return NextDBOperation(IO, RSS_FetchNetworkUsetableEntry);
216 eNextState RSS_FetchNetworkUsetableEntry(AsyncIO *IO)
220 struct cdbdata *cdbut;
221 rss_aggregator *Ctx = (rss_aggregator *) IO->Data;
224 /* Find out if we've already seen this item */
225 strcpy(Ctx->ThisMsg->ut.ut_msgid, ChrPtr(Ctx->ThisMsg->MsgGUID)); /// TODO
226 Ctx->ThisMsg->ut.ut_timestamp = time(NULL);
228 cdbut = cdb_fetch(CDB_USETABLE, SKEY(Ctx->ThisMsg->MsgGUID));
231 /* Item has already been seen */
232 EV_syslog(LOG_DEBUG, "%s has already been seen\n", ChrPtr(Ctx->ThisMsg->MsgGUID));
235 /* rewrite the record anyway, to update the timestamp */
236 cdb_store(CDB_USETABLE,
237 SKEY(Ctx->ThisMsg->MsgGUID),
238 &Ctx->ThisMsg->ut, sizeof(struct UseTable) );
240 if (GetNextHashPos(Ctx->Messages, Ctx->Pos, &len, &Key, (void**) &Ctx->ThisMsg))
241 return NextDBOperation(IO, RSS_FetchNetworkUsetableEntry);
248 NextDBOperation(IO, RSSSaveMessage);
253 void RSSAddSaveMessage(struct CtdlMessage *Msg, struct recptypes *recp, StrBuf *MsgGUID, StrBuf *MessageBody, rss_aggregat *Cfg)
255 networker_save_message *Ctx;
257 pthread_mutex_lock(&RSSQueueMutex);
259 pthread_mutex_unlock(&RSSQueueMutex);
262 Ctx = (networker_save_message *) malloc(sizeof(networker_save_message));
263 memset(Ctx, 0, sizeof(networker_save_message));
265 Ctx->MsgGUID = MsgGUID;
266 Ctx->Message = MessageBody;
271 Ctx->IO.CitContext = CloneContext(&rss_CC);
272 Ctx->IO.Terminate = FreeNetworkSaveMessage;
273 Ctx->IO.ShutdownAbort = AbortNetworkSaveMessage;
274 QueueDBOperation(&Ctx->IO, RSS_FetchNetworkUsetableEntry);
279 * Commit a fetched and parsed RSS item to disk
281 void rss_save_item(rss_item *ri, rss_aggregator *Cfg)
284 struct MD5Context md5context;
285 u_char rawdigest[MD5_DIGEST_LEN];
286 struct CtdlMessage *msg;
290 AsyncIO *IO = &Cfg->IO;
294 /* Construct a GUID to use in the S_USETABLE table.
295 * If one is not present in the item itself, make one up.
297 if (ri->guid != NULL) {
298 StrBufSpaceToBlank(ri->guid);
299 StrBufTrim(ri->guid);
300 guid = NewStrBufPlain(HKEY("rss/"));
301 StrBufAppendBuf(guid, ri->guid, 0);
304 MD5Init(&md5context);
305 if (ri->title != NULL) {
306 MD5Update(&md5context, (const unsigned char*)ChrPtr(ri->title), StrLength(ri->title));
308 if (ri->link != NULL) {
309 MD5Update(&md5context, (const unsigned char*)ChrPtr(ri->link), StrLength(ri->link));
311 MD5Final(rawdigest, &md5context);
312 guid = NewStrBufPlain(NULL, MD5_DIGEST_LEN * 2 + 12 /* _rss2ctdl*/);
313 StrBufHexEscAppend(guid, NULL, rawdigest, MD5_DIGEST_LEN);
314 StrBufAppendBufPlain(guid, HKEY("_rss2ctdl"), 0);
317 /* translate Item into message. */
318 EVM_syslog(LOG_DEBUG, "RSS: translating item...\n");
319 if (ri->description == NULL) ri->description = NewStrBufPlain(HKEY(""));
320 StrBufSpaceToBlank(ri->description);
321 msg = malloc(sizeof(struct CtdlMessage));
322 memset(msg, 0, sizeof(struct CtdlMessage));
323 msg->cm_magic = CTDLMESSAGE_MAGIC;
324 msg->cm_anon_type = MES_NORMAL;
325 msg->cm_format_type = FMT_RFC822;
327 if (ri->guid != NULL) {
328 msg->cm_fields['E'] = strdup(ChrPtr(ri->guid));
331 if (ri->author_or_creator != NULL) {
333 StrBuf *Encoded = NULL;
336 From = html_to_ascii(ChrPtr(ri->author_or_creator),
337 StrLength(ri->author_or_creator),
339 StrBufPlain(ri->author_or_creator, From, -1);
340 StrBufTrim(ri->author_or_creator);
343 FromAt = strchr(ChrPtr(ri->author_or_creator), '@') != NULL;
344 if (!FromAt && StrLength (ri->author_email) > 0)
346 StrBufRFC2047encode(&Encoded, ri->author_or_creator);
347 msg->cm_fields['A'] = SmashStrBuf(&Encoded);
348 msg->cm_fields['P'] = SmashStrBuf(&ri->author_email);
354 msg->cm_fields['A'] = SmashStrBuf(&ri->author_or_creator);
355 msg->cm_fields['P'] = strdup(msg->cm_fields['A']);
359 StrBufRFC2047encode(&Encoded, ri->author_or_creator);
360 msg->cm_fields['A'] = SmashStrBuf(&Encoded);
361 msg->cm_fields['P'] = strdup("rss@localhost");
364 if (ri->pubdate <= 0) {
365 ri->pubdate = time(NULL);
370 msg->cm_fields['A'] = strdup("rss");
373 msg->cm_fields['N'] = strdup(NODENAME);
374 if (ri->title != NULL) {
377 StrBuf *Encoded, *QPEncoded;
380 StrBufSpaceToBlank(ri->title);
381 len = StrLength(ri->title);
382 Sbj = html_to_ascii(ChrPtr(ri->title), len, 512, 0);
384 if (Sbj[len - 1] == '\n')
389 Encoded = NewStrBufPlain(Sbj, len);
393 StrBufRFC2047encode(&QPEncoded, Encoded);
395 msg->cm_fields['U'] = SmashStrBuf(&QPEncoded);
396 FreeStrBuf(&Encoded);
398 msg->cm_fields['T'] = malloc(64);
399 snprintf(msg->cm_fields['T'], 64, "%ld", ri->pubdate);
400 if (ri->channel_title != NULL) {
401 if (StrLength(ri->channel_title) > 0) {
402 msg->cm_fields['O'] = strdup(ChrPtr(ri->channel_title));
405 if (ri->link == NULL)
406 ri->link = NewStrBufPlain(HKEY(""));
408 #if 0 /* temporarily disable shorter urls. */
409 msg->cm_fields[TMP_SHORTER_URLS] = GetShorterUrls(ri->description);
412 msglen += 1024 + StrLength(ri->link) + StrLength(ri->description) ;
414 Message = NewStrBufPlain(NULL, StrLength(ri->description));
416 StrBufPlain(Message, HKEY(
417 "Content-type: text/html; charset=\"UTF-8\"\r\n\r\n"
419 #if 0 /* disable shorter url for now. */
420 msg->cm_fields[TMP_SHORTER_URL_OFFSET] = StrLength(Message);
422 StrBufAppendBuf(Message, ri->description, 0);
423 StrBufAppendBufPlain(Message, HKEY("<br><br>\n"), 0);
425 AppendLink(Message, ri->link, ri->linkTitle, NULL);
426 AppendLink(Message, ri->reLink, ri->reLinkTitle, "Reply to this");
427 StrBufAppendBufPlain(Message, HKEY("</body></html>\n"), 0);
431 networker_save_message *SaveMsg;
433 SaveMsg = (networker_save_message *) malloc(sizeof(networker_save_message));
434 memset(SaveMsg, 0, sizeof(networker_save_message));
436 SaveMsg->MsgGUID = guid;
437 SaveMsg->Message = Message;
440 n = GetCount(Cfg->Messages) + 1;
441 Put(Cfg->Messages, IKEY(n), SaveMsg, FreeNetworkSaveMessage);
449 int rss_do_fetching(rss_aggregator *Cfg)
458 if ((Cfg->next_poll != 0) && (now < Cfg->next_poll))
461 ri = (rss_item*) malloc(sizeof(rss_item));
462 memset(ri, 0, sizeof(rss_item));
465 IO->CitContext = CloneContext(&rss_CC);
469 syslog(LOG_DEBUG, "Fetching RSS feed <%s>\n", ChrPtr(Cfg->Url));
470 ParseURL(&IO->ConnectMe, Cfg->Url, 80);
471 CurlPrepareURL(IO->ConnectMe);
473 if (! evcurl_init(IO,
476 "Citadel RSS Client",
478 RSSAggregatorTerminate))
480 syslog(LOG_DEBUG, "Unable to initialize libcurl.\n");
484 QueueCurlContext(IO);
489 void DeleteRssCfg(void *vptr)
491 rss_aggregator *rncptr = (rss_aggregator *)vptr;
492 AsyncIO *IO = &rncptr->IO;
493 EVM_syslog(LOG_DEBUG, "RSS: destroying\n");
495 FreeStrBuf(&rncptr->Url);
496 FreeStrBuf(&rncptr->rooms);
497 FreeStrBuf(&rncptr->CData);
498 FreeStrBuf(&rncptr->Key);
499 FreeStrBuf(&rncptr->IO.HttpReq.ReplyData);
500 DeleteHash(&rncptr->OtherQRnumbers);
501 FreeURL(&rncptr->IO.ConnectMe);
503 DeleteHashPos (&rncptr->Pos);
504 DeleteHash (&rncptr->Messages);
505 if (rncptr->recp.recp_room != NULL)
506 free(rncptr->recp.recp_room);
509 if (rncptr->Item != NULL)
511 FreeStrBuf(&rncptr->Item->guid);
512 FreeStrBuf(&rncptr->Item->title);
513 FreeStrBuf(&rncptr->Item->link);
514 FreeStrBuf(&rncptr->Item->linkTitle);
515 FreeStrBuf(&rncptr->Item->reLink);
516 FreeStrBuf(&rncptr->Item->reLinkTitle);
517 FreeStrBuf(&rncptr->Item->description);
518 FreeStrBuf(&rncptr->Item->channel_title);
519 FreeStrBuf(&rncptr->Item->author_or_creator);
520 FreeStrBuf(&rncptr->Item->author_url);
521 FreeStrBuf(&rncptr->Item->author_email);
528 eNextState RSSAggregatorTerminate(AsyncIO *IO)
530 rss_aggregator *rncptr = (rss_aggregator *)IO->Data;
532 EVM_syslog(LOG_DEBUG, "RSS: Terminating.\n");
535 UnlinkRSSAggregator(rncptr);
540 * Scan a room's netconfig to determine whether it is requesting any RSS feeds
542 void rssclient_scan_room(struct ctdlroom *qrbuf, void *data)
544 StrBuf *CfgData=NULL;
547 rss_room_counter *Count = NULL;
549 char filename[PATH_MAX];
552 rss_aggregator *rncptr = NULL;
553 rss_aggregator *use_this_rncptr = NULL;
555 const char *CfgPtr, *lPtr;
558 pthread_mutex_lock(&RSSQueueMutex);
559 if (GetHash(RSSQueueRooms, LKEY(qrbuf->QRnumber), &vptr))
562 "rssclient: [%ld] %s already in progress.\n",
565 pthread_mutex_unlock(&RSSQueueMutex);
568 pthread_mutex_unlock(&RSSQueueMutex);
570 assoc_file_name(filename, sizeof filename, qrbuf, ctdl_netcfg_dir);
572 if (server_shutting_down)
575 /* Only do net processing for rooms that have netconfigs */
576 fd = open(filename, 0);
578 //syslog(LOG_DEBUG, "rssclient: %s no config.\n", qrbuf->QRname);
582 if (server_shutting_down)
585 if (fstat(fd, &statbuf) == -1) {
586 syslog(LOG_DEBUG, "ERROR: could not stat configfile '%s' - %s\n",
587 filename, strerror(errno));
591 if (server_shutting_down)
594 CfgData = NewStrBufPlain(NULL, statbuf.st_size + 1);
596 if (StrBufReadBLOB(CfgData, &fd, 1, statbuf.st_size, &Err) < 0) {
598 FreeStrBuf(&CfgData);
599 syslog(LOG_DEBUG, "ERROR: reading config '%s' - %s<br>\n",
600 filename, strerror(errno));
604 if (server_shutting_down)
608 CfgType = NewStrBuf();
609 Line = NewStrBufPlain(NULL, StrLength(CfgData));
613 Done = StrBufSipLine(Line, CfgData, &CfgPtr) == 0;
614 if (StrLength(Line) > 0)
617 StrBufExtract_NextToken(CfgType, Line, &lPtr, '|');
618 if (!strcasecmp("rssclient", ChrPtr(CfgType)))
622 Count = malloc(sizeof(rss_room_counter));
626 rncptr = (rss_aggregator *) malloc(sizeof(rss_aggregator));
627 memset (rncptr, 0, sizeof(rss_aggregator));
628 rncptr->roomlist_parts = 1;
629 rncptr->Url = NewStrBuf();
630 StrBufExtract_NextToken(rncptr->Url, Line, &lPtr, '|');
632 pthread_mutex_lock(&RSSQueueMutex);
633 GetHash(RSSFetchUrls, SKEY(rncptr->Url), &vptr);
634 use_this_rncptr = (rss_aggregator *)vptr;
635 if (use_this_rncptr != NULL)
638 StrBufAppendBufPlain(use_this_rncptr->rooms,
641 if (use_this_rncptr->roomlist_parts == 1)
643 use_this_rncptr->OtherQRnumbers = NewHash(1, lFlathash);
645 QRnumber = (long*)malloc(sizeof(long));
646 *QRnumber = qrbuf->QRnumber;
647 Put(use_this_rncptr->OtherQRnumbers, LKEY(qrbuf->QRnumber), QRnumber, NULL);
648 use_this_rncptr->roomlist_parts++;
650 pthread_mutex_unlock(&RSSQueueMutex);
652 FreeStrBuf(&rncptr->Url);
657 pthread_mutex_unlock(&RSSQueueMutex);
659 rncptr->ItemType = RSS_UNSET;
661 rncptr->rooms = NewStrBufPlain(qrbuf->QRname, -1);
663 pthread_mutex_lock(&RSSQueueMutex);
664 Put(RSSFetchUrls, SKEY(rncptr->Url), rncptr, DeleteRssCfg);
665 pthread_mutex_unlock(&RSSQueueMutex);
671 Count->QRnumber = qrbuf->QRnumber;
672 pthread_mutex_lock(&RSSQueueMutex);
673 syslog(LOG_DEBUG, "rssclient: [%ld] %s now starting.\n",
674 qrbuf->QRnumber, qrbuf->QRname);
675 Put(RSSQueueRooms, LKEY(qrbuf->QRnumber), Count, NULL);
676 pthread_mutex_unlock(&RSSQueueMutex);
678 FreeStrBuf(&CfgData);
679 FreeStrBuf(&CfgType);
684 * Scan for rooms that have RSS client requests configured
686 void rssclient_scan(void) {
687 static int doing_rssclient = 0;
688 rss_aggregator *rptr = NULL;
694 /* Run no more than once every 15 minutes. */
695 if ((time(NULL) - last_run) < 900) {
700 * This is a simple concurrency check to make sure only one rssclient run
701 * is done at a time. We could do this with a mutex, but since we
702 * don't really require extremely fine granularity here, we'll do it
703 * with a static variable instead.
705 if (doing_rssclient) return;
707 if ((GetCount(RSSQueueRooms) > 0) || (GetCount(RSSFetchUrls) > 0))
710 syslog(LOG_DEBUG, "rssclient started\n");
711 CtdlForEachRoom(rssclient_scan_room, NULL);
713 pthread_mutex_lock(&RSSQueueMutex);
715 it = GetNewHashPos(RSSFetchUrls, 0);
716 while (!server_shutting_down &&
717 GetNextHashPos(RSSFetchUrls, it, &len, &Key, &vrptr) &&
719 rptr = (rss_aggregator *)vrptr;
720 if (!rss_do_fetching(rptr))
721 UnlinkRSSAggregator(rptr);
724 pthread_mutex_unlock(&RSSQueueMutex);
726 syslog(LOG_DEBUG, "rssclient ended\n");
731 void rss_cleanup(void)
733 /* citthread_mutex_destroy(&RSSQueueMutex); TODO */
734 DeleteHash(&RSSFetchUrls);
735 DeleteHash(&RSSQueueRooms);
739 CTDL_MODULE_INIT(rssclient)
743 CtdlFillSystemContext(&rss_CC, "rssclient");
744 pthread_mutex_init(&RSSQueueMutex, NULL);
745 RSSQueueRooms = NewHash(1, lFlathash);
746 RSSFetchUrls = NewHash(1, NULL);
747 syslog(LOG_INFO, "%s\n", curl_version());
748 CtdlRegisterSessionHook(rssclient_scan, EVT_TIMER);
749 CtdlRegisterCleanupHook(rss_cleanup);