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 QueueDBOperation(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 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 QueueDBOperation(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;
293 /* Construct a GUID to use in the S_USETABLE table.
294 * If one is not present in the item itself, make one up.
296 if (ri->guid != NULL) {
297 StrBufSpaceToBlank(ri->guid);
298 StrBufTrim(ri->guid);
299 guid = NewStrBufPlain(HKEY("rss/"));
300 StrBufAppendBuf(guid, ri->guid, 0);
303 MD5Init(&md5context);
304 if (ri->title != NULL) {
305 MD5Update(&md5context, (const unsigned char*)ChrPtr(ri->title), StrLength(ri->title));
307 if (ri->link != NULL) {
308 MD5Update(&md5context, (const unsigned char*)ChrPtr(ri->link), StrLength(ri->link));
310 MD5Final(rawdigest, &md5context);
311 guid = NewStrBufPlain(NULL, MD5_DIGEST_LEN * 2 + 12 /* _rss2ctdl*/);
312 StrBufHexEscAppend(guid, NULL, rawdigest, MD5_DIGEST_LEN);
313 StrBufAppendBufPlain(guid, HKEY("_rss2ctdl"), 0);
316 /* translate Item into message. */
317 syslog(LOG_DEBUG, "RSS: translating item...\n");
318 if (ri->description == NULL) ri->description = NewStrBufPlain(HKEY(""));
319 StrBufSpaceToBlank(ri->description);
320 msg = malloc(sizeof(struct CtdlMessage));
321 memset(msg, 0, sizeof(struct CtdlMessage));
322 msg->cm_magic = CTDLMESSAGE_MAGIC;
323 msg->cm_anon_type = MES_NORMAL;
324 msg->cm_format_type = FMT_RFC822;
326 if (ri->guid != NULL) {
327 msg->cm_fields['E'] = strdup(ChrPtr(ri->guid));
330 if (ri->author_or_creator != NULL) {
332 StrBuf *Encoded = NULL;
335 From = html_to_ascii(ChrPtr(ri->author_or_creator),
336 StrLength(ri->author_or_creator),
338 StrBufPlain(ri->author_or_creator, From, -1);
339 StrBufTrim(ri->author_or_creator);
342 FromAt = strchr(ChrPtr(ri->author_or_creator), '@') != NULL;
343 if (!FromAt && StrLength (ri->author_email) > 0)
345 StrBufRFC2047encode(&Encoded, ri->author_or_creator);
346 msg->cm_fields['A'] = SmashStrBuf(&Encoded);
347 msg->cm_fields['P'] = SmashStrBuf(&ri->author_email);
353 msg->cm_fields['A'] = SmashStrBuf(&ri->author_or_creator);
354 msg->cm_fields['P'] = strdup(msg->cm_fields['A']);
358 StrBufRFC2047encode(&Encoded, ri->author_or_creator);
359 msg->cm_fields['A'] = SmashStrBuf(&Encoded);
360 msg->cm_fields['P'] = strdup("rss@localhost");
363 if (ri->pubdate <= 0) {
364 ri->pubdate = time(NULL);
369 msg->cm_fields['A'] = strdup("rss");
372 msg->cm_fields['N'] = strdup(NODENAME);
373 if (ri->title != NULL) {
376 StrBuf *Encoded, *QPEncoded;
379 StrBufSpaceToBlank(ri->title);
380 len = StrLength(ri->title);
381 Sbj = html_to_ascii(ChrPtr(ri->title), len, 512, 0);
383 if (Sbj[len - 1] == '\n')
388 Encoded = NewStrBufPlain(Sbj, len);
392 StrBufRFC2047encode(&QPEncoded, Encoded);
394 msg->cm_fields['U'] = SmashStrBuf(&QPEncoded);
395 FreeStrBuf(&Encoded);
397 msg->cm_fields['T'] = malloc(64);
398 snprintf(msg->cm_fields['T'], 64, "%ld", ri->pubdate);
399 if (ri->channel_title != NULL) {
400 if (StrLength(ri->channel_title) > 0) {
401 msg->cm_fields['O'] = strdup(ChrPtr(ri->channel_title));
404 if (ri->link == NULL)
405 ri->link = NewStrBufPlain(HKEY(""));
407 #if 0 /* temporarily disable shorter urls. */
408 msg->cm_fields[TMP_SHORTER_URLS] = GetShorterUrls(ri->description);
411 msglen += 1024 + StrLength(ri->link) + StrLength(ri->description) ;
413 Message = NewStrBufPlain(NULL, StrLength(ri->description));
415 StrBufPlain(Message, HKEY(
416 "Content-type: text/html; charset=\"UTF-8\"\r\n\r\n"
418 #if 0 /* disable shorter url for now. */
419 msg->cm_fields[TMP_SHORTER_URL_OFFSET] = StrLength(Message);
421 StrBufAppendBuf(Message, ri->description, 0);
422 StrBufAppendBufPlain(Message, HKEY("<br><br>\n"), 0);
424 AppendLink(Message, ri->link, ri->linkTitle, NULL);
425 AppendLink(Message, ri->reLink, ri->reLinkTitle, "Reply to this");
426 StrBufAppendBufPlain(Message, HKEY("</body></html>\n"), 0);
430 networker_save_message *SaveMsg;
432 SaveMsg = (networker_save_message *) malloc(sizeof(networker_save_message));
433 memset(SaveMsg, 0, sizeof(networker_save_message));
435 SaveMsg->MsgGUID = guid;
436 SaveMsg->Message = Message;
439 n = GetCount(Cfg->Messages) + 1;
440 Put(Cfg->Messages, IKEY(n), SaveMsg, FreeNetworkSaveMessage);
448 int rss_do_fetching(rss_aggregator *Cfg)
457 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;
493 FreeStrBuf(&rncptr->Url);
494 FreeStrBuf(&rncptr->rooms);
495 FreeStrBuf(&rncptr->CData);
496 FreeStrBuf(&rncptr->Key);
497 FreeStrBuf(&rncptr->IO.HttpReq.ReplyData);
498 DeleteHash(&rncptr->OtherQRnumbers);
499 FreeURL(&rncptr->IO.ConnectMe);
501 if (rncptr->Item != NULL)
503 FreeStrBuf(&rncptr->Item->guid);
504 FreeStrBuf(&rncptr->Item->title);
505 FreeStrBuf(&rncptr->Item->link);
506 FreeStrBuf(&rncptr->Item->linkTitle);
507 FreeStrBuf(&rncptr->Item->reLink);
508 FreeStrBuf(&rncptr->Item->reLinkTitle);
509 FreeStrBuf(&rncptr->Item->description);
510 FreeStrBuf(&rncptr->Item->channel_title);
511 FreeStrBuf(&rncptr->Item->author_or_creator);
512 FreeStrBuf(&rncptr->Item->author_url);
513 FreeStrBuf(&rncptr->Item->author_email);
520 eNextState RSSAggregatorTerminate(AsyncIO *IO)
522 rss_aggregator *rncptr = (rss_aggregator *)IO->Data;
529 pthread_mutex_lock(&RSSQueueMutex);
531 if (rncptr->RefCount == 0)
533 UnlinkRSSAggregator(rncptr);
536 pthread_mutex_unlock(&RSSQueueMutex);
538 At = GetNewHashPos(RSSFetchUrls, 0);
540 pthread_mutex_lock(&RSSQueueMutex);
541 GetHashPosFromKey(RSSFetchUrls, SKEY(rncptr->Url), At);
542 GetHashPos(RSSFetchUrls, At, &HKLen, &HK, &vData);
543 DeleteEntryFromHash(RSSFetchUrls, At);
544 pthread_mutex_unlock(&RSSQueueMutex);
545 DeleteHashPos (&rncptr->Pos);
546 DeleteHash (&rncptr->Messages);
547 if (rncptr->recp.recp_room != NULL)
548 free(rncptr->recp.recp_room);
554 * Scan a room's netconfig to determine whether it is requesting any RSS feeds
556 void rssclient_scan_room(struct ctdlroom *qrbuf, void *data)
558 StrBuf *CfgData=NULL;
561 rss_room_counter *Count = NULL;
563 char filename[PATH_MAX];
566 rss_aggregator *rncptr = NULL;
567 rss_aggregator *use_this_rncptr = NULL;
569 const char *CfgPtr, *lPtr;
572 pthread_mutex_lock(&RSSQueueMutex);
573 if (GetHash(RSSQueueRooms, LKEY(qrbuf->QRnumber), &vptr))
576 "rssclient: [%ld] %s already in progress.\n",
579 pthread_mutex_unlock(&RSSQueueMutex);
582 pthread_mutex_unlock(&RSSQueueMutex);
584 assoc_file_name(filename, sizeof filename, qrbuf, ctdl_netcfg_dir);
586 if (server_shutting_down)
589 /* Only do net processing for rooms that have netconfigs */
590 fd = open(filename, 0);
592 //syslog(LOG_DEBUG, "rssclient: %s no config.\n", qrbuf->QRname);
596 if (server_shutting_down)
599 if (fstat(fd, &statbuf) == -1) {
600 syslog(LOG_DEBUG, "ERROR: could not stat configfile '%s' - %s\n",
601 filename, strerror(errno));
605 if (server_shutting_down)
608 CfgData = NewStrBufPlain(NULL, statbuf.st_size + 1);
610 if (StrBufReadBLOB(CfgData, &fd, 1, statbuf.st_size, &Err) < 0) {
612 FreeStrBuf(&CfgData);
613 syslog(LOG_DEBUG, "ERROR: reading config '%s' - %s<br>\n",
614 filename, strerror(errno));
618 if (server_shutting_down)
622 CfgType = NewStrBuf();
623 Line = NewStrBufPlain(NULL, StrLength(CfgData));
627 Done = StrBufSipLine(Line, CfgData, &CfgPtr) == 0;
628 if (StrLength(Line) > 0)
631 StrBufExtract_NextToken(CfgType, Line, &lPtr, '|');
632 if (!strcasecmp("rssclient", ChrPtr(CfgType)))
636 Count = malloc(sizeof(rss_room_counter));
640 rncptr = (rss_aggregator *) malloc(sizeof(rss_aggregator));
641 memset (rncptr, 0, sizeof(rss_aggregator));
642 rncptr->roomlist_parts = 1;
643 rncptr->Url = NewStrBuf();
644 StrBufExtract_NextToken(rncptr->Url, Line, &lPtr, '|');
646 pthread_mutex_lock(&RSSQueueMutex);
647 GetHash(RSSFetchUrls, SKEY(rncptr->Url), &vptr);
648 use_this_rncptr = (rss_aggregator *)vptr;
649 if (use_this_rncptr != NULL)
651 /* mustn't attach to an active session */
652 if (use_this_rncptr->RefCount > 0)
654 DeleteRssCfg(rncptr);
660 StrBufAppendBufPlain(use_this_rncptr->rooms,
663 if (use_this_rncptr->roomlist_parts == 1)
665 use_this_rncptr->OtherQRnumbers = NewHash(1, lFlathash);
667 QRnumber = (long*)malloc(sizeof(long));
668 *QRnumber = qrbuf->QRnumber;
669 Put(use_this_rncptr->OtherQRnumbers, LKEY(qrbuf->QRnumber), QRnumber, NULL);
670 use_this_rncptr->roomlist_parts++;
672 pthread_mutex_unlock(&RSSQueueMutex);
675 FreeStrBuf(&rncptr->Url);
680 pthread_mutex_unlock(&RSSQueueMutex);
682 rncptr->ItemType = RSS_UNSET;
684 rncptr->rooms = NewStrBufPlain(qrbuf->QRname, -1);
686 pthread_mutex_lock(&RSSQueueMutex);
687 Put(RSSFetchUrls, SKEY(rncptr->Url), rncptr, DeleteRssCfg);
688 pthread_mutex_unlock(&RSSQueueMutex);
694 Count->QRnumber = qrbuf->QRnumber;
695 pthread_mutex_lock(&RSSQueueMutex);
696 syslog(LOG_DEBUG, "rssclient: [%ld] %s now starting.\n",
697 qrbuf->QRnumber, qrbuf->QRname);
698 Put(RSSQueueRooms, LKEY(qrbuf->QRnumber), Count, NULL);
699 pthread_mutex_unlock(&RSSQueueMutex);
701 FreeStrBuf(&CfgData);
702 FreeStrBuf(&CfgType);
707 * Scan for rooms that have RSS client requests configured
709 void rssclient_scan(void) {
710 static int doing_rssclient = 0;
711 rss_aggregator *rptr = NULL;
717 /* Run no more than once every 15 minutes. */
718 if ((time(NULL) - last_run) < 900) {
723 * This is a simple concurrency check to make sure only one rssclient run
724 * is done at a time. We could do this with a mutex, but since we
725 * don't really require extremely fine granularity here, we'll do it
726 * with a static variable instead.
728 if (doing_rssclient) return;
731 syslog(LOG_DEBUG, "rssclient started\n");
732 CtdlForEachRoom(rssclient_scan_room, NULL);
734 pthread_mutex_lock(&RSSQueueMutex);
736 it = GetNewHashPos(RSSFetchUrls, 0);
737 while (!server_shutting_down &&
738 GetNextHashPos(RSSFetchUrls, it, &len, &Key, &vrptr) &&
740 rptr = (rss_aggregator *)vrptr;
741 if (rptr->RefCount == 0)
742 if (!rss_do_fetching(rptr))
743 UnlinkRSSAggregator(rptr);
746 pthread_mutex_unlock(&RSSQueueMutex);
748 syslog(LOG_DEBUG, "rssclient ended\n");
753 void rss_cleanup(void)
755 /* citthread_mutex_destroy(&RSSQueueMutex); TODO */
756 DeleteHash(&RSSFetchUrls);
757 DeleteHash(&RSSQueueRooms);
761 CTDL_MODULE_INIT(rssclient)
765 CtdlFillSystemContext(&rss_CC, "rssclient");
766 pthread_mutex_init(&RSSQueueMutex, NULL);
767 RSSQueueRooms = NewHash(1, lFlathash);
768 RSSFetchUrls = NewHash(1, NULL);
769 syslog(LOG_INFO, "%s\n", curl_version());
770 CtdlRegisterSessionHook(rssclient_scan, EVT_TIMER);
771 CtdlRegisterCleanupHook(rss_cleanup);