source: protocols/twitter/twitter_lib.c @ e08ae0c

Last change on this file since e08ae0c was e08ae0c, checked in by Wilmer van der Gaast <wilmer@…>, at 2012-11-04T23:39:48Z

Can log in now. Fails to fetch timelines though, which is going to be the
more annoying part anyway. Plus, I want streaming API stuff instead.

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