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);
184 ((struct CitContext*)IO->CitContext)->state = CON_IDLE;
185 ((struct CitContext*)IO->CitContext)->kill_me = 1;
187 last_run = time(NULL);
191 eNextState AbortNetworkSaveMessage (AsyncIO *IO)
193 return eAbort; ///TODO
196 eNextState RSSSaveMessage(AsyncIO *IO)
198 networker_save_message *Ctx = (networker_save_message *) IO->Data;
200 Ctx->Msg->cm_fields['M'] = SmashStrBuf(&Ctx->Message);
202 CtdlSubmitMsg(Ctx->Msg, Ctx->recp, NULL, 0);
204 /* write the uidl to the use table so we don't store this item again */
205 cdb_store(CDB_USETABLE, SKEY(Ctx->MsgGUID), &Ctx->ut, sizeof(struct UseTable) );
207 return eTerminateConnection;
210 eNextState RSS_FetchNetworkUsetableEntry(AsyncIO *IO)
212 struct cdbdata *cdbut;
213 networker_save_message *Ctx = (networker_save_message *) IO->Data;
215 /* Find out if we've already seen this item */
216 strcpy(Ctx->ut.ut_msgid, ChrPtr(Ctx->MsgGUID)); /// TODO
217 Ctx->ut.ut_timestamp = time(NULL);
219 cdbut = cdb_fetch(CDB_USETABLE, SKEY(Ctx->MsgGUID));
222 /* Item has already been seen */
223 syslog(LOG_DEBUG, "%s has already been seen\n", ChrPtr(Ctx->MsgGUID));
226 /* rewrite the record anyway, to update the timestamp */
227 cdb_store(CDB_USETABLE,
229 &Ctx->ut, sizeof(struct UseTable) );
235 NextDBOperation(IO, RSSSaveMessage);
239 void RSSQueueSaveMessage(struct CtdlMessage *Msg, struct recptypes *recp, StrBuf *MsgGUID, StrBuf *MessageBody, rss_aggregator *Cfg)
241 networker_save_message *Ctx;
243 Ctx = (networker_save_message *) malloc(sizeof(networker_save_message));
244 memset(Ctx, 0, sizeof(networker_save_message));
246 Ctx->MsgGUID = MsgGUID;
247 Ctx->Message = MessageBody;
252 Ctx->IO.CitContext = CloneContext(&rss_CC);
253 Ctx->IO.Terminate = FreeNetworkSaveMessage;
254 Ctx->IO.ShutdownAbort = AbortNetworkSaveMessage;
255 QueueDBOperation(&Ctx->IO, RSS_FetchNetworkUsetableEntry);
260 * Commit a fetched and parsed RSS item to disk
262 void rss_save_item(rss_item *ri, rss_aggregator *Cfg)
265 struct MD5Context md5context;
266 u_char rawdigest[MD5_DIGEST_LEN];
267 struct CtdlMessage *msg;
268 struct recptypes *recp = NULL;
274 recp = (struct recptypes *) malloc(sizeof(struct recptypes));
275 if (recp == NULL) return;
276 memset(recp, 0, sizeof(struct recptypes));
277 Buf = NewStrBufDup(Cfg->rooms);
278 recp->recp_room = SmashStrBuf(&Buf);
279 recp->num_room = Cfg->roomlist_parts;
280 recp->recptypes_magic = RECPTYPES_MAGIC;
283 /* Construct a GUID to use in the S_USETABLE table.
284 * If one is not present in the item itself, make one up.
286 if (ri->guid != NULL) {
287 StrBufSpaceToBlank(ri->guid);
288 StrBufTrim(ri->guid);
289 guid = NewStrBufPlain(HKEY("rss/"));
290 StrBufAppendBuf(guid, ri->guid, 0);
293 MD5Init(&md5context);
294 if (ri->title != NULL) {
295 MD5Update(&md5context, (const unsigned char*)ChrPtr(ri->title), StrLength(ri->title));
297 if (ri->link != NULL) {
298 MD5Update(&md5context, (const unsigned char*)ChrPtr(ri->link), StrLength(ri->link));
300 MD5Final(rawdigest, &md5context);
301 guid = NewStrBufPlain(NULL, MD5_DIGEST_LEN * 2 + 12 /* _rss2ctdl*/);
302 StrBufHexEscAppend(guid, NULL, rawdigest, MD5_DIGEST_LEN);
303 StrBufAppendBufPlain(guid, HKEY("_rss2ctdl"), 0);
306 /* translate Item into message. */
307 syslog(LOG_DEBUG, "RSS: translating item...\n");
308 if (ri->description == NULL) ri->description = NewStrBufPlain(HKEY(""));
309 StrBufSpaceToBlank(ri->description);
310 msg = malloc(sizeof(struct CtdlMessage));
311 memset(msg, 0, sizeof(struct CtdlMessage));
312 msg->cm_magic = CTDLMESSAGE_MAGIC;
313 msg->cm_anon_type = MES_NORMAL;
314 msg->cm_format_type = FMT_RFC822;
316 if (ri->guid != NULL) {
317 msg->cm_fields['E'] = strdup(ChrPtr(ri->guid));
320 if (ri->author_or_creator != NULL) {
322 StrBuf *Encoded = NULL;
325 From = html_to_ascii(ChrPtr(ri->author_or_creator),
326 StrLength(ri->author_or_creator),
328 StrBufPlain(ri->author_or_creator, From, -1);
329 StrBufTrim(ri->author_or_creator);
332 FromAt = strchr(ChrPtr(ri->author_or_creator), '@') != NULL;
333 if (!FromAt && StrLength (ri->author_email) > 0)
335 StrBufRFC2047encode(&Encoded, ri->author_or_creator);
336 msg->cm_fields['A'] = SmashStrBuf(&Encoded);
337 msg->cm_fields['P'] = SmashStrBuf(&ri->author_email);
343 msg->cm_fields['A'] = SmashStrBuf(&ri->author_or_creator);
344 msg->cm_fields['P'] = strdup(msg->cm_fields['A']);
348 StrBufRFC2047encode(&Encoded, ri->author_or_creator);
349 msg->cm_fields['A'] = SmashStrBuf(&Encoded);
350 msg->cm_fields['P'] = strdup("rss@localhost");
353 if (ri->pubdate <= 0) {
354 ri->pubdate = time(NULL);
359 msg->cm_fields['A'] = strdup("rss");
362 msg->cm_fields['N'] = strdup(NODENAME);
363 if (ri->title != NULL) {
366 StrBuf *Encoded, *QPEncoded;
369 StrBufSpaceToBlank(ri->title);
370 len = StrLength(ri->title);
371 Sbj = html_to_ascii(ChrPtr(ri->title), len, 512, 0);
373 if (Sbj[len - 1] == '\n')
378 Encoded = NewStrBufPlain(Sbj, len);
382 StrBufRFC2047encode(&QPEncoded, Encoded);
384 msg->cm_fields['U'] = SmashStrBuf(&QPEncoded);
385 FreeStrBuf(&Encoded);
387 msg->cm_fields['T'] = malloc(64);
388 snprintf(msg->cm_fields['T'], 64, "%ld", ri->pubdate);
389 if (ri->channel_title != NULL) {
390 if (StrLength(ri->channel_title) > 0) {
391 msg->cm_fields['O'] = strdup(ChrPtr(ri->channel_title));
394 if (ri->link == NULL)
395 ri->link = NewStrBufPlain(HKEY(""));
397 #if 0 /* temporarily disable shorter urls. */
398 msg->cm_fields[TMP_SHORTER_URLS] = GetShorterUrls(ri->description);
401 msglen += 1024 + StrLength(ri->link) + StrLength(ri->description) ;
403 Message = NewStrBufPlain(NULL, StrLength(ri->description));
405 StrBufPlain(Message, HKEY(
406 "Content-type: text/html; charset=\"UTF-8\"\r\n\r\n"
408 #if 0 /* disable shorter url for now. */
409 msg->cm_fields[TMP_SHORTER_URL_OFFSET] = StrLength(Message);
411 StrBufAppendBuf(Message, ri->description, 0);
412 StrBufAppendBufPlain(Message, HKEY("<br><br>\n"), 0);
414 AppendLink(Message, ri->link, ri->linkTitle, NULL);
415 AppendLink(Message, ri->reLink, ri->reLinkTitle, "Reply to this");
416 StrBufAppendBufPlain(Message, HKEY("</body></html>\n"), 0);
418 RSSQueueSaveMessage(msg, recp, guid, Message, Cfg);
426 int rss_do_fetching(rss_aggregator *Cfg)
435 if ((Cfg->next_poll != 0) && (now < Cfg->next_poll))
439 ri = (rss_item*) malloc(sizeof(rss_item));
440 memset(ri, 0, sizeof(rss_item));
443 IO->CitContext = CloneContext(&rss_CC);
447 syslog(LOG_DEBUG, "Fetching RSS feed <%s>\n", ChrPtr(Cfg->Url));
448 ParseURL(&IO->ConnectMe, Cfg->Url, 80);
449 CurlPrepareURL(IO->ConnectMe);
451 if (! evcurl_init(IO,
454 "Citadel RSS Client",
456 RSSAggregatorTerminate))
458 syslog(LOG_DEBUG, "Unable to initialize libcurl.\n");
462 evcurl_handle_start(IO);
467 void DeleteRssCfg(void *vptr)
469 rss_aggregator *rncptr = (rss_aggregator *)vptr;
471 FreeStrBuf(&rncptr->Url);
472 FreeStrBuf(&rncptr->rooms);
473 FreeStrBuf(&rncptr->CData);
474 FreeStrBuf(&rncptr->Key);
475 FreeStrBuf(&rncptr->IO.HttpReq.ReplyData);
476 DeleteHash(&rncptr->OtherQRnumbers);
477 FreeURL(&rncptr->IO.ConnectMe);
479 if (rncptr->Item != NULL)
481 FreeStrBuf(&rncptr->Item->guid);
482 FreeStrBuf(&rncptr->Item->title);
483 FreeStrBuf(&rncptr->Item->link);
484 FreeStrBuf(&rncptr->Item->linkTitle);
485 FreeStrBuf(&rncptr->Item->reLink);
486 FreeStrBuf(&rncptr->Item->reLinkTitle);
487 FreeStrBuf(&rncptr->Item->description);
488 FreeStrBuf(&rncptr->Item->channel_title);
489 FreeStrBuf(&rncptr->Item->author_or_creator);
490 FreeStrBuf(&rncptr->Item->author_url);
491 FreeStrBuf(&rncptr->Item->author_email);
498 eNextState RSSAggregatorTerminate(AsyncIO *IO)
500 rss_aggregator *rncptr = (rss_aggregator *)IO->Data;
507 pthread_mutex_lock(&RSSQueueMutex);
509 if (rncptr->RefCount == 0)
511 UnlinkRSSAggregator(rncptr);
514 pthread_mutex_unlock(&RSSQueueMutex);
516 At = GetNewHashPos(RSSFetchUrls, 0);
518 pthread_mutex_lock(&RSSQueueMutex);
519 GetHashPosFromKey(RSSFetchUrls, SKEY(rncptr->Url), At);
520 GetHashPos(RSSFetchUrls, At, &HKLen, &HK, &vData);
521 DeleteEntryFromHash(RSSFetchUrls, At);
522 pthread_mutex_unlock(&RSSQueueMutex);
530 * Scan a room's netconfig to determine whether it is requesting any RSS feeds
532 void rssclient_scan_room(struct ctdlroom *qrbuf, void *data)
534 StrBuf *CfgData=NULL;
537 rss_room_counter *Count = NULL;
539 char filename[PATH_MAX];
542 rss_aggregator *rncptr = NULL;
543 rss_aggregator *use_this_rncptr = NULL;
545 const char *CfgPtr, *lPtr;
548 pthread_mutex_lock(&RSSQueueMutex);
549 if (GetHash(RSSQueueRooms, LKEY(qrbuf->QRnumber), &vptr))
552 "rssclient: [%ld] %s already in progress.\n",
555 pthread_mutex_unlock(&RSSQueueMutex);
558 pthread_mutex_unlock(&RSSQueueMutex);
560 assoc_file_name(filename, sizeof filename, qrbuf, ctdl_netcfg_dir);
562 if (server_shutting_down)
565 /* Only do net processing for rooms that have netconfigs */
566 fd = open(filename, 0);
568 //syslog(LOG_DEBUG, "rssclient: %s no config.\n", qrbuf->QRname);
572 if (server_shutting_down)
575 if (fstat(fd, &statbuf) == -1) {
576 syslog(LOG_DEBUG, "ERROR: could not stat configfile '%s' - %s\n",
577 filename, strerror(errno));
581 if (server_shutting_down)
584 CfgData = NewStrBufPlain(NULL, statbuf.st_size + 1);
586 if (StrBufReadBLOB(CfgData, &fd, 1, statbuf.st_size, &Err) < 0) {
588 FreeStrBuf(&CfgData);
589 syslog(LOG_DEBUG, "ERROR: reading config '%s' - %s<br>\n",
590 filename, strerror(errno));
594 if (server_shutting_down)
598 CfgType = NewStrBuf();
599 Line = NewStrBufPlain(NULL, StrLength(CfgData));
603 Done = StrBufSipLine(Line, CfgData, &CfgPtr) == 0;
604 if (StrLength(Line) > 0)
607 StrBufExtract_NextToken(CfgType, Line, &lPtr, '|');
608 if (!strcasecmp("rssclient", ChrPtr(CfgType)))
612 Count = malloc(sizeof(rss_room_counter));
616 rncptr = (rss_aggregator *) malloc(sizeof(rss_aggregator));
617 memset (rncptr, 0, sizeof(rss_aggregator));
618 rncptr->roomlist_parts = 1;
619 rncptr->Url = NewStrBuf();
620 StrBufExtract_NextToken(rncptr->Url, Line, &lPtr, '|');
622 pthread_mutex_lock(&RSSQueueMutex);
623 GetHash(RSSFetchUrls, SKEY(rncptr->Url), &vptr);
624 use_this_rncptr = (rss_aggregator *)vptr;
625 if (use_this_rncptr != NULL)
627 /* mustn't attach to an active session */
628 if (use_this_rncptr->RefCount > 0)
630 DeleteRssCfg(rncptr);
636 StrBufAppendBufPlain(use_this_rncptr->rooms,
639 if (use_this_rncptr->roomlist_parts == 1)
641 use_this_rncptr->OtherQRnumbers = NewHash(1, lFlathash);
643 QRnumber = (long*)malloc(sizeof(long));
644 *QRnumber = qrbuf->QRnumber;
645 Put(use_this_rncptr->OtherQRnumbers, LKEY(qrbuf->QRnumber), QRnumber, NULL);
646 use_this_rncptr->roomlist_parts++;
648 pthread_mutex_unlock(&RSSQueueMutex);
651 FreeStrBuf(&rncptr->Url);
656 pthread_mutex_unlock(&RSSQueueMutex);
658 rncptr->ItemType = RSS_UNSET;
660 rncptr->rooms = NewStrBufPlain(qrbuf->QRname, -1);
662 pthread_mutex_lock(&RSSQueueMutex);
663 Put(RSSFetchUrls, SKEY(rncptr->Url), rncptr, DeleteRssCfg);
664 pthread_mutex_unlock(&RSSQueueMutex);
670 Count->QRnumber = qrbuf->QRnumber;
671 pthread_mutex_lock(&RSSQueueMutex);
672 syslog(LOG_DEBUG, "rssclient: [%ld] %s now starting.\n",
673 qrbuf->QRnumber, qrbuf->QRname);
674 Put(RSSQueueRooms, LKEY(qrbuf->QRnumber), Count, NULL);
675 pthread_mutex_unlock(&RSSQueueMutex);
677 FreeStrBuf(&CfgData);
678 FreeStrBuf(&CfgType);
683 * Scan for rooms that have RSS client requests configured
685 void rssclient_scan(void) {
686 static int doing_rssclient = 0;
687 rss_aggregator *rptr = NULL;
693 /* Run no more than once every 15 minutes. */
694 if ((time(NULL) - last_run) < 900) {
699 * This is a simple concurrency check to make sure only one rssclient run
700 * is done at a time. We could do this with a mutex, but since we
701 * don't really require extremely fine granularity here, we'll do it
702 * with a static variable instead.
704 if (doing_rssclient) return;
707 syslog(LOG_DEBUG, "rssclient started\n");
708 CtdlForEachRoom(rssclient_scan_room, NULL);
710 pthread_mutex_lock(&RSSQueueMutex);
712 it = GetNewHashPos(RSSFetchUrls, 0);
713 while (!server_shutting_down &&
714 GetNextHashPos(RSSFetchUrls, it, &len, &Key, &vrptr) &&
716 rptr = (rss_aggregator *)vrptr;
717 if (rptr->RefCount == 0)
718 if (!rss_do_fetching(rptr))
719 UnlinkRSSAggregator(rptr);
722 pthread_mutex_unlock(&RSSQueueMutex);
724 syslog(LOG_DEBUG, "rssclient ended\n");
729 void rss_cleanup(void)
731 /* citthread_mutex_destroy(&RSSQueueMutex); TODO */
732 DeleteHash(&RSSFetchUrls);
733 DeleteHash(&RSSQueueRooms);
737 CTDL_MODULE_INIT(rssclient)
741 CtdlFillSystemContext(&rss_CC, "rssclient");
742 pthread_mutex_init(&RSSQueueMutex, NULL);
743 RSSQueueRooms = NewHash(1, lFlathash);
744 RSSFetchUrls = NewHash(1, NULL);
745 syslog(LOG_INFO, "%s\n", curl_version());
746 CtdlRegisterSessionHook(rssclient_scan, EVT_TIMER);
747 CtdlRegisterCleanupHook(rss_cleanup);