source: protocols/twitter/twitter_lib.c @ 0688e99

Last change on this file since 0688e99 was 0688e99, checked in by Wilmer van der Gaast <wilmer@…>, at 2012-11-05T08:46:06Z

Type safety check.

  • Property mode set to 100644
File size: 28.3 KB
Line 
1/***************************************************************************\
2*                                                                           *
3*  BitlBee - An IRC to IM gateway                                           *
4*  Simple module to facilitate twitter functionality.                       *
5*                                                                           *
6*  Copyright 2009-2010 Geert Mulders <g.c.w.m.mulders@gmail.com>            *
7*  Copyright 2010-2012 Wilmer van der Gaast <wilmer@gaast.net>              *
8*                                                                           *
9*  This library is free software; you can redistribute it and/or            *
10*  modify it under the terms of the GNU Lesser General Public               *
11*  License as published by the Free Software Foundation, version            *
12*  2.1.                                                                     *
13*                                                                           *
14*  This library is distributed in the hope that it will be useful,          *
15*  but WITHOUT ANY WARRANTY; without even the implied warranty of           *
16*  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU        *
17*  Lesser General Public License for more details.                          *
18*                                                                           *
19*  You should have received a copy of the GNU Lesser General Public License *
20*  along with this library; if not, write to the Free Software Foundation,  *
21*  Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA           *
22*                                                                           *
23****************************************************************************/
24
25/* For strptime(): */
26#if(__sun)
27#else
28#define _XOPEN_SOURCE
29#endif
30
31#include "twitter_http.h"
32#include "twitter.h"
33#include "bitlbee.h"
34#include "url.h"
35#include "misc.h"
36#include "base64.h"
37#include "xmltree.h"
38#include "twitter_lib.h"
39#include "json_util.h"
40#include <ctype.h>
41#include <errno.h>
42
43/* GLib < 2.12.0 doesn't have g_ascii_strtoll(), work around using system strtoll(). */
44/* GLib < 2.12.4 can be buggy: http://bugs.debian.org/cgi-bin/bugreport.cgi?bug=488013 */
45#if !GLIB_CHECK_VERSION(2,12,5)
46#include <stdlib.h>
47#include <limits.h>
48#define g_ascii_strtoll strtoll
49#endif
50
51#define TXL_STATUS 1
52#define TXL_USER 2
53#define TXL_ID 3
54
55struct twitter_xml_list {
56        int type;
57        gint64 next_cursor;
58        GSList *list;
59};
60
61struct twitter_xml_user {
62        char *name;
63        char *screen_name;
64};
65
66struct twitter_xml_status {
67        time_t created_at;
68        char *text;
69        struct twitter_xml_user *user;
70        guint64 id, reply_to;
71};
72
73static void twitter_groupchat_init(struct im_connection *ic);
74
75/**
76 * Frees a twitter_xml_user struct.
77 */
78static void txu_free(struct twitter_xml_user *txu)
79{
80        if (txu == NULL)
81                return;
82
83        g_free(txu->name);
84        g_free(txu->screen_name);
85        g_free(txu);
86}
87
88/**
89 * Frees a twitter_xml_status struct.
90 */
91static void txs_free(struct twitter_xml_status *txs)
92{
93        if (txs == NULL)
94                return;
95
96        g_free(txs->text);
97        txu_free(txs->user);
98        g_free(txs);
99}
100
101/**
102 * Free a twitter_xml_list struct.
103 * type is the type of list the struct holds.
104 */
105static void txl_free(struct twitter_xml_list *txl)
106{
107        GSList *l;
108        if (txl == NULL)
109                return;
110
111        for (l = txl->list; l; l = g_slist_next(l)) {
112                if (txl->type == TXL_STATUS) {
113                        txs_free((struct twitter_xml_status *) l->data);
114                } else if (txl->type == TXL_ID) {
115                        g_free(l->data);
116                } else if (txl->type == TXL_USER) {
117                        txu_free(l->data);
118                }
119        }
120
121        g_slist_free(txl->list);
122        g_free(txl);
123}
124
125/**
126 * Compare status elements
127 */
128static gint twitter_compare_elements(gconstpointer a, gconstpointer b)
129{
130        struct twitter_xml_status *a_status = (struct twitter_xml_status *) a;
131        struct twitter_xml_status *b_status = (struct twitter_xml_status *) b;
132
133        if (a_status->created_at < b_status->created_at) {
134                return -1;
135        } else if (a_status->created_at > b_status->created_at) {
136                return 1;
137        } else {
138                return 0;
139        }
140}
141
142/**
143 * Add a buddy if it is not already added, set the status to logged in.
144 */
145static void twitter_add_buddy(struct im_connection *ic, char *name, const char *fullname)
146{
147        struct twitter_data *td = ic->proto_data;
148
149        // Check if the buddy is already in the buddy list.
150        if (!bee_user_by_handle(ic->bee, ic, name)) {
151                char *mode = set_getstr(&ic->acc->set, "mode");
152
153                // The buddy is not in the list, add the buddy and set the status to logged in.
154                imcb_add_buddy(ic, name, NULL);
155                imcb_rename_buddy(ic, name, fullname);
156                if (g_strcasecmp(mode, "chat") == 0) {
157                        /* Necessary so that nicks always get translated to the
158                           exact Twitter username. */
159                        imcb_buddy_nick_hint(ic, name, name);
160                        imcb_chat_add_buddy(td->timeline_gc, name);
161                } else if (g_strcasecmp(mode, "many") == 0)
162                        imcb_buddy_status(ic, name, OPT_LOGGED_IN, NULL, NULL);
163        }
164}
165
166/* Warning: May return a malloc()ed value, which will be free()d on the next
167   call. Only for short-term use. NOT THREADSAFE!  */
168char *twitter_parse_error(struct http_request *req)
169{
170        static char *ret = NULL;
171        struct xt_node *root, *node, *err;
172
173        g_free(ret);
174        ret = NULL;
175
176        if (req->body_size > 0) {
177                root = xt_from_string(req->reply_body, req->body_size);
178               
179                for (node = root; node; node = node->next)
180                        if ((err = xt_find_node(node->children, "error")) && err->text_len > 0) {
181                                ret = g_strdup_printf("%s (%s)", req->status_string, err->text);
182                                break;
183                        }
184
185                xt_free_node(root);
186        }
187
188        return ret ? ret : req->status_string;
189}
190
191/* TODO: NULL means failure, but not always that the connection is dead. This sucks for callers. */
192static json_value *twitter_parse_response(struct im_connection *ic, struct http_request *req)
193{
194        gboolean logging_in = !(ic->flags & OPT_LOGGED_IN);
195        gboolean periodic;
196        struct twitter_data *td = ic->proto_data;
197        json_value *ret;
198        char path[64] = "", *s;
199       
200        if ((s = strchr(req->request, ' '))) {
201                path[sizeof(path)-1] = '\0';
202                strncpy(path, s + 1, sizeof(path) - 1);
203                if ((s = strchr(path, '?')) || (s = strchr(path, ' ')))
204                        *s = '\0';
205        }
206       
207        /* Kinda nasty. :-( Trying to suppress error messages, but only
208           for periodic (i.e. mentions/timeline) queries. */
209        periodic = strstr(path, "timeline") || strstr(path, "mentions");
210       
211        if (req->status_code == 401 && logging_in) {
212                /* IIRC Twitter once had an outage where they were randomly
213                   throwing 401s so I'll keep treating this one as fatal
214                   only during login. */
215                imcb_error(ic, "Authentication failure");
216                imc_logout(ic, FALSE);
217                return NULL;
218        } else if (req->status_code != 200) {
219                // It didn't go well, output the error and return.
220                if (!periodic || logging_in || ++td->http_fails >= 5)
221                        imcb_error(ic, "Could not retrieve %s: %s",
222                                   path, twitter_parse_error(req));
223               
224                if (logging_in)
225                        imc_logout(ic, TRUE);
226                return NULL;
227        } else {
228                td->http_fails = 0;
229        }
230
231        if ((ret = json_parse(req->reply_body)) == NULL) {
232                imcb_error(ic, "Could not retrieve %s: %s",
233                           path, "XML parse error");
234        }
235        return ret;
236}
237
238static void twitter_http_get_friends_ids(struct http_request *req);
239
240/**
241 * Get the friends ids.
242 */
243void twitter_get_friends_ids(struct im_connection *ic, gint64 next_cursor)
244{
245        // Primitive, but hey! It works...     
246        char *args[2];
247        args[0] = "cursor";
248        args[1] = g_strdup_printf("%lld", (long long) next_cursor);
249        twitter_http(ic, TWITTER_FRIENDS_IDS_URL, twitter_http_get_friends_ids, ic, 0, args, 2);
250
251        g_free(args[1]);
252}
253
254/**
255 * Fill a list of ids.
256 */
257static xt_status twitter_xt_get_friends_id_list(json_value *node, struct twitter_xml_list *txl)
258{
259        json_value *c;
260        int i;
261
262        // Set the list type.
263        txl->type = TXL_ID;
264
265        c = json_o_get(node, "ids");
266        if (!c || c->type != json_array)
267                return XT_ABORT;
268
269        for (i = 0; i < c->u.array.length; i ++) {
270                if (c->u.array.values[i]->type != json_integer)
271                        continue;
272               
273                txl->list = g_slist_prepend(txl->list,
274                        g_strdup_printf("%ld", c->u.array.values[i]->u.integer));
275               
276        }
277       
278        c = json_o_get(node, "next_cursor");
279        if (c && c->type == json_integer)
280                txl->next_cursor = c->u.integer;
281        else
282                txl->next_cursor = -1;
283       
284        return XT_HANDLED;
285}
286
287static void twitter_get_users_lookup(struct im_connection *ic);
288
289/**
290 * Callback for getting the friends ids.
291 */
292static void twitter_http_get_friends_ids(struct http_request *req)
293{
294        struct im_connection *ic;
295        json_value *parsed;
296        struct twitter_xml_list *txl;
297        struct twitter_data *td;
298
299        ic = req->data;
300
301        // Check if the connection is still active.
302        if (!g_slist_find(twitter_connections, ic))
303                return;
304
305        td = ic->proto_data;
306
307        /* Create the room now that we "logged in". */
308        if (!td->timeline_gc && g_strcasecmp(set_getstr(&ic->acc->set, "mode"), "chat") == 0)
309                twitter_groupchat_init(ic);
310
311        txl = g_new0(struct twitter_xml_list, 1);
312        txl->list = td->follow_ids;
313
314        // Parse the data.
315        if (!(parsed = twitter_parse_response(ic, req)))
316                return;
317       
318        twitter_xt_get_friends_id_list(parsed, txl);
319        json_value_free(parsed);
320
321        td->follow_ids = txl->list;
322        if (txl->next_cursor)
323                /* These were just numbers. Up to 4000 in a response AFAIK so if we get here
324                   we may be using a spammer account. \o/ */
325                twitter_get_friends_ids(ic, txl->next_cursor);
326        else
327                /* Now to convert all those numbers into names.. */
328                twitter_get_users_lookup(ic);
329
330        txl->list = NULL;
331        txl_free(txl);
332}
333
334static xt_status twitter_xt_get_users(json_value *node, struct twitter_xml_list *txl);
335static void twitter_http_get_users_lookup(struct http_request *req);
336
337static void twitter_get_users_lookup(struct im_connection *ic)
338{
339        struct twitter_data *td = ic->proto_data;
340        char *args[2] = {
341                "user_id",
342                NULL,
343        };
344        GString *ids = g_string_new("");
345        int i;
346       
347        /* We can request up to 100 users at a time. */
348        for (i = 0; i < 100 && td->follow_ids; i ++) {
349                g_string_append_printf(ids, ",%s", (char*) td->follow_ids->data);
350                g_free(td->follow_ids->data);
351                td->follow_ids = g_slist_remove(td->follow_ids, td->follow_ids->data);
352        }
353        if (ids->len > 0) {
354                args[1] = ids->str + 1;
355                /* POST, because I think ids can be up to 1KB long. */
356                twitter_http(ic, TWITTER_USERS_LOOKUP_URL, twitter_http_get_users_lookup, ic, 1, args, 2);
357        } else {
358                /* We have all users. Continue with login. (Get statuses.) */
359                td->flags |= TWITTER_HAVE_FRIENDS;
360                twitter_login_finish(ic);
361        }
362        g_string_free(ids, TRUE);
363}
364
365/**
366 * Callback for getting (twitter)friends...
367 *
368 * Be afraid, be very afraid! This function will potentially add hundreds of "friends". "Who has
369 * hundreds of friends?" you wonder? You probably not, since you are reading the source of
370 * BitlBee... Get a life and meet new people!
371 */
372static void twitter_http_get_users_lookup(struct http_request *req)
373{
374        struct im_connection *ic = req->data;
375        json_value *parsed;
376        struct twitter_xml_list *txl;
377        GSList *l = NULL;
378        struct twitter_xml_user *user;
379
380        // Check if the connection is still active.
381        if (!g_slist_find(twitter_connections, ic))
382                return;
383
384        txl = g_new0(struct twitter_xml_list, 1);
385        txl->list = NULL;
386
387        // Get the user list from the parsed xml feed.
388        if (!(parsed = twitter_parse_response(ic, req)))
389                return;
390        twitter_xt_get_users(parsed, txl);
391        json_value_free(parsed);
392
393        // Add the users as buddies.
394        for (l = txl->list; l; l = g_slist_next(l)) {
395                user = l->data;
396                twitter_add_buddy(ic, user->screen_name, user->name);
397        }
398
399        // Free the structure.
400        txl_free(txl);
401
402        twitter_get_users_lookup(ic);
403}
404
405/**
406 * Function to fill a twitter_xml_list struct.
407 * It sets:
408 *  - all <user>s from the <users> element.
409 */
410static xt_status twitter_xt_get_users(json_value *node, struct twitter_xml_list *txl)
411{
412        struct twitter_xml_user *txu;
413        int i;
414
415        // Set the type of the list.
416        txl->type = TXL_USER;
417
418        if (!node || node->type != json_array)
419                return XT_ABORT;
420
421        // The root <users> node should hold the list of users <user>
422        // Walk over the nodes children.
423        for (i = 0; i < node->u.array.length; i ++) {
424                txu = g_new0(struct twitter_xml_user, 1);
425                txu->name = g_strdup(json_o_str(node->u.array.values[i], "name"));
426                txu->screen_name = g_strdup(json_o_str(node->u.array.values[i], "screen_name"));
427                txl->list = g_slist_prepend(txl->list, txu);
428        }
429
430        return XT_HANDLED;
431}
432
433#ifdef __GLIBC__
434#define TWITTER_TIME_FORMAT "%a %b %d %H:%M:%S %z %Y"
435#else
436#define TWITTER_TIME_FORMAT "%a %b %d %H:%M:%S +0000 %Y"
437#endif
438
439/**
440 * Function to fill a twitter_xml_status struct.
441 * It sets:
442 *  - the status text and
443 *  - the created_at timestamp and
444 *  - the status id and
445 *  - the user in a twitter_xml_user struct.
446 */
447static xt_status twitter_xt_get_status(struct xt_node *node, struct twitter_xml_status *txs)
448{
449        struct xt_node *child, *rt = NULL;
450
451        // Walk over the nodes children.
452        for (child = node->children; child; child = child->next) {
453                if (g_strcasecmp("text", child->name) == 0) {
454                        txs->text = g_memdup(child->text, child->text_len + 1);
455                } else if (g_strcasecmp("retweeted_status", child->name) == 0) {
456                        rt = child;
457                } else if (g_strcasecmp("created_at", child->name) == 0) {
458                        struct tm parsed;
459
460                        /* Very sensitive to changes to the formatting of
461                           this field. :-( Also assumes the timezone used
462                           is UTC since C time handling functions suck. */
463                        if (strptime(child->text, TWITTER_TIME_FORMAT, &parsed) != NULL)
464                                txs->created_at = mktime_utc(&parsed);
465                } else if (g_strcasecmp("user", child->name) == 0) {
466                        txs->user = g_new0(struct twitter_xml_user, 1);
467//                      twitter_xt_get_user(child, txs->user);
468                } else if (g_strcasecmp("id", child->name) == 0) {
469                        txs->id = g_ascii_strtoull(child->text, NULL, 10);
470                } else if (g_strcasecmp("in_reply_to_status_id", child->name) == 0) {
471                        txs->reply_to = g_ascii_strtoull(child->text, NULL, 10);
472                }
473        }
474
475        /* If it's a (truncated) retweet, get the original. Even if the API claims it
476           wasn't truncated because it may be lying. */
477        if (rt) {
478                struct twitter_xml_status *rtxs = g_new0(struct twitter_xml_status, 1);
479                if (twitter_xt_get_status(rt, rtxs) != XT_HANDLED) {
480                        txs_free(rtxs);
481                        return XT_HANDLED;
482                }
483
484                g_free(txs->text);
485                txs->text = g_strdup_printf("RT @%s: %s", rtxs->user->screen_name, rtxs->text);
486                txs_free(rtxs);
487        } else {
488                struct xt_node *urls, *url;
489               
490                urls = xt_find_path(node, "entities");
491                if (urls != NULL)
492                        urls = urls->children;
493                for (; urls; urls = urls->next) {
494                        if (strcmp(urls->name, "urls") != 0 && strcmp(urls->name, "media") != 0)
495                                continue;
496                       
497                        for (url = urls ? urls->children : NULL; url; url = url->next) {
498                                /* "short" is a reserved word. :-P */
499                                struct xt_node *kort = xt_find_node(url->children, "url");
500                                struct xt_node *disp = xt_find_node(url->children, "display_url");
501                                char *pos, *new;
502                               
503                                if (!kort || !kort->text || !disp || !disp->text ||
504                                    !(pos = strstr(txs->text, kort->text)))
505                                        continue;
506                               
507                                *pos = '\0';
508                                new = g_strdup_printf("%s%s &lt;%s&gt;%s", txs->text, kort->text,
509                                                      disp->text, pos + strlen(kort->text));
510                               
511                                g_free(txs->text);
512                                txs->text = new;
513                        }
514                }
515        }
516
517        return XT_HANDLED;
518}
519
520/**
521 * Function to fill a twitter_xml_list struct.
522 * It sets:
523 *  - all <status>es within the <status> element and
524 *  - the next_cursor.
525 */
526static xt_status twitter_xt_get_status_list(struct im_connection *ic, struct xt_node *node,
527                                            struct twitter_xml_list *txl)
528{
529        struct twitter_xml_status *txs;
530        struct xt_node *child;
531        bee_user_t *bu;
532
533        // Set the type of the list.
534        txl->type = TXL_STATUS;
535
536        // The root <statuses> node should hold the list of statuses <status>
537        // Walk over the nodes children.
538        for (child = node->children; child; child = child->next) {
539                if (g_strcasecmp("status", child->name) == 0) {
540                        txs = g_new0(struct twitter_xml_status, 1);
541                        twitter_xt_get_status(child, txs);
542                        // Put the item in the front of the list.
543                        txl->list = g_slist_prepend(txl->list, txs);
544
545                        if (txs->user && txs->user->screen_name &&
546                            (bu = bee_user_by_handle(ic->bee, ic, txs->user->screen_name))) {
547                                struct twitter_user_data *tud = bu->data;
548
549                                if (txs->id > tud->last_id) {
550                                        tud->last_id = txs->id;
551                                        tud->last_time = txs->created_at;
552                                }
553                        }
554                } else if (g_strcasecmp("next_cursor", child->name) == 0) {
555//                      twitter_xt_next_cursor(child, txl);
556                }
557        }
558
559        return XT_HANDLED;
560}
561
562static char *twitter_msg_add_id(struct im_connection *ic,
563                                struct twitter_xml_status *txs, const char *prefix)
564{
565        struct twitter_data *td = ic->proto_data;
566        char *ret = NULL;
567
568        if (!set_getbool(&ic->acc->set, "show_ids")) {
569                if (*prefix)
570                        return g_strconcat(prefix, txs->text, NULL);
571                else
572                        return NULL;
573        }
574
575        td->log[td->log_id].id = txs->id;
576        td->log[td->log_id].bu = bee_user_by_handle(ic->bee, ic, txs->user->screen_name);
577        if (txs->reply_to) {
578                int i;
579                for (i = 0; i < TWITTER_LOG_LENGTH; i++)
580                        if (td->log[i].id == txs->reply_to) {
581                                ret = g_strdup_printf("\002[\002%02d->%02d\002]\002 %s%s",
582                                                      td->log_id, i, prefix, txs->text);
583                                break;
584                        }
585        }
586        if (ret == NULL)
587                ret = g_strdup_printf("\002[\002%02d\002]\002 %s%s", td->log_id, prefix, txs->text);
588        td->log_id = (td->log_id + 1) % TWITTER_LOG_LENGTH;
589
590        return ret;
591}
592
593static void twitter_groupchat_init(struct im_connection *ic)
594{
595        char *name_hint;
596        struct groupchat *gc;
597        struct twitter_data *td = ic->proto_data;
598        GSList *l;
599
600        td->timeline_gc = gc = imcb_chat_new(ic, "twitter/timeline");
601
602        name_hint = g_strdup_printf("%s_%s", td->prefix, ic->acc->user);
603        imcb_chat_name_hint(gc, name_hint);
604        g_free(name_hint);
605
606        for (l = ic->bee->users; l; l = l->next) {
607                bee_user_t *bu = l->data;
608                if (bu->ic == ic)
609                        imcb_chat_add_buddy(td->timeline_gc, bu->handle);
610        }
611}
612
613/**
614 * Function that is called to see the statuses in a groupchat window.
615 */
616static void twitter_groupchat(struct im_connection *ic, GSList * list)
617{
618        struct twitter_data *td = ic->proto_data;
619        GSList *l = NULL;
620        struct twitter_xml_status *status;
621        struct groupchat *gc;
622        guint64 last_id = 0;
623
624        // Create a new groupchat if it does not exsist.
625        if (!td->timeline_gc)
626                twitter_groupchat_init(ic);
627
628        gc = td->timeline_gc;
629        if (!gc->joined)
630                imcb_chat_add_buddy(gc, ic->acc->user);
631
632        for (l = list; l; l = g_slist_next(l)) {
633                char *msg;
634
635                status = l->data;
636                if (status->user == NULL || status->text == NULL || last_id == status->id)
637                        continue;
638
639                last_id = status->id;
640
641                strip_html(status->text);
642
643                if (set_getbool(&ic->acc->set, "strip_newlines"))
644                        strip_newlines(status->text);
645
646                msg = twitter_msg_add_id(ic, status, "");
647
648                // Say it!
649                if (g_strcasecmp(td->user, status->user->screen_name) == 0) {
650                        imcb_chat_log(gc, "You: %s", msg ? msg : status->text);
651                } else {
652                        twitter_add_buddy(ic, status->user->screen_name, status->user->name);
653
654                        imcb_chat_msg(gc, status->user->screen_name,
655                                      msg ? msg : status->text, 0, status->created_at);
656                }
657
658                g_free(msg);
659
660                // Update the timeline_id to hold the highest id, so that by the next request
661                // we won't pick up the updates already in the list.
662                td->timeline_id = MAX(td->timeline_id, status->id);
663        }
664}
665
666/**
667 * Function that is called to see statuses as private messages.
668 */
669static void twitter_private_message_chat(struct im_connection *ic, GSList * list)
670{
671        struct twitter_data *td = ic->proto_data;
672        GSList *l = NULL;
673        struct twitter_xml_status *status;
674        char from[MAX_STRING];
675        gboolean mode_one;
676        guint64 last_id = 0;
677
678        mode_one = g_strcasecmp(set_getstr(&ic->acc->set, "mode"), "one") == 0;
679
680        if (mode_one) {
681                g_snprintf(from, sizeof(from) - 1, "%s_%s", td->prefix, ic->acc->user);
682                from[MAX_STRING - 1] = '\0';
683        }
684
685        for (l = list; l; l = g_slist_next(l)) {
686                char *prefix = NULL, *text = NULL;
687
688                status = l->data;
689                if (status->user == NULL || status->text == NULL || last_id == status->id)
690                        continue;
691
692                last_id = status->id;
693
694                strip_html(status->text);
695                if (mode_one)
696                        prefix = g_strdup_printf("\002<\002%s\002>\002 ",
697                                                 status->user->screen_name);
698                else
699                        twitter_add_buddy(ic, status->user->screen_name, status->user->name);
700
701                text = twitter_msg_add_id(ic, status, prefix ? prefix : "");
702
703                imcb_buddy_msg(ic,
704                               mode_one ? from : status->user->screen_name,
705                               text ? text : status->text, 0, status->created_at);
706
707                // Update the timeline_id to hold the highest id, so that by the next request
708                // we won't pick up the updates already in the list.
709                td->timeline_id = MAX(td->timeline_id, status->id);
710
711                g_free(text);
712                g_free(prefix);
713        }
714}
715
716static void twitter_http_get_home_timeline(struct http_request *req);
717static void twitter_http_get_mentions(struct http_request *req);
718
719/**
720 * Get the timeline with optionally mentions
721 */
722void twitter_get_timeline(struct im_connection *ic, gint64 next_cursor)
723{
724        struct twitter_data *td = ic->proto_data;
725        gboolean include_mentions = set_getbool(&ic->acc->set, "fetch_mentions");
726
727        if (td->flags & TWITTER_DOING_TIMELINE) {
728                if (++td->http_fails >= 5) {
729                        imcb_error(ic, "Fetch timeout (%d)", td->flags);
730                        imc_logout(ic, TRUE);
731                }
732        }
733
734        td->flags |= TWITTER_DOING_TIMELINE;
735
736        twitter_get_home_timeline(ic, next_cursor);
737
738        if (include_mentions) {
739                twitter_get_mentions(ic, next_cursor);
740        }
741}
742
743/**
744 * Call this one after receiving timeline/mentions. Show to user once we have
745 * both.
746 */
747void twitter_flush_timeline(struct im_connection *ic)
748{
749        struct twitter_data *td = ic->proto_data;
750        gboolean include_mentions = set_getbool(&ic->acc->set, "fetch_mentions");
751        int show_old_mentions = set_getint(&ic->acc->set, "show_old_mentions");
752        struct twitter_xml_list *home_timeline = td->home_timeline_obj;
753        struct twitter_xml_list *mentions = td->mentions_obj;
754        GSList *output = NULL;
755        GSList *l;
756
757        if (!(td->flags & TWITTER_GOT_TIMELINE)) {
758                return;
759        }
760
761        if (include_mentions && !(td->flags & TWITTER_GOT_MENTIONS)) {
762                return;
763        }
764
765        if (home_timeline && home_timeline->list) {
766                for (l = home_timeline->list; l; l = g_slist_next(l)) {
767                        output = g_slist_insert_sorted(output, l->data, twitter_compare_elements);
768                }
769        }
770
771        if (include_mentions && mentions && mentions->list) {
772                for (l = mentions->list; l; l = g_slist_next(l)) {
773                        if (show_old_mentions < 1 && output && twitter_compare_elements(l->data, output->data) < 0) {
774                                continue;
775                        }
776
777                        output = g_slist_insert_sorted(output, l->data, twitter_compare_elements);
778                }
779        }
780       
781        if (!(ic->flags & OPT_LOGGED_IN))
782                imcb_connected(ic);
783
784        // See if the user wants to see the messages in a groupchat window or as private messages.
785        if (g_strcasecmp(set_getstr(&ic->acc->set, "mode"), "chat") == 0)
786                twitter_groupchat(ic, output);
787        else
788                twitter_private_message_chat(ic, output);
789
790        g_slist_free(output);
791
792        txl_free(home_timeline);
793        txl_free(mentions);
794
795        td->flags &= ~(TWITTER_DOING_TIMELINE | TWITTER_GOT_TIMELINE | TWITTER_GOT_MENTIONS);
796        td->home_timeline_obj = td->mentions_obj = NULL;
797}
798
799/**
800 * Get the timeline.
801 */
802void twitter_get_home_timeline(struct im_connection *ic, gint64 next_cursor)
803{
804        struct twitter_data *td = ic->proto_data;
805
806        txl_free(td->home_timeline_obj);
807        td->home_timeline_obj = NULL;
808        td->flags &= ~TWITTER_GOT_TIMELINE;
809
810        char *args[6];
811        args[0] = "cursor";
812        args[1] = g_strdup_printf("%lld", (long long) next_cursor);
813        args[2] = "include_entities";
814        args[3] = "true";
815        if (td->timeline_id) {
816                args[4] = "since_id";
817                args[5] = g_strdup_printf("%llu", (long long unsigned int) td->timeline_id);
818        }
819
820        if (twitter_http(ic, TWITTER_HOME_TIMELINE_URL, twitter_http_get_home_timeline, ic, 0, args,
821                     td->timeline_id ? 6 : 4) == NULL) {
822                if (++td->http_fails >= 5)
823                        imcb_error(ic, "Could not retrieve %s: %s",
824                                   TWITTER_HOME_TIMELINE_URL, "connection failed");
825                td->flags |= TWITTER_GOT_TIMELINE;
826                twitter_flush_timeline(ic);
827        }
828
829        g_free(args[1]);
830        if (td->timeline_id) {
831                g_free(args[5]);
832        }
833}
834
835/**
836 * Get mentions.
837 */
838void twitter_get_mentions(struct im_connection *ic, gint64 next_cursor)
839{
840        struct twitter_data *td = ic->proto_data;
841
842        txl_free(td->mentions_obj);
843        td->mentions_obj = NULL;
844        td->flags &= ~TWITTER_GOT_MENTIONS;
845
846        char *args[6];
847        args[0] = "cursor";
848        args[1] = g_strdup_printf("%lld", (long long) next_cursor);
849        args[2] = "include_entities";
850        args[3] = "true";
851        if (td->timeline_id) {
852                args[4] = "since_id";
853                args[5] = g_strdup_printf("%llu", (long long unsigned int) td->timeline_id);
854        } else {
855                args[4] = "count";
856                args[5] = g_strdup_printf("%d", set_getint(&ic->acc->set, "show_old_mentions"));
857        }
858
859        if (twitter_http(ic, TWITTER_MENTIONS_URL, twitter_http_get_mentions,
860                         ic, 0, args, 6) == NULL) {
861                if (++td->http_fails >= 5)
862                        imcb_error(ic, "Could not retrieve %s: %s",
863                                   TWITTER_MENTIONS_URL, "connection failed");
864                td->flags |= TWITTER_GOT_MENTIONS;
865                twitter_flush_timeline(ic);
866        }
867
868        g_free(args[1]);
869        if (td->timeline_id) {
870                g_free(args[5]);
871        }
872}
873
874/**
875 * Callback for getting the home timeline.
876 */
877static void twitter_http_get_home_timeline(struct http_request *req)
878{
879        struct im_connection *ic = req->data;
880        struct twitter_data *td;
881        struct xt_node *parsed;
882        struct twitter_xml_list *txl;
883
884        // Check if the connection is still active.
885        if (!g_slist_find(twitter_connections, ic))
886                return;
887
888        td = ic->proto_data;
889
890        txl = g_new0(struct twitter_xml_list, 1);
891        txl->list = NULL;
892
893        // The root <statuses> node should hold the list of statuses <status>
894        if (!(parsed = twitter_parse_response(ic, req)))
895                goto end;
896        twitter_xt_get_status_list(ic, parsed, txl);
897//      json_value_free(parsed);
898
899        td->home_timeline_obj = txl;
900
901      end:
902        td->flags |= TWITTER_GOT_TIMELINE;
903
904        twitter_flush_timeline(ic);
905}
906
907/**
908 * Callback for getting mentions.
909 */
910static void twitter_http_get_mentions(struct http_request *req)
911{
912        struct im_connection *ic = req->data;
913        struct twitter_data *td;
914        struct xt_node *parsed;
915        struct twitter_xml_list *txl;
916
917        // Check if the connection is still active.
918        if (!g_slist_find(twitter_connections, ic))
919                return;
920
921        td = ic->proto_data;
922
923        txl = g_new0(struct twitter_xml_list, 1);
924        txl->list = NULL;
925
926        // The root <statuses> node should hold the list of statuses <status>
927        if (!(parsed = twitter_parse_response(ic, req)))
928                goto end;
929        twitter_xt_get_status_list(ic, parsed, txl);
930//      json_value_free(parsed);
931
932        td->mentions_obj = txl;
933
934      end:
935        td->flags |= TWITTER_GOT_MENTIONS;
936
937        twitter_flush_timeline(ic);
938}
939
940/**
941 * Callback to use after sending a POST request to twitter.
942 * (Generic, used for a few kinds of queries.)
943 */
944static void twitter_http_post(struct http_request *req)
945{
946        struct im_connection *ic = req->data;
947        struct twitter_data *td;
948        struct xt_node *parsed, *node;
949
950        // Check if the connection is still active.
951        if (!g_slist_find(twitter_connections, ic))
952                return;
953
954        td = ic->proto_data;
955        td->last_status_id = 0;
956
957        if (!(parsed = twitter_parse_response(ic, req)))
958                return;
959       
960        if ((node = xt_find_node(parsed, "status")) &&
961            (node = xt_find_node(node->children, "id")) && node->text)
962                td->last_status_id = g_ascii_strtoull(node->text, NULL, 10);
963}
964
965/**
966 * Function to POST a new status to twitter.
967 */
968void twitter_post_status(struct im_connection *ic, char *msg, guint64 in_reply_to)
969{
970        char *args[4] = {
971                "status", msg,
972                "in_reply_to_status_id",
973                g_strdup_printf("%llu", (unsigned long long) in_reply_to)
974        };
975        twitter_http(ic, TWITTER_STATUS_UPDATE_URL, twitter_http_post, ic, 1,
976                     args, in_reply_to ? 4 : 2);
977        g_free(args[3]);
978}
979
980
981/**
982 * Function to POST a new message to twitter.
983 */
984void twitter_direct_messages_new(struct im_connection *ic, char *who, char *msg)
985{
986        char *args[4];
987        args[0] = "screen_name";
988        args[1] = who;
989        args[2] = "text";
990        args[3] = msg;
991        // Use the same callback as for twitter_post_status, since it does basically the same.
992        twitter_http(ic, TWITTER_DIRECT_MESSAGES_NEW_URL, twitter_http_post, ic, 1, args, 4);
993}
994
995void twitter_friendships_create_destroy(struct im_connection *ic, char *who, int create)
996{
997        char *args[2];
998        args[0] = "screen_name";
999        args[1] = who;
1000        twitter_http(ic, create ? TWITTER_FRIENDSHIPS_CREATE_URL : TWITTER_FRIENDSHIPS_DESTROY_URL,
1001                     twitter_http_post, ic, 1, args, 2);
1002}
1003
1004void twitter_status_destroy(struct im_connection *ic, guint64 id)
1005{
1006        char *url;
1007        url = g_strdup_printf("%s%llu%s", TWITTER_STATUS_DESTROY_URL,
1008                              (unsigned long long) id, ".json");
1009        twitter_http(ic, url, twitter_http_post, ic, 1, NULL, 0);
1010        g_free(url);
1011}
1012
1013void twitter_status_retweet(struct im_connection *ic, guint64 id)
1014{
1015        char *url;
1016        url = g_strdup_printf("%s%llu%s", TWITTER_STATUS_RETWEET_URL,
1017                              (unsigned long long) id, ".json");
1018        twitter_http(ic, url, twitter_http_post, ic, 1, NULL, 0);
1019        g_free(url);
1020}
1021
1022/**
1023 * Report a user for sending spam.
1024 */
1025void twitter_report_spam(struct im_connection *ic, char *screen_name)
1026{
1027        char *args[2] = {
1028                "screen_name",
1029                NULL,
1030        };
1031        args[1] = screen_name;
1032        twitter_http(ic, TWITTER_REPORT_SPAM_URL, twitter_http_post,
1033                     ic, 1, args, 2);
1034}
1035
1036/**
1037 * Favourite a tweet.
1038 */
1039void twitter_favourite_tweet(struct im_connection *ic, guint64 id)
1040{
1041        char *url;
1042        url = g_strdup_printf("%s%llu%s", TWITTER_FAVORITE_CREATE_URL,
1043                              (unsigned long long) id, ".json");
1044        twitter_http(ic, url, twitter_http_post, ic, 1, NULL, 0);
1045        g_free(url);
1046}
Note: See TracBrowser for help on using the repository browser.