source: protocols/twitter/twitter_lib.c @ c43f488

Last change on this file since c43f488 was c43f488, checked in by Wilmer van der Gaast <wilmer@…>, at 2012-06-04T10:58:51Z

Remove two hacks for some glib<2.14 versions that are no longer supported.

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