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. */
71 struct rssnetcfg *rnclist = NULL;
72 void AppendLink(StrBuf *Message, StrBuf *link, StrBuf *LinkTitle, const char *Title)
74 if (StrLength(link) > 0)
76 StrBufAppendBufPlain(Message, HKEY("<a href=\""), 0);
77 StrBufAppendBuf(Message, link, 0);
78 StrBufAppendBufPlain(Message, HKEY("\">"), 0);
79 if (StrLength(LinkTitle) > 0)
80 StrBufAppendBuf(Message, LinkTitle, 0);
81 else if ((Title != NULL) && !IsEmptyStr(Title))
82 StrBufAppendBufPlain(Message, Title, -1, 0);
84 StrBufAppendBuf(Message, link, 0);
85 StrBufAppendBufPlain(Message, HKEY("</a><br>\n"), 0);
88 typedef struct __networker_save_message {
90 struct CtdlMessage *Msg;
91 struct recptypes *recp;
96 } networker_save_message;
99 void DeleteRoomReference(long QRnumber)
105 rss_room_counter *pRoomC;
107 At = GetNewHashPos(RSSQueueRooms, 0);
109 GetHashPosFromKey(RSSQueueRooms, LKEY(QRnumber), At);
110 GetHashPos(RSSQueueRooms, At, &HKLen, &HK, &vData);
111 pRoomC = (rss_room_counter *) vData;
113 if (pRoomC->count == 0)
114 DeleteEntryFromHash(RSSQueueRooms, At);
118 void UnlinkRooms(rss_aggregator *Cfg)
121 DeleteRoomReference(Cfg->QRnumber);
122 if (Cfg->OtherQRnumbers != NULL)
129 At = GetNewHashPos(Cfg->OtherQRnumbers, 0);
130 while (GetNextHashPos(Cfg->OtherQRnumbers, At, &HKLen, &HK, &vData) &&
133 long *lData = (long*) vData;
134 DeleteRoomReference(*lData);
142 void UnlinkAggregator(rss_aggregator *Cfg)
148 At = GetNewHashPos(RSSFetchUrls, 0);
149 if (GetHashPosFromKey(RSSFetchUrls, SKEY(Cfg->Url), At) == 0)
151 DeleteEntryFromHash(RSSFetchUrls, At);
156 eNextState FreeNetworkSaveMessage (AsyncIO *IO)
158 networker_save_message *Ctx = (networker_save_message *) IO->Data;
160 citthread_mutex_lock(&RSSQueueMutex);
161 Ctx->Cfg->RefCount --;
163 if (Ctx->Cfg->RefCount == 0)
165 UnlinkAggregator(Ctx->Cfg);
168 citthread_mutex_unlock(&RSSQueueMutex);
170 CtdlFreeMessage(Ctx->Msg);
171 free_recipients(Ctx->recp);
172 FreeStrBuf(&Ctx->MsgGUID);
177 eNextState AbortNetworkSaveMessage (AsyncIO *IO)
179 return eAbort; ///TODO
182 eNextState RSSSaveMessage(AsyncIO *IO)
184 networker_save_message *Ctx = (networker_save_message *) IO->Data;
186 Ctx->Msg->cm_fields['M'] = SmashStrBuf(&Ctx->Message);
188 CtdlSubmitMsg(Ctx->Msg, Ctx->recp, NULL, 0);
190 /* write the uidl to the use table so we don't store this item again */
191 cdb_store(CDB_USETABLE, SKEY(Ctx->MsgGUID), &Ctx->ut, sizeof(struct UseTable) );
193 return eTerminateConnection;
196 // TODO: relink me: ExpandShortUrls(ri->description);
198 eNextState FetchNetworkUsetableEntry(AsyncIO *IO)
200 struct cdbdata *cdbut;
201 networker_save_message *Ctx = (networker_save_message *) IO->Data;
203 /* Find out if we've already seen this item */
204 strcpy(Ctx->ut.ut_msgid, ChrPtr(Ctx->MsgGUID)); /// TODO
205 Ctx->ut.ut_timestamp = time(NULL);
207 cdbut = cdb_fetch(CDB_USETABLE, SKEY(Ctx->MsgGUID));
210 /* Item has already been seen */
211 CtdlLogPrintf(CTDL_DEBUG, "%s has already been seen\n", ChrPtr(Ctx->MsgGUID));
214 /* rewrite the record anyway, to update the timestamp */
215 cdb_store(CDB_USETABLE,
217 &Ctx->ut, sizeof(struct UseTable) );
218 return eTerminateConnection;
223 NextDBOperation(IO, RSSSaveMessage);
227 void RSSQueueSaveMessage(struct CtdlMessage *Msg, struct recptypes *recp, StrBuf *MsgGUID, StrBuf *MessageBody, rss_aggregator *Cfg)
229 networker_save_message *Ctx;
231 Ctx = (networker_save_message *) malloc(sizeof(networker_save_message));
232 memset(Ctx, 0, sizeof(networker_save_message));
234 Ctx->MsgGUID = MsgGUID;
235 Ctx->Message = MessageBody;
240 Ctx->IO.CitContext = CloneContext(CC);
241 Ctx->IO.Terminate = FreeNetworkSaveMessage;
242 Ctx->IO.ShutdownAbort = AbortNetworkSaveMessage;
243 QueueDBOperation(&Ctx->IO, FetchNetworkUsetableEntry);
248 * Commit a fetched and parsed RSS item to disk
250 void rss_save_item(rss_item *ri, rss_aggregator *Cfg)
253 struct MD5Context md5context;
254 u_char rawdigest[MD5_DIGEST_LEN];
255 struct CtdlMessage *msg;
256 struct recptypes *recp = NULL;
262 recp = (struct recptypes *) malloc(sizeof(struct recptypes));
263 if (recp == NULL) return;
264 memset(recp, 0, sizeof(struct recptypes));
265 Buf = NewStrBufDup(Cfg->rooms);
266 recp->recp_room = SmashStrBuf(&Buf);
267 recp->num_room = Cfg->roomlist_parts;
268 recp->recptypes_magic = RECPTYPES_MAGIC;
271 /* Construct a GUID to use in the S_USETABLE table.
272 * If one is not present in the item itself, make one up.
274 if (ri->guid != NULL) {
275 StrBufSpaceToBlank(ri->guid);
276 StrBufTrim(ri->guid);
277 guid = NewStrBufPlain(HKEY("rss/"));
278 StrBufAppendBuf(guid, ri->guid, 0);
281 MD5Init(&md5context);
282 if (ri->title != NULL) {
283 MD5Update(&md5context, (const unsigned char*)ChrPtr(ri->title), StrLength(ri->title));
285 if (ri->link != NULL) {
286 MD5Update(&md5context, (const unsigned char*)ChrPtr(ri->link), StrLength(ri->link));
288 MD5Final(rawdigest, &md5context);
289 guid = NewStrBufPlain(NULL, MD5_DIGEST_LEN * 2 + 12 /* _rss2ctdl*/);
290 StrBufHexEscAppend(guid, NULL, rawdigest, MD5_DIGEST_LEN);
291 StrBufAppendBufPlain(guid, HKEY("_rss2ctdl"), 0);
294 /* translate Item into message. */
295 CtdlLogPrintf(CTDL_DEBUG, "RSS: translating item...\n");
296 if (ri->description == NULL) ri->description = NewStrBufPlain(HKEY(""));
297 StrBufSpaceToBlank(ri->description);
298 msg = malloc(sizeof(struct CtdlMessage));
299 memset(msg, 0, sizeof(struct CtdlMessage));
300 msg->cm_magic = CTDLMESSAGE_MAGIC;
301 msg->cm_anon_type = MES_NORMAL;
302 msg->cm_format_type = FMT_RFC822;
304 if (ri->guid != NULL) {
305 msg->cm_fields['E'] = strdup(ChrPtr(ri->guid));
308 if (ri->author_or_creator != NULL) {
310 StrBuf *Encoded = NULL;
313 From = html_to_ascii(ChrPtr(ri->author_or_creator),
314 StrLength(ri->author_or_creator),
316 StrBufPlain(ri->author_or_creator, From, -1);
317 StrBufTrim(ri->author_or_creator);
320 FromAt = strchr(ChrPtr(ri->author_or_creator), '@') != NULL;
321 if (!FromAt && StrLength (ri->author_email) > 0)
323 StrBufRFC2047encode(&Encoded, ri->author_or_creator);
324 msg->cm_fields['A'] = SmashStrBuf(&Encoded);
325 msg->cm_fields['P'] = SmashStrBuf(&ri->author_email);
330 msg->cm_fields['P'] = SmashStrBuf(&ri->author_or_creator);
333 StrBufRFC2047encode(&Encoded, ri->author_or_creator);
334 msg->cm_fields['A'] = SmashStrBuf(&Encoded);
335 msg->cm_fields['P'] = strdup("rss@localhost");
340 msg->cm_fields['A'] = strdup("rss");
343 msg->cm_fields['N'] = strdup(NODENAME);
344 if (ri->title != NULL) {
347 StrBuf *Encoded, *QPEncoded;
350 StrBufSpaceToBlank(ri->title);
351 len = StrLength(ri->title);
352 Sbj = html_to_ascii(ChrPtr(ri->title), len, 512, 0);
354 if (Sbj[len - 1] == '\n')
359 Encoded = NewStrBufPlain(Sbj, len);
363 StrBufRFC2047encode(&QPEncoded, Encoded);
365 msg->cm_fields['U'] = SmashStrBuf(&QPEncoded);
366 FreeStrBuf(&Encoded);
368 msg->cm_fields['T'] = malloc(64);
369 snprintf(msg->cm_fields['T'], 64, "%ld", ri->pubdate);
370 if (ri->channel_title != NULL) {
371 if (StrLength(ri->channel_title) > 0) {
372 msg->cm_fields['O'] = strdup(ChrPtr(ri->channel_title));
375 if (ri->link == NULL)
376 ri->link = NewStrBufPlain(HKEY(""));
378 #if 0 /* temporarily disable shorter urls. */
379 msg->cm_fields[TMP_SHORTER_URLS] = GetShorterUrls(ri->description);
382 msglen += 1024 + StrLength(ri->link) + StrLength(ri->description) ;
384 Message = NewStrBufPlain(NULL, StrLength(ri->description));
386 StrBufPlain(Message, HKEY(
387 "Content-type: text/html; charset=\"UTF-8\"\r\n\r\n"
389 #if 0 /* disable shorter url for now. */
390 msg->cm_fields[TMP_SHORTER_URL_OFFSET] = StrLength(Message);
392 StrBufAppendBuf(Message, ri->description, 0);
393 StrBufAppendBufPlain(Message, HKEY("<br><br>\n"), 0);
395 AppendLink(Message, ri->link, ri->linkTitle, NULL);
396 AppendLink(Message, ri->reLink, ri->reLinkTitle, "Reply to this");
397 StrBufAppendBufPlain(Message, HKEY("</body></html>\n"), 0);
399 RSSQueueSaveMessage(msg, recp, guid, Message, Cfg);
407 int rss_do_fetching(rss_aggregator *Cfg)
416 if ((Cfg->next_poll != 0) && (now < Cfg->next_poll))
420 ri = (rss_item*) malloc(sizeof(rss_item));
421 memset(ri, 0, sizeof(rss_item));
424 IO->CitContext = CloneContext(CC);
428 CtdlLogPrintf(CTDL_DEBUG, "Fetching RSS feed <%s>\n", ChrPtr(Cfg->Url));
429 ParseURL(&IO->ConnectMe, Cfg->Url, 80);
430 CurlPrepareURL(IO->ConnectMe);
432 if (! evcurl_init(IO,
435 "Citadel RSS Client",
438 CtdlLogPrintf(CTDL_ALERT, "Unable to initialize libcurl.\n");
442 evcurl_handle_start(IO);
448 void DeleteRssCfg(void *vptr)
450 rss_aggregator *rncptr = (rss_aggregator *)vptr;
452 FreeStrBuf(&rncptr->Url);
453 FreeStrBuf(&rncptr->rooms);
459 * Scan a room's netconfig to determine whether it is requesting any RSS feeds
461 void rssclient_scan_room(struct ctdlroom *qrbuf, void *data)
466 rss_room_counter *Count = NULL;
468 char filename[PATH_MAX];
471 rss_aggregator *rncptr = NULL;
472 rss_aggregator *use_this_rncptr = NULL;
474 const char *CfgPtr, *lPtr;
477 citthread_mutex_lock(&RSSQueueMutex);
478 if (GetHash(RSSQueueRooms, LKEY(qrbuf->QRnumber), &vptr))
480 //CtdlLogPrintf(CTDL_DEBUG, "rssclient: %s already in progress.\n", qrbuf->QRname);
481 citthread_mutex_unlock(&RSSQueueMutex);
484 citthread_mutex_unlock(&RSSQueueMutex);
486 assoc_file_name(filename, sizeof filename, qrbuf, ctdl_netcfg_dir);
488 if (CtdlThreadCheckStop())
491 /* Only do net processing for rooms that have netconfigs */
492 fd = open(filename, 0);
494 //CtdlLogPrintf(CTDL_DEBUG, "rssclient: %s no config.\n", qrbuf->QRname);
497 if (CtdlThreadCheckStop())
499 if (fstat(fd, &statbuf) == -1) {
500 CtdlLogPrintf(CTDL_DEBUG, "ERROR: could not stat configfile '%s' - %s\n",
501 filename, strerror(errno));
504 if (CtdlThreadCheckStop())
506 CfgData = NewStrBufPlain(NULL, statbuf.st_size + 1);
507 if (StrBufReadBLOB(CfgData, &fd, 1, statbuf.st_size, &Err) < 0) {
509 FreeStrBuf(&CfgData);
510 CtdlLogPrintf(CTDL_DEBUG, "ERROR: reading config '%s' - %s<br>\n",
511 filename, strerror(errno));
515 if (CtdlThreadCheckStop())
519 CfgType = NewStrBuf();
520 Line = NewStrBufPlain(NULL, StrLength(CfgData));
524 Done = StrBufSipLine(Line, CfgData, &CfgPtr) == 0;
525 if (StrLength(Line) > 0)
528 StrBufExtract_NextToken(CfgType, Line, &lPtr, '|');
529 if (!strcmp("rssclient", ChrPtr(CfgType)))
533 Count = malloc(sizeof(rss_room_counter));
537 rncptr = (rss_aggregator *) malloc(sizeof(rss_aggregator));
538 memset (rncptr, 0, sizeof(rss_aggregator));
539 rncptr->roomlist_parts = 1;
540 rncptr->Url = NewStrBuf();
541 StrBufExtract_NextToken(rncptr->Url, Line, &lPtr, '|');
543 citthread_mutex_lock(&RSSQueueMutex);
544 GetHash(RSSFetchUrls, SKEY(rncptr->Url), &vptr);
545 use_this_rncptr = (rss_aggregator *)vptr;
546 if (use_this_rncptr != NULL)
548 /* mustn't attach to an active session */
549 if (use_this_rncptr->RefCount > 0)
551 DeleteRssCfg(rncptr);
557 StrBufAppendBufPlain(use_this_rncptr->rooms,
560 if (use_this_rncptr->roomlist_parts == 1)
562 use_this_rncptr->OtherQRnumbers = NewHash(1, lFlathash);
564 //// TODO add reference here!
566 QRnumber = (long*)malloc(sizeof(long));
567 *QRnumber = qrbuf->QRnumber;
568 Put(use_this_rncptr->OtherQRnumbers, LKEY(qrbuf->QRnumber), QRnumber, NULL);
569 use_this_rncptr->roomlist_parts++;
571 citthread_mutex_unlock(&RSSQueueMutex);
574 citthread_mutex_unlock(&RSSQueueMutex);
576 rncptr->ItemType = RSS_UNSET;
578 rncptr->rooms = NewStrBufPlain(qrbuf->QRname, -1);
580 citthread_mutex_lock(&RSSQueueMutex);
581 Put(RSSFetchUrls, SKEY(rncptr->Url), rncptr, DeleteRssCfg);
582 citthread_mutex_unlock(&RSSQueueMutex);
588 Count->QRnumber = qrbuf->QRnumber;
589 citthread_mutex_lock(&RSSQueueMutex);
590 Put(RSSQueueRooms, LKEY(qrbuf->QRnumber), Count, NULL);
591 citthread_mutex_unlock(&RSSQueueMutex);
593 FreeStrBuf(&CfgData);
594 FreeStrBuf(&CfgType);
599 * Scan for rooms that have RSS client requests configured
601 void rssclient_scan(void) {
602 static int doing_rssclient = 0;
603 rss_aggregator *rptr = NULL;
610 * This is a simple concurrency check to make sure only one rssclient run
611 * is done at a time. We could do this with a mutex, but since we
612 * don't really require extremely fine granularity here, we'll do it
613 * with a static variable instead.
615 if (doing_rssclient) return;
618 CtdlLogPrintf(CTDL_DEBUG, "rssclient started\n");
619 CtdlForEachRoom(rssclient_scan_room, NULL);
621 citthread_mutex_lock(&RSSQueueMutex);
623 it = GetNewHashPos(RSSQueueRooms, 0);
624 while (GetNextHashPos(RSSFetchUrls, it, &len, &Key, &vrptr) &&
626 rptr = (rss_aggregator *)vrptr;
627 if (rptr->RefCount == 0)
628 if (!rss_do_fetching(rptr))
634 citthread_mutex_unlock(&RSSQueueMutex);
636 CtdlLogPrintf(CTDL_DEBUG, "rssclientscheduler ended\n");
641 void RSSCleanup(void)
643 citthread_mutex_destroy(&RSSQueueMutex);
644 DeleteHash(&RSSFetchUrls);
645 DeleteHash(&RSSQueueRooms);
649 CTDL_MODULE_INIT(rssclient)
653 citthread_mutex_init(&RSSQueueMutex, NULL);
654 RSSQueueRooms = NewHash(1, Flathash);
655 RSSFetchUrls = NewHash(1, NULL);
656 CtdlLogPrintf(CTDL_INFO, "%s\n", curl_version());
657 CtdlRegisterSessionHook(rssclient_scan, EVT_TIMER);