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
65 citthread_mutex_t RSSQueueMutex; /* locks the access to the following vars: */
66 HashList *RSSQueueRooms = NULL; /* rss_room_counter */
67 HashList *RSSFetchUrls = NULL; /* -> rss_aggregator; ->RefCount access to be locked too. */
69 eNextState RSSAggregatorTerminate(AsyncIO *IO);
72 struct rssnetcfg *rnclist = NULL;
73 void AppendLink(StrBuf *Message, StrBuf *link, StrBuf *LinkTitle, const char *Title)
75 if (StrLength(link) > 0)
77 StrBufAppendBufPlain(Message, HKEY("<a href=\""), 0);
78 StrBufAppendBuf(Message, link, 0);
79 StrBufAppendBufPlain(Message, HKEY("\">"), 0);
80 if (StrLength(LinkTitle) > 0)
81 StrBufAppendBuf(Message, LinkTitle, 0);
82 else if ((Title != NULL) && !IsEmptyStr(Title))
83 StrBufAppendBufPlain(Message, Title, -1, 0);
85 StrBufAppendBuf(Message, link, 0);
86 StrBufAppendBufPlain(Message, HKEY("</a><br>\n"), 0);
89 typedef struct __networker_save_message {
91 struct CtdlMessage *Msg;
92 struct recptypes *recp;
97 } networker_save_message;
100 void DeleteRoomReference(long QRnumber)
106 rss_room_counter *pRoomC;
108 At = GetNewHashPos(RSSQueueRooms, 0);
110 GetHashPosFromKey(RSSQueueRooms, LKEY(QRnumber), At);
111 GetHashPos(RSSQueueRooms, At, &HKLen, &HK, &vData);
114 pRoomC = (rss_room_counter *) vData;
116 if (pRoomC->count == 0)
117 DeleteEntryFromHash(RSSQueueRooms, At);
122 void UnlinkRooms(rss_aggregator *Cfg)
125 DeleteRoomReference(Cfg->QRnumber);
126 if (Cfg->OtherQRnumbers != NULL)
133 At = GetNewHashPos(Cfg->OtherQRnumbers, 0);
134 while (GetNextHashPos(Cfg->OtherQRnumbers, At, &HKLen, &HK, &vData) &&
137 long *lData = (long*) vData;
138 DeleteRoomReference(*lData);
146 void UnlinkRSSAggregator(rss_aggregator *Cfg)
152 At = GetNewHashPos(RSSFetchUrls, 0);
153 if (GetHashPosFromKey(RSSFetchUrls, SKEY(Cfg->Url), At) == 0)
155 DeleteEntryFromHash(RSSFetchUrls, At);
160 eNextState FreeNetworkSaveMessage (AsyncIO *IO)
162 networker_save_message *Ctx = (networker_save_message *) IO->Data;
164 citthread_mutex_lock(&RSSQueueMutex);
165 Ctx->Cfg->RefCount --;
167 if (Ctx->Cfg->RefCount == 0)
169 UnlinkRSSAggregator(Ctx->Cfg);
172 citthread_mutex_unlock(&RSSQueueMutex);
174 CtdlFreeMessage(Ctx->Msg);
175 free_recipients(Ctx->recp);
176 FreeStrBuf(&Ctx->Message);
177 FreeStrBuf(&Ctx->MsgGUID);
182 eNextState AbortNetworkSaveMessage (AsyncIO *IO)
184 return eAbort; ///TODO
187 eNextState RSSSaveMessage(AsyncIO *IO)
189 networker_save_message *Ctx = (networker_save_message *) IO->Data;
191 Ctx->Msg->cm_fields['M'] = SmashStrBuf(&Ctx->Message);
193 CtdlSubmitMsg(Ctx->Msg, Ctx->recp, NULL, 0);
195 /* write the uidl to the use table so we don't store this item again */
196 cdb_store(CDB_USETABLE, SKEY(Ctx->MsgGUID), &Ctx->ut, sizeof(struct UseTable) );
198 return eTerminateConnection;
201 eNextState RSS_FetchNetworkUsetableEntry(AsyncIO *IO)
203 struct cdbdata *cdbut;
204 networker_save_message *Ctx = (networker_save_message *) IO->Data;
206 /* Find out if we've already seen this item */
207 strcpy(Ctx->ut.ut_msgid, ChrPtr(Ctx->MsgGUID)); /// TODO
208 Ctx->ut.ut_timestamp = time(NULL);
210 cdbut = cdb_fetch(CDB_USETABLE, SKEY(Ctx->MsgGUID));
213 /* Item has already been seen */
214 syslog(LOG_DEBUG, "%s has already been seen\n", ChrPtr(Ctx->MsgGUID));
217 /* rewrite the record anyway, to update the timestamp */
218 cdb_store(CDB_USETABLE,
220 &Ctx->ut, sizeof(struct UseTable) );
226 NextDBOperation(IO, RSSSaveMessage);
230 void RSSQueueSaveMessage(struct CtdlMessage *Msg, struct recptypes *recp, StrBuf *MsgGUID, StrBuf *MessageBody, rss_aggregator *Cfg)
232 networker_save_message *Ctx;
234 Ctx = (networker_save_message *) malloc(sizeof(networker_save_message));
235 memset(Ctx, 0, sizeof(networker_save_message));
237 Ctx->MsgGUID = MsgGUID;
238 Ctx->Message = MessageBody;
243 Ctx->IO.CitContext = CloneContext(CC);
244 Ctx->IO.Terminate = FreeNetworkSaveMessage;
245 Ctx->IO.ShutdownAbort = AbortNetworkSaveMessage;
246 QueueDBOperation(&Ctx->IO, RSS_FetchNetworkUsetableEntry);
251 * Commit a fetched and parsed RSS item to disk
253 void rss_save_item(rss_item *ri, rss_aggregator *Cfg)
256 struct MD5Context md5context;
257 u_char rawdigest[MD5_DIGEST_LEN];
258 struct CtdlMessage *msg;
259 struct recptypes *recp = NULL;
265 recp = (struct recptypes *) malloc(sizeof(struct recptypes));
266 if (recp == NULL) return;
267 memset(recp, 0, sizeof(struct recptypes));
268 Buf = NewStrBufDup(Cfg->rooms);
269 recp->recp_room = SmashStrBuf(&Buf);
270 recp->num_room = Cfg->roomlist_parts;
271 recp->recptypes_magic = RECPTYPES_MAGIC;
274 /* Construct a GUID to use in the S_USETABLE table.
275 * If one is not present in the item itself, make one up.
277 if (ri->guid != NULL) {
278 StrBufSpaceToBlank(ri->guid);
279 StrBufTrim(ri->guid);
280 guid = NewStrBufPlain(HKEY("rss/"));
281 StrBufAppendBuf(guid, ri->guid, 0);
284 MD5Init(&md5context);
285 if (ri->title != NULL) {
286 MD5Update(&md5context, (const unsigned char*)ChrPtr(ri->title), StrLength(ri->title));
288 if (ri->link != NULL) {
289 MD5Update(&md5context, (const unsigned char*)ChrPtr(ri->link), StrLength(ri->link));
291 MD5Final(rawdigest, &md5context);
292 guid = NewStrBufPlain(NULL, MD5_DIGEST_LEN * 2 + 12 /* _rss2ctdl*/);
293 StrBufHexEscAppend(guid, NULL, rawdigest, MD5_DIGEST_LEN);
294 StrBufAppendBufPlain(guid, HKEY("_rss2ctdl"), 0);
297 /* translate Item into message. */
298 syslog(LOG_DEBUG, "RSS: translating item...\n");
299 if (ri->description == NULL) ri->description = NewStrBufPlain(HKEY(""));
300 StrBufSpaceToBlank(ri->description);
301 msg = malloc(sizeof(struct CtdlMessage));
302 memset(msg, 0, sizeof(struct CtdlMessage));
303 msg->cm_magic = CTDLMESSAGE_MAGIC;
304 msg->cm_anon_type = MES_NORMAL;
305 msg->cm_format_type = FMT_RFC822;
307 if (ri->guid != NULL) {
308 msg->cm_fields['E'] = strdup(ChrPtr(ri->guid));
311 if (ri->author_or_creator != NULL) {
313 StrBuf *Encoded = NULL;
316 From = html_to_ascii(ChrPtr(ri->author_or_creator),
317 StrLength(ri->author_or_creator),
319 StrBufPlain(ri->author_or_creator, From, -1);
320 StrBufTrim(ri->author_or_creator);
323 FromAt = strchr(ChrPtr(ri->author_or_creator), '@') != NULL;
324 if (!FromAt && StrLength (ri->author_email) > 0)
326 StrBufRFC2047encode(&Encoded, ri->author_or_creator);
327 msg->cm_fields['A'] = SmashStrBuf(&Encoded);
328 msg->cm_fields['P'] = SmashStrBuf(&ri->author_email);
334 msg->cm_fields['A'] = SmashStrBuf(&ri->author_or_creator);
335 msg->cm_fields['P'] = strdup(msg->cm_fields['A']);
339 StrBufRFC2047encode(&Encoded, ri->author_or_creator);
340 msg->cm_fields['A'] = SmashStrBuf(&Encoded);
341 msg->cm_fields['P'] = strdup("rss@localhost");
346 msg->cm_fields['A'] = strdup("rss");
349 msg->cm_fields['N'] = strdup(NODENAME);
350 if (ri->title != NULL) {
353 StrBuf *Encoded, *QPEncoded;
356 StrBufSpaceToBlank(ri->title);
357 len = StrLength(ri->title);
358 Sbj = html_to_ascii(ChrPtr(ri->title), len, 512, 0);
360 if (Sbj[len - 1] == '\n')
365 Encoded = NewStrBufPlain(Sbj, len);
369 StrBufRFC2047encode(&QPEncoded, Encoded);
371 msg->cm_fields['U'] = SmashStrBuf(&QPEncoded);
372 FreeStrBuf(&Encoded);
374 msg->cm_fields['T'] = malloc(64);
375 snprintf(msg->cm_fields['T'], 64, "%ld", ri->pubdate);
376 if (ri->channel_title != NULL) {
377 if (StrLength(ri->channel_title) > 0) {
378 msg->cm_fields['O'] = strdup(ChrPtr(ri->channel_title));
381 if (ri->link == NULL)
382 ri->link = NewStrBufPlain(HKEY(""));
384 #if 0 /* temporarily disable shorter urls. */
385 msg->cm_fields[TMP_SHORTER_URLS] = GetShorterUrls(ri->description);
388 msglen += 1024 + StrLength(ri->link) + StrLength(ri->description) ;
390 Message = NewStrBufPlain(NULL, StrLength(ri->description));
392 StrBufPlain(Message, HKEY(
393 "Content-type: text/html; charset=\"UTF-8\"\r\n\r\n"
395 #if 0 /* disable shorter url for now. */
396 msg->cm_fields[TMP_SHORTER_URL_OFFSET] = StrLength(Message);
398 StrBufAppendBuf(Message, ri->description, 0);
399 StrBufAppendBufPlain(Message, HKEY("<br><br>\n"), 0);
401 AppendLink(Message, ri->link, ri->linkTitle, NULL);
402 AppendLink(Message, ri->reLink, ri->reLinkTitle, "Reply to this");
403 StrBufAppendBufPlain(Message, HKEY("</body></html>\n"), 0);
405 RSSQueueSaveMessage(msg, recp, guid, Message, Cfg);
413 int rss_do_fetching(rss_aggregator *Cfg)
422 if ((Cfg->next_poll != 0) && (now < Cfg->next_poll))
426 ri = (rss_item*) malloc(sizeof(rss_item));
427 memset(ri, 0, sizeof(rss_item));
430 IO->CitContext = CloneContext(CC);
434 syslog(LOG_DEBUG, "Fetching RSS feed <%s>\n", ChrPtr(Cfg->Url));
435 ParseURL(&IO->ConnectMe, Cfg->Url, 80);
436 CurlPrepareURL(IO->ConnectMe);
438 if (! evcurl_init(IO,
441 "Citadel RSS Client",
443 RSSAggregatorTerminate))
445 syslog(LOG_DEBUG, "Unable to initialize libcurl.\n");
449 evcurl_handle_start(IO);
455 void DeleteRssCfg(void *vptr)
457 rss_aggregator *rncptr = (rss_aggregator *)vptr;
459 FreeStrBuf(&rncptr->Url);
460 FreeStrBuf(&rncptr->rooms);
461 FreeStrBuf(&rncptr->CData);
462 FreeStrBuf(&rncptr->Key);
464 DeleteHash(&rncptr->OtherQRnumbers);
466 if (rncptr->Item != NULL)
468 FreeStrBuf(&rncptr->Item->guid);
469 FreeStrBuf(&rncptr->Item->title);
470 FreeStrBuf(&rncptr->Item->link);
471 FreeStrBuf(&rncptr->Item->linkTitle);
472 FreeStrBuf(&rncptr->Item->reLink);
473 FreeStrBuf(&rncptr->Item->reLinkTitle);
474 FreeStrBuf(&rncptr->Item->description);
475 FreeStrBuf(&rncptr->Item->channel_title);
476 FreeStrBuf(&rncptr->Item->author_or_creator);
477 FreeStrBuf(&rncptr->Item->author_url);
478 FreeStrBuf(&rncptr->Item->author_email);
485 eNextState RSSAggregatorTerminate(AsyncIO *IO)
487 rss_aggregator *rncptr = (rss_aggregator *)IO->Data;
493 citthread_mutex_lock(&RSSQueueMutex);
495 if (rncptr->RefCount == 0)
497 UnlinkRSSAggregator(rncptr);
500 citthread_mutex_unlock(&RSSQueueMutex);
502 At = GetNewHashPos(RSSFetchUrls, 0);
504 citthread_mutex_lock(&RSSQueueMutex);
505 GetHashPosFromKey(RSSFetchUrls, SKEY(rncptr->Url), At);
506 GetHashPos(RSSFetchUrls, At, &HKLen, &HK, &vData);
507 DeleteEntryFromHash(RSSFetchUrls, At);
508 citthread_mutex_unlock(&RSSQueueMutex);
516 * Scan a room's netconfig to determine whether it is requesting any RSS feeds
518 void rssclient_scan_room(struct ctdlroom *qrbuf, void *data)
523 rss_room_counter *Count = NULL;
525 char filename[PATH_MAX];
528 rss_aggregator *rncptr = NULL;
529 rss_aggregator *use_this_rncptr = NULL;
531 const char *CfgPtr, *lPtr;
534 citthread_mutex_lock(&RSSQueueMutex);
535 if (GetHash(RSSQueueRooms, LKEY(qrbuf->QRnumber), &vptr))
538 "rssclient: [%ld] %s already in progress.\n",
541 citthread_mutex_unlock(&RSSQueueMutex);
544 citthread_mutex_unlock(&RSSQueueMutex);
546 assoc_file_name(filename, sizeof filename, qrbuf, ctdl_netcfg_dir);
548 if (CtdlThreadCheckStop())
551 /* Only do net processing for rooms that have netconfigs */
552 fd = open(filename, 0);
554 //syslog(LOG_DEBUG, "rssclient: %s no config.\n", qrbuf->QRname);
557 if (CtdlThreadCheckStop())
559 if (fstat(fd, &statbuf) == -1) {
560 syslog(LOG_DEBUG, "ERROR: could not stat configfile '%s' - %s\n",
561 filename, strerror(errno));
564 if (CtdlThreadCheckStop())
566 CfgData = NewStrBufPlain(NULL, statbuf.st_size + 1);
567 if (StrBufReadBLOB(CfgData, &fd, 1, statbuf.st_size, &Err) < 0) {
569 FreeStrBuf(&CfgData);
570 syslog(LOG_DEBUG, "ERROR: reading config '%s' - %s<br>\n",
571 filename, strerror(errno));
575 if (CtdlThreadCheckStop())
579 CfgType = NewStrBuf();
580 Line = NewStrBufPlain(NULL, StrLength(CfgData));
584 Done = StrBufSipLine(Line, CfgData, &CfgPtr) == 0;
585 if (StrLength(Line) > 0)
588 StrBufExtract_NextToken(CfgType, Line, &lPtr, '|');
589 if (!strcasecmp("rssclient", ChrPtr(CfgType)))
593 Count = malloc(sizeof(rss_room_counter));
597 rncptr = (rss_aggregator *) malloc(sizeof(rss_aggregator));
598 memset (rncptr, 0, sizeof(rss_aggregator));
599 rncptr->roomlist_parts = 1;
600 rncptr->Url = NewStrBuf();
601 StrBufExtract_NextToken(rncptr->Url, Line, &lPtr, '|');
603 citthread_mutex_lock(&RSSQueueMutex);
604 GetHash(RSSFetchUrls, SKEY(rncptr->Url), &vptr);
605 use_this_rncptr = (rss_aggregator *)vptr;
606 if (use_this_rncptr != NULL)
608 /* mustn't attach to an active session */
609 if (use_this_rncptr->RefCount > 0)
611 DeleteRssCfg(rncptr);
617 StrBufAppendBufPlain(use_this_rncptr->rooms,
620 if (use_this_rncptr->roomlist_parts == 1)
622 use_this_rncptr->OtherQRnumbers = NewHash(1, lFlathash);
624 QRnumber = (long*)malloc(sizeof(long));
625 *QRnumber = qrbuf->QRnumber;
626 Put(use_this_rncptr->OtherQRnumbers, LKEY(qrbuf->QRnumber), QRnumber, NULL);
627 use_this_rncptr->roomlist_parts++;
629 citthread_mutex_unlock(&RSSQueueMutex);
632 citthread_mutex_unlock(&RSSQueueMutex);
634 rncptr->ItemType = RSS_UNSET;
636 rncptr->rooms = NewStrBufPlain(qrbuf->QRname, -1);
638 citthread_mutex_lock(&RSSQueueMutex);
639 Put(RSSFetchUrls, SKEY(rncptr->Url), rncptr, DeleteRssCfg);
640 citthread_mutex_unlock(&RSSQueueMutex);
646 Count->QRnumber = qrbuf->QRnumber;
647 citthread_mutex_lock(&RSSQueueMutex);
648 syslog(LOG_DEBUG, "rssclient: [%ld] %s now starting.\n",
649 qrbuf->QRnumber, qrbuf->QRname);
650 Put(RSSQueueRooms, LKEY(qrbuf->QRnumber), Count, NULL);
651 citthread_mutex_unlock(&RSSQueueMutex);
653 FreeStrBuf(&CfgData);
654 FreeStrBuf(&CfgType);
659 * Scan for rooms that have RSS client requests configured
661 void rssclient_scan(void) {
662 static int doing_rssclient = 0;
663 rss_aggregator *rptr = NULL;
670 * This is a simple concurrency check to make sure only one rssclient run
671 * is done at a time. We could do this with a mutex, but since we
672 * don't really require extremely fine granularity here, we'll do it
673 * with a static variable instead.
675 if (doing_rssclient) return;
678 syslog(LOG_DEBUG, "rssclient started\n");
679 CtdlForEachRoom(rssclient_scan_room, NULL);
681 citthread_mutex_lock(&RSSQueueMutex);
683 it = GetNewHashPos(RSSFetchUrls, 0);
684 while (GetNextHashPos(RSSFetchUrls, it, &len, &Key, &vrptr) &&
686 rptr = (rss_aggregator *)vrptr;
687 if (rptr->RefCount == 0)
688 if (!rss_do_fetching(rptr))
689 UnlinkRSSAggregator(rptr);
692 citthread_mutex_unlock(&RSSQueueMutex);
694 syslog(LOG_DEBUG, "rssclient ended\n");
699 void rss_cleanup(void)
701 citthread_mutex_destroy(&RSSQueueMutex);
702 DeleteHash(&RSSFetchUrls);
703 DeleteHash(&RSSQueueRooms);
707 CTDL_MODULE_INIT(rssclient)
711 citthread_mutex_init(&RSSQueueMutex, NULL);
712 RSSQueueRooms = NewHash(1, lFlathash);
713 RSSFetchUrls = NewHash(1, NULL);
714 syslog(LOG_INFO, "%s\n", curl_version());
715 CtdlRegisterSessionHook(rssclient_scan, EVT_TIMER);
716 CtdlRegisterCleanupHook(rss_cleanup);