source: protocols/twitter/twitter_lib.c @ 7b8238d

Last change on this file since 7b8238d was ce402b2, checked in by dequis <dx@…>, at 2015-01-26T07:50:54Z

Twitter format strings

Allow users to specify how tweets should be displayed

3 new settings are available to set how tweets are displayed:

  • twitter_format_string for normal tweets
  • retweet_format_string for retweets
  • reply_format_string for replies

For full documentation see the help files

  • Property mode set to 100644
File size: 39.8 KB
RevLine 
[1b221e0]1/***************************************************************************\
2*                                                                           *
3*  BitlBee - An IRC to IM gateway                                           *
4*  Simple module to facilitate twitter functionality.                       *
5*                                                                           *
[199fea6]6*  Copyright 2009-2010 Geert Mulders <g.c.w.m.mulders@gmail.com>            *
[0e788f5]7*  Copyright 2010-2013 Wilmer van der Gaast <wilmer@gaast.net>              *
[1b221e0]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
[08579a1]25/* For strptime(): */
[daae10f]26#if(__sun)
27#else
[08579a1]28#define _XOPEN_SOURCE
[daae10f]29#endif
[08579a1]30
[1b221e0]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 "twitter_lib.h"
[e08ae0c]38#include "json_util.h"
[1b221e0]39#include <ctype.h>
40#include <errno.h>
41
42#define TXL_STATUS 1
[62d2cfb]43#define TXL_USER 2
44#define TXL_ID 3
45
[1b221e0]46struct twitter_xml_list {
[62d2cfb]47        int type;
[8203da9]48        gint64 next_cursor;
[1b221e0]49        GSList *list;
50};
51
52struct twitter_xml_user {
[73ee390]53        guint64 uid;
[1b221e0]54        char *name;
55        char *screen_name;
56};
57
58struct twitter_xml_status {
[08579a1]59        time_t created_at;
[1b221e0]60        char *text;
61        struct twitter_xml_user *user;
[67f6828]62        guint64 id, rt_id; /* Usually equal, with RTs id == *original* id */
63        guint64 reply_to;
[73ee390]64        gboolean from_filter;
[ce402b2]65        struct twitter_xml_status *rt;
[1b221e0]66};
67
[62d2cfb]68/**
69 * Frees a twitter_xml_user struct.
70 */
71static void txu_free(struct twitter_xml_user *txu)
72{
[a26af5c]73        if (txu == NULL)
74                return;
[2322a9f]75
[62d2cfb]76        g_free(txu->name);
77        g_free(txu->screen_name);
[2abceca]78        g_free(txu);
[62d2cfb]79}
80
81/**
82 * Frees a twitter_xml_status struct.
83 */
84static void txs_free(struct twitter_xml_status *txs)
85{
[2322a9f]86        if (txs == NULL)
87                return;
88
[62d2cfb]89        g_free(txs->text);
90        txu_free(txs->user);
[ce402b2]91        txs_free(txs->rt);
[2abceca]92        g_free(txs);
[62d2cfb]93}
94
95/**
96 * Free a twitter_xml_list struct.
97 * type is the type of list the struct holds.
98 */
99static void txl_free(struct twitter_xml_list *txl)
100{
101        GSList *l;
[a26af5c]102        if (txl == NULL)
103                return;
[2322a9f]104
105        for (l = txl->list; l; l = g_slist_next(l)) {
106                if (txl->type == TXL_STATUS) {
[5983eca]107                        txs_free((struct twitter_xml_status *) l->data);
[2322a9f]108                } else if (txl->type == TXL_ID) {
[62d2cfb]109                        g_free(l->data);
[2322a9f]110                } else if (txl->type == TXL_USER) {
[de923d5]111                        txu_free(l->data);
[2322a9f]112                }
113        }
114
[62d2cfb]115        g_slist_free(txl->list);
[fd65edb]116        g_free(txl);
[62d2cfb]117}
118
119/**
[2322a9f]120 * Compare status elements
121 */
122static gint twitter_compare_elements(gconstpointer a, gconstpointer b)
123{
124        struct twitter_xml_status *a_status = (struct twitter_xml_status *) a;
125        struct twitter_xml_status *b_status = (struct twitter_xml_status *) b;
126
127        if (a_status->created_at < b_status->created_at) {
128                return -1;
129        } else if (a_status->created_at > b_status->created_at) {
130                return 1;
131        } else {
132                return 0;
133        }
134}
135
136/**
137 * Add a buddy if it is not already added, set the status to logged in.
[62d2cfb]138 */
[3e69802]139static void twitter_add_buddy(struct im_connection *ic, char *name, const char *fullname)
[62d2cfb]140{
[1014cab]141        struct twitter_data *td = ic->proto_data;
142
[de923d5]143        // Check if the buddy is already in the buddy list.
[5983eca]144        if (!bee_user_by_handle(ic->bee, ic, name)) {
[62d2cfb]145                // The buddy is not in the list, add the buddy and set the status to logged in.
[5983eca]146                imcb_add_buddy(ic, name, NULL);
147                imcb_rename_buddy(ic, name, fullname);
[631ec80]148                if (td->flags & TWITTER_MODE_CHAT) {
[5c18a76]149                        /* Necessary so that nicks always get translated to the
150                           exact Twitter username. */
[5983eca]151                        imcb_buddy_nick_hint(ic, name, name);
[7f557d5]152                        if (td->timeline_gc)
153                                imcb_chat_add_buddy(td->timeline_gc, name);
[631ec80]154                } else if (td->flags & TWITTER_MODE_MANY)
[5983eca]155                        imcb_buddy_status(ic, name, OPT_LOGGED_IN, NULL, NULL);
[62d2cfb]156        }
157}
[1b221e0]158
[a7b9ec7]159/* Warning: May return a malloc()ed value, which will be free()d on the next
[de923d5]160   call. Only for short-term use. NOT THREADSAFE!  */
[6eca2eb]161char *twitter_parse_error(struct http_request *req)
[a7b9ec7]162{
163        static char *ret = NULL;
[5246133]164        json_value *root, *err;
[5983eca]165
[a7b9ec7]166        g_free(ret);
167        ret = NULL;
[5983eca]168
169        if (req->body_size > 0) {
[7a80925]170                root = json_parse(req->reply_body, req->body_size);
[5246133]171                err = json_o_get(root, "errors");
[dff0e0b]172                if (err && err->type == json_array && (err = err->u.array.values[0]) &&
[5246133]173                    err->type == json_object) {
174                        const char *msg = json_o_str(err, "message");
175                        if (msg)
176                                ret = g_strdup_printf("%s (%s)", req->status_string, msg);
177                }
178                json_value_free(root);
[a7b9ec7]179        }
[5983eca]180
[6eca2eb]181        return ret ? ret : req->status_string;
[a7b9ec7]182}
183
[fb351ce]184/* WATCH OUT: This function might or might not destroy your connection.
185   Sub-optimal indeed, but just be careful when this returns NULL! */
[e08ae0c]186static json_value *twitter_parse_response(struct im_connection *ic, struct http_request *req)
[2a6da96]187{
188        gboolean logging_in = !(ic->flags & OPT_LOGGED_IN);
189        gboolean periodic;
190        struct twitter_data *td = ic->proto_data;
[e08ae0c]191        json_value *ret;
[2a6da96]192        char path[64] = "", *s;
193       
194        if ((s = strchr(req->request, ' '))) {
195                path[sizeof(path)-1] = '\0';
196                strncpy(path, s + 1, sizeof(path) - 1);
197                if ((s = strchr(path, '?')) || (s = strchr(path, ' ')))
198                        *s = '\0';
199        }
200       
201        /* Kinda nasty. :-( Trying to suppress error messages, but only
202           for periodic (i.e. mentions/timeline) queries. */
203        periodic = strstr(path, "timeline") || strstr(path, "mentions");
204       
205        if (req->status_code == 401 && logging_in) {
206                /* IIRC Twitter once had an outage where they were randomly
207                   throwing 401s so I'll keep treating this one as fatal
208                   only during login. */
[5246133]209                imcb_error(ic, "Authentication failure (%s)",
210                               twitter_parse_error(req));
[2a6da96]211                imc_logout(ic, FALSE);
212                return NULL;
213        } else if (req->status_code != 200) {
214                // It didn't go well, output the error and return.
215                if (!periodic || logging_in || ++td->http_fails >= 5)
[96dd574]216                        twitter_log(ic, "Error: Could not retrieve %s: %s",
217                                    path, twitter_parse_error(req));
[2a6da96]218               
219                if (logging_in)
220                        imc_logout(ic, TRUE);
221                return NULL;
222        } else {
223                td->http_fails = 0;
224        }
225
[7a80925]226        if ((ret = json_parse(req->reply_body, req->body_size)) == NULL) {
[2a6da96]227                imcb_error(ic, "Could not retrieve %s: %s",
228                           path, "XML parse error");
229        }
230        return ret;
231}
232
[1b221e0]233static void twitter_http_get_friends_ids(struct http_request *req);
234
235/**
236 * Get the friends ids.
237 */
[8203da9]238void twitter_get_friends_ids(struct im_connection *ic, gint64 next_cursor)
[1b221e0]239{
[85c3004]240        // Primitive, but hey! It works...
[5983eca]241        char *args[2];
[1b221e0]242        args[0] = "cursor";
[85c3004]243        args[1] = g_strdup_printf("%" G_GINT64_FORMAT, next_cursor);
[bb5ce4d1]244        twitter_http(ic, TWITTER_FRIENDS_IDS_URL, twitter_http_get_friends_ids, ic, 0, args, 2);
[1b221e0]245
246        g_free(args[1]);
247}
248
249/**
250 * Fill a list of ids.
251 */
[9e8c945]252static gboolean twitter_xt_get_friends_id_list(json_value *node, struct twitter_xml_list *txl)
[1b221e0]253{
[e08ae0c]254        json_value *c;
255        int i;
[5983eca]256
[62d2cfb]257        // Set the list type.
258        txl->type = TXL_ID;
[1b221e0]259
[e08ae0c]260        c = json_o_get(node, "ids");
261        if (!c || c->type != json_array)
[9e8c945]262                return FALSE;
[1b221e0]263
[e08ae0c]264        for (i = 0; i < c->u.array.length; i ++) {
[0688e99]265                if (c->u.array.values[i]->type != json_integer)
266                        continue;
267               
[e08ae0c]268                txl->list = g_slist_prepend(txl->list,
[7a80925]269                        g_strdup_printf("%" PRIu64, c->u.array.values[i]->u.integer));
[e08ae0c]270        }
271       
272        c = json_o_get(node, "next_cursor");
273        if (c && c->type == json_integer)
274                txl->next_cursor = c->u.integer;
275        else
276                txl->next_cursor = -1;
277       
[9e8c945]278        return TRUE;
[1b221e0]279}
280
[de923d5]281static void twitter_get_users_lookup(struct im_connection *ic);
282
[1b221e0]283/**
284 * Callback for getting the friends ids.
285 */
286static void twitter_http_get_friends_ids(struct http_request *req)
287{
288        struct im_connection *ic;
[e08ae0c]289        json_value *parsed;
[1b221e0]290        struct twitter_xml_list *txl;
[3bd4a93]291        struct twitter_data *td;
[1b221e0]292
293        ic = req->data;
294
[62d2cfb]295        // Check if the connection is still active.
[5983eca]296        if (!g_slist_find(twitter_connections, ic))
[62d2cfb]297                return;
[5983eca]298
[37aa317]299        td = ic->proto_data;
[62d2cfb]300
[1b221e0]301        txl = g_new0(struct twitter_xml_list, 1);
[de923d5]302        txl->list = td->follow_ids;
[1b221e0]303
304        // Parse the data.
[2a6da96]305        if (!(parsed = twitter_parse_response(ic, req)))
306                return;
[e08ae0c]307       
[d0752e8]308        twitter_xt_get_friends_id_list(parsed, txl);
[e08ae0c]309        json_value_free(parsed);
[1b221e0]310
[de923d5]311        td->follow_ids = txl->list;
[1b221e0]312        if (txl->next_cursor)
[de923d5]313                /* These were just numbers. Up to 4000 in a response AFAIK so if we get here
314                   we may be using a spammer account. \o/ */
[1b221e0]315                twitter_get_friends_ids(ic, txl->next_cursor);
[de923d5]316        else
317                /* Now to convert all those numbers into names.. */
318                twitter_get_users_lookup(ic);
319
320        txl->list = NULL;
321        txl_free(txl);
322}
323
[9e8c945]324static gboolean twitter_xt_get_users(json_value *node, struct twitter_xml_list *txl);
[de923d5]325static void twitter_http_get_users_lookup(struct http_request *req);
326
327static void twitter_get_users_lookup(struct im_connection *ic)
328{
329        struct twitter_data *td = ic->proto_data;
330        char *args[2] = {
331                "user_id",
332                NULL,
333        };
334        GString *ids = g_string_new("");
335        int i;
336       
337        /* We can request up to 100 users at a time. */
338        for (i = 0; i < 100 && td->follow_ids; i ++) {
339                g_string_append_printf(ids, ",%s", (char*) td->follow_ids->data);
340                g_free(td->follow_ids->data);
341                td->follow_ids = g_slist_remove(td->follow_ids, td->follow_ids->data);
342        }
343        if (ids->len > 0) {
344                args[1] = ids->str + 1;
345                /* POST, because I think ids can be up to 1KB long. */
346                twitter_http(ic, TWITTER_USERS_LOOKUP_URL, twitter_http_get_users_lookup, ic, 1, args, 2);
347        } else {
348                /* We have all users. Continue with login. (Get statuses.) */
349                td->flags |= TWITTER_HAVE_FRIENDS;
350                twitter_login_finish(ic);
351        }
352        g_string_free(ids, TRUE);
353}
354
355/**
356 * Callback for getting (twitter)friends...
357 *
358 * Be afraid, be very afraid! This function will potentially add hundreds of "friends". "Who has
359 * hundreds of friends?" you wonder? You probably not, since you are reading the source of
360 * BitlBee... Get a life and meet new people!
361 */
362static void twitter_http_get_users_lookup(struct http_request *req)
363{
364        struct im_connection *ic = req->data;
[e08ae0c]365        json_value *parsed;
[de923d5]366        struct twitter_xml_list *txl;
367        GSList *l = NULL;
368        struct twitter_xml_user *user;
369
370        // Check if the connection is still active.
371        if (!g_slist_find(twitter_connections, ic))
372                return;
373
374        txl = g_new0(struct twitter_xml_list, 1);
375        txl->list = NULL;
[1b221e0]376
[de923d5]377        // Get the user list from the parsed xml feed.
[2a6da96]378        if (!(parsed = twitter_parse_response(ic, req)))
379                return;
[d0752e8]380        twitter_xt_get_users(parsed, txl);
[e08ae0c]381        json_value_free(parsed);
[de923d5]382
383        // Add the users as buddies.
384        for (l = txl->list; l; l = g_slist_next(l)) {
385                user = l->data;
386                twitter_add_buddy(ic, user->screen_name, user->name);
387        }
388
389        // Free the structure.
[62d2cfb]390        txl_free(txl);
[de923d5]391
392        twitter_get_users_lookup(ic);
[1b221e0]393}
394
[8e3b7ac]395struct twitter_xml_user *twitter_xt_get_user(const json_value *node)
396{
397        struct twitter_xml_user *txu;
[73ee390]398        json_value *jv;
[8e3b7ac]399       
400        txu = g_new0(struct twitter_xml_user, 1);
401        txu->name = g_strdup(json_o_str(node, "name"));
402        txu->screen_name = g_strdup(json_o_str(node, "screen_name"));
403       
[73ee390]404        jv = json_o_get(node, "id");
405        txu->uid = jv->u.integer;
406       
[8e3b7ac]407        return txu;
408}
409
[62d2cfb]410/**
411 * Function to fill a twitter_xml_list struct.
412 * It sets:
413 *  - all <user>s from the <users> element.
414 */
[9e8c945]415static gboolean twitter_xt_get_users(json_value *node, struct twitter_xml_list *txl)
[62d2cfb]416{
417        struct twitter_xml_user *txu;
[e08ae0c]418        int i;
[62d2cfb]419
420        // Set the type of the list.
421        txl->type = TXL_USER;
422
[e08ae0c]423        if (!node || node->type != json_array)
[9e8c945]424                return FALSE;
[e08ae0c]425
[62d2cfb]426        // The root <users> node should hold the list of users <user>
427        // Walk over the nodes children.
[e08ae0c]428        for (i = 0; i < node->u.array.length; i ++) {
[8e3b7ac]429                txu = twitter_xt_get_user(node->u.array.values[i]);
430                if (txu)
431                        txl->list = g_slist_prepend(txl->list, txu);
[62d2cfb]432        }
433
[9e8c945]434        return TRUE;
[62d2cfb]435}
436
[2b02617]437#ifdef __GLIBC__
438#define TWITTER_TIME_FORMAT "%a %b %d %H:%M:%S %z %Y"
439#else
440#define TWITTER_TIME_FORMAT "%a %b %d %H:%M:%S +0000 %Y"
441#endif
[62d2cfb]442
[d1356cb]443static char* expand_entities(char* text, const json_value *entities);
444
[1b221e0]445/**
446 * Function to fill a twitter_xml_status struct.
447 * It sets:
448 *  - the status text and
449 *  - the created_at timestamp and
450 *  - the status id and
451 *  - the user in a twitter_xml_user struct.
452 */
[c9b5817]453static struct twitter_xml_status *twitter_xt_get_status(const json_value *node)
[1b221e0]454{
[c9b5817]455        struct twitter_xml_status *txs;
[fb351ce]456        const json_value *rt = NULL, *entities = NULL;
[8e3b7ac]457       
458        if (node->type != json_object)
[9e8c945]459                return FALSE;
[c9b5817]460        txs = g_new0(struct twitter_xml_status, 1);
[1b221e0]461
[9e8c945]462        JSON_O_FOREACH (node, k, v) {
[8e3b7ac]463                if (strcmp("text", k) == 0 && v->type == json_string) {
[fb351ce]464                        txs->text = g_memdup(v->u.string.ptr, v->u.string.length + 1);
[29f72b7]465                        strip_html(txs->text);
[8e3b7ac]466                } else if (strcmp("retweeted_status", k) == 0 && v->type == json_object) {
467                        rt = v;
468                } else if (strcmp("created_at", k) == 0 && v->type == json_string) {
[08579a1]469                        struct tm parsed;
[5983eca]470
[08579a1]471                        /* Very sensitive to changes to the formatting of
472                           this field. :-( Also assumes the timezone used
473                           is UTC since C time handling functions suck. */
[8e3b7ac]474                        if (strptime(v->u.string.ptr, TWITTER_TIME_FORMAT, &parsed) != NULL)
[5983eca]475                                txs->created_at = mktime_utc(&parsed);
[8e3b7ac]476                } else if (strcmp("user", k) == 0 && v->type == json_object) {
477                        txs->user = twitter_xt_get_user(v);
478                } else if (strcmp("id", k) == 0 && v->type == json_integer) {
[573e274]479                        txs->rt_id = txs->id = v->u.integer;
[8e3b7ac]480                } else if (strcmp("in_reply_to_status_id", k) == 0 && v->type == json_integer) {
481                        txs->reply_to = v->u.integer;
482                } else if (strcmp("entities", k) == 0 && v->type == json_object) {
[fb351ce]483                        entities = v;
[ce81acd]484                }
[1b221e0]485        }
[5983eca]486
[0fff0b2]487        /* If it's a (truncated) retweet, get the original. Even if the API claims it
488           wasn't truncated because it may be lying. */
489        if (rt) {
[c9b5817]490                struct twitter_xml_status *rtxs = twitter_xt_get_status(rt);
491                if (rtxs) {
492                        g_free(txs->text);
[ce402b2]493                        txs->text = g_strdup(rtxs->text);
[c9b5817]494                        txs->id = rtxs->id;
[ce402b2]495                        txs->rt = rtxs;
[e193aeb]496                }
[fb351ce]497        } else if (entities) {
[d1356cb]498                txs->text = expand_entities(txs->text, entities);
499        }
500
[c9b5817]501        if (txs->text && txs->user && txs->id)
502                return txs;
503       
504        txs_free(txs);
505        return NULL;
[d1356cb]506}
507
508/**
509 * Function to fill a twitter_xml_status struct (DM variant).
510 */
[2cd8540]511static struct twitter_xml_status *twitter_xt_get_dm(const json_value *node)
[d1356cb]512{
[2cd8540]513        struct twitter_xml_status *txs;
[d1356cb]514        const json_value *entities = NULL;
515       
516        if (node->type != json_object)
517                return FALSE;
[2cd8540]518        txs = g_new0(struct twitter_xml_status, 1);
[d1356cb]519
520        JSON_O_FOREACH (node, k, v) {
521                if (strcmp("text", k) == 0 && v->type == json_string) {
522                        txs->text = g_memdup(v->u.string.ptr, v->u.string.length + 1);
[29f72b7]523                        strip_html(txs->text);
[d1356cb]524                } else if (strcmp("created_at", k) == 0 && v->type == json_string) {
525                        struct tm parsed;
526
527                        /* Very sensitive to changes to the formatting of
528                           this field. :-( Also assumes the timezone used
529                           is UTC since C time handling functions suck. */
530                        if (strptime(v->u.string.ptr, TWITTER_TIME_FORMAT, &parsed) != NULL)
531                                txs->created_at = mktime_utc(&parsed);
532                } else if (strcmp("sender", k) == 0 && v->type == json_object) {
533                        txs->user = twitter_xt_get_user(v);
534                } else if (strcmp("id", k) == 0 && v->type == json_integer) {
535                        txs->id = v->u.integer;
536                }
537        }
538
539        if (entities) {
540                txs->text = expand_entities(txs->text, entities);
541        }
542
[2cd8540]543        if (txs->text && txs->user && txs->id)
544                return txs;
545       
546        txs_free(txs);
547        return NULL;
[d1356cb]548}
549
550static char* expand_entities(char* text, const json_value *entities) {
551        JSON_O_FOREACH (entities, k, v) {
552                int i;
553               
554                if (v->type != json_array)
555                        continue;
556                if (strcmp(k, "urls") != 0 && strcmp(k, "media") != 0)
557                        continue;
558               
559                for (i = 0; i < v->u.array.length; i ++) {
560                        if (v->u.array.values[i]->type != json_object)
[8e3b7ac]561                                continue;
[d1356cb]562                       
563                        const char *kort = json_o_str(v->u.array.values[i], "url");
564                        const char *disp = json_o_str(v->u.array.values[i], "display_url");
565                        char *pos, *new;
566                       
567                        if (!kort || !disp || !(pos = strstr(text, kort)))
[429a9b1]568                                continue;
569                       
[d1356cb]570                        *pos = '\0';
[29f72b7]571                        new = g_strdup_printf("%s%s <%s>%s", text, kort,
[d1356cb]572                                              disp, pos + strlen(kort));
573                       
574                        g_free(text);
575                        text = new;
[429a9b1]576                }
[e193aeb]577        }
[d1356cb]578       
579        return text;
[1b221e0]580}
581
582/**
583 * Function to fill a twitter_xml_list struct.
584 * It sets:
585 *  - all <status>es within the <status> element and
586 *  - the next_cursor.
587 */
[9e8c945]588static gboolean twitter_xt_get_status_list(struct im_connection *ic, const json_value *node,
589                                           struct twitter_xml_list *txl)
[1b221e0]590{
591        struct twitter_xml_status *txs;
[8e3b7ac]592        int i;
[1b221e0]593
[62d2cfb]594        // Set the type of the list.
595        txl->type = TXL_STATUS;
[8e3b7ac]596       
597        if (node->type != json_array)
[9e8c945]598                return FALSE;
[62d2cfb]599
[1b221e0]600        // The root <statuses> node should hold the list of statuses <status>
601        // Walk over the nodes children.
[8e3b7ac]602        for (i = 0; i < node->u.array.length; i ++) {
[c9b5817]603                txs = twitter_xt_get_status(node->u.array.values[i]);
604                if (!txs)
605                        continue;
606               
[8e3b7ac]607                txl->list = g_slist_prepend(txl->list, txs);
[1b221e0]608        }
609
[9e8c945]610        return TRUE;
[1b221e0]611}
612
[ce402b2]613/**
614 * Function to properly format a tweet as per the users configuration.
615 */
616static char *twitter_msg_get_text(struct im_connection *ic, int log_id, int reply_to,
617                                struct twitter_xml_status *txs, const char *prefix) {
618        gchar * format = set_getstr(&ic->acc->set, "format_string");
619        GString * text = g_string_new(NULL);
620
621        gchar *c;
622        if (reply_to != -1)
623                format = set_getstr(&ic->acc->set, "reply_format_string");
624        if (txs->rt)
625                format = set_getstr(&ic->acc->set, "retweet_format_string");
626
627        for (c = format; *c ; c++) {
628                if (!(*c == '%' && *(c+1))) {
629                        text = g_string_append_c(text, *c);
630                        continue;
631                }
632                c++; // Move past the %
633                switch (*c) {
634                        case 'i':
635                                g_string_append_printf(text, "%02x", log_id);
636                                break;
637                        case 'r':
638                                if (reply_to != -1) // In case someone does put %r in the wrong format_string
639                                g_string_append_printf(text, "%02x", reply_to);
640                                break;
641                        case 'a':
642                                if (txs->rt) // In case someone does put %a in the wrong format_string
643                                        text = g_string_append(text, txs->rt->user->screen_name);
644                                break;
645                        case 'c':
646                                text = g_string_append(text, txs->text);
647                                break;
648                        default:
649                                text = g_string_append_c(text, *c);
650                }
651        }
652        text = g_string_prepend(text, prefix);
653        return g_string_free(text, FALSE);
654}
655
[c9b5817]656/* Will log messages either way. Need to keep track of IDs for stream deduping.
657   Plus, show_ids is on by default and I don't see why anyone would disable it. */
[ce81acd]658static char *twitter_msg_add_id(struct im_connection *ic,
[5983eca]659                                struct twitter_xml_status *txs, const char *prefix)
[ce81acd]660{
661        struct twitter_data *td = ic->proto_data;
[c9b5817]662        int reply_to = -1;
663        bee_user_t *bu;
[5983eca]664
665        if (txs->reply_to) {
[ce81acd]666                int i;
[5983eca]667                for (i = 0; i < TWITTER_LOG_LENGTH; i++)
668                        if (td->log[i].id == txs->reply_to) {
[c9b5817]669                                reply_to = i;
[ce81acd]670                                break;
671                        }
672        }
[5983eca]673
[c9b5817]674        if (txs->user && txs->user->screen_name &&
675            (bu = bee_user_by_handle(ic->bee, ic, txs->user->screen_name))) {
676                struct twitter_user_data *tud = bu->data;
677
678                if (txs->id > tud->last_id) {
679                        tud->last_id = txs->id;
680                        tud->last_time = txs->created_at;
681                }
682        }
683       
684        td->log_id = (td->log_id + 1) % TWITTER_LOG_LENGTH;
685        td->log[td->log_id].id = txs->id;
686        td->log[td->log_id].bu = bee_user_by_handle(ic->bee, ic, txs->user->screen_name);
687       
[67f6828]688        /* This is all getting hairy. :-( If we RT'ed something ourselves,
689           remember OUR id instead so undo will work. In other cases, the
690           original tweet's id should be remembered for deduplicating. */
[9f8bb17]691        if (g_strcasecmp(txs->user->screen_name, td->user) == 0)
[67f6828]692                td->log[td->log_id].id = txs->rt_id;
693       
[ce402b2]694        return twitter_msg_get_text(ic, td->log_id, reply_to, txs, prefix);
[ce81acd]695}
696
[73ee390]697/**
698 * Function that is called to see the filter statuses in groupchat windows.
699 */
700static void twitter_status_show_filter(struct im_connection *ic, struct twitter_xml_status *status)
701{
702        struct twitter_data *td = ic->proto_data;
703        char *msg = twitter_msg_add_id(ic, status, "");
704        struct twitter_filter *tf;
705        GSList *f;
706        GSList *l;
707
708        for (f = td->filters; f; f = g_slist_next(f)) {
709                tf = f->data;
710
711                switch (tf->type) {
712                case TWITTER_FILTER_TYPE_FOLLOW:
713                        if (status->user->uid != tf->uid)
714                                continue;
715                        break;
716
717                case TWITTER_FILTER_TYPE_TRACK:
718                        if (strcasestr(status->text, tf->text) == NULL)
719                                continue;
720                        break;
721
722                default:
723                        continue;
724                }
725
726                for (l = tf->groupchats; l; l = g_slist_next(l)) {
727                        imcb_chat_msg(l->data, status->user->screen_name,
728                                      msg ? msg : status->text, 0, 0);
729                }
730        }
731
732        g_free(msg);
733}
734
[62d2cfb]735/**
736 * Function that is called to see the statuses in a groupchat window.
737 */
[29f72b7]738static void twitter_status_show_chat(struct im_connection *ic, struct twitter_xml_status *status)
[62d2cfb]739{
740        struct twitter_data *td = ic->proto_data;
741        struct groupchat *gc;
[29f72b7]742        gboolean me = g_strcasecmp(td->user, status->user->screen_name) == 0;
743        char *msg;
[62d2cfb]744
745        // Create a new groupchat if it does not exsist.
[631ec80]746        gc = twitter_groupchat_init(ic);
[62d2cfb]747
[29f72b7]748        if (!me)
749                /* MUST be done before twitter_msg_add_id() to avoid #872. */
750                twitter_add_buddy(ic, status->user->screen_name, status->user->name);
751        msg = twitter_msg_add_id(ic, status, "");
752       
753        // Say it!
754        if (me) {
755                imcb_chat_log(gc, "You: %s", msg ? msg : status->text);
756        } else {
757                imcb_chat_msg(gc, status->user->screen_name,
758                              msg ? msg : status->text, 0, status->created_at);
[62d2cfb]759        }
[29f72b7]760
761        g_free(msg);
[62d2cfb]762}
763
764/**
765 * Function that is called to see statuses as private messages.
766 */
[29f72b7]767static void twitter_status_show_msg(struct im_connection *ic, struct twitter_xml_status *status)
[62d2cfb]768{
769        struct twitter_data *td = ic->proto_data;
[631ec80]770        char from[MAX_STRING] = "";
[29f72b7]771        char *prefix = NULL, *text = NULL;
772        gboolean me = g_strcasecmp(td->user, status->user->screen_name) == 0;
[62d2cfb]773
[631ec80]774        if (td->flags & TWITTER_MODE_ONE) {
[5983eca]775                g_snprintf(from, sizeof(from) - 1, "%s_%s", td->prefix, ic->acc->user);
776                from[MAX_STRING - 1] = '\0';
[e88fbe27]777        }
[5983eca]778
[29f72b7]779        if (td->flags & TWITTER_MODE_ONE)
780                prefix = g_strdup_printf("\002<\002%s\002>\002 ",
781                                         status->user->screen_name);
782        else if (!me)
783                twitter_add_buddy(ic, status->user->screen_name, status->user->name);
784        else
785                prefix = g_strdup("You: ");
[5983eca]786
[29f72b7]787        text = twitter_msg_add_id(ic, status, prefix ? prefix : "");
[5983eca]788
[29f72b7]789        imcb_buddy_msg(ic,
790                       *from ? from : status->user->screen_name,
791                       text ? text : status->text, 0, status->created_at);
[5983eca]792
[29f72b7]793        g_free(text);
794        g_free(prefix);
795}
[5983eca]796
[29f72b7]797static void twitter_status_show(struct im_connection *ic, struct twitter_xml_status *status)
798{
799        struct twitter_data *td = ic->proto_data;
[7549d00]800        char *last_id_str;
[29f72b7]801       
802        if (status->user == NULL || status->text == NULL)
803                return;
804       
805        /* Grrrr. Would like to do this during parsing, but can't access
806           settings from there. */
807        if (set_getbool(&ic->acc->set, "strip_newlines"))
808                strip_newlines(status->text);
809       
[73ee390]810        if (status->from_filter)
811                twitter_status_show_filter(ic, status);
812        else if (td->flags & TWITTER_MODE_CHAT)
[29f72b7]813                twitter_status_show_chat(ic, status);
814        else
815                twitter_status_show_msg(ic, status);
[5983eca]816
[29f72b7]817        // Update the timeline_id to hold the highest id, so that by the next request
818        // we won't pick up the updates already in the list.
[573e274]819        td->timeline_id = MAX(td->timeline_id, status->rt_id);
[7549d00]820
821        last_id_str = g_strdup_printf("%" G_GUINT64_FORMAT, td->timeline_id);
822        set_setstr(&ic->acc->set, "last_tweet", last_id_str);
823        g_free(last_id_str);
[62d2cfb]824}
825
[73ee390]826static gboolean twitter_stream_handle_object(struct im_connection *ic, json_value *o, gboolean from_filter);
[ddc2de5]827
828static void twitter_http_stream(struct http_request *req)
829{
[dff0e0b]830        struct im_connection *ic = req->data;
[dd672e2]831        struct twitter_data *td;
[dff0e0b]832        json_value *parsed;
[62f6b45]833        int len = 0;
834        char c, *nl;
[73ee390]835        gboolean from_filter;
[dff0e0b]836       
837        if (!g_slist_find(twitter_connections, ic))
838                return;
[ddc2de5]839       
[e132b60]840        ic->flags |= OPT_PONGED;
[dd672e2]841        td = ic->proto_data;
842       
843        if ((req->flags & HTTPC_EOF) || !req->reply_body) {
[73ee390]844                if (req == td->stream)
845                        td->stream = NULL;
846                else if (req == td->filter_stream)
847                        td->filter_stream = NULL;
848
[dd672e2]849                imcb_error(ic, "Stream closed (%s)", req->status_string);
850                imc_logout(ic, TRUE);
851                return;
852        }
853       
[62f6b45]854        /* MUST search for CRLF, not just LF:
855           https://dev.twitter.com/docs/streaming-apis/processing#Parsing_responses */
[c1d9c95]856        if (!(nl = strstr(req->reply_body, "\r\n")))
[ddc2de5]857                return;
858       
[62f6b45]859        len = nl - req->reply_body;
860        if (len > 0) {
861                c = req->reply_body[len];
862                req->reply_body[len] = '\0';
863               
[7a80925]864                if ((parsed = json_parse(req->reply_body, req->body_size))) {
[73ee390]865                        from_filter = (req == td->filter_stream);
866                        twitter_stream_handle_object(ic, parsed, from_filter);
[62f6b45]867                }
868                json_value_free(parsed);
869                req->reply_body[len] = c;
[dff0e0b]870        }
[ddc2de5]871       
[62f6b45]872        http_flush_bytes(req, len + 2);
[dff0e0b]873       
874        /* One notification might bring multiple events! */
875        if (req->body_size > 0)
876                twitter_http_stream(req);
[ddc2de5]877}
[2322a9f]878
[5aa96fc8]879static gboolean twitter_stream_handle_event(struct im_connection *ic, json_value *o);
[c9b5817]880static gboolean twitter_stream_handle_status(struct im_connection *ic, struct twitter_xml_status *txs);
[5aa96fc8]881
[73ee390]882static gboolean twitter_stream_handle_object(struct im_connection *ic, json_value *o, gboolean from_filter)
[dff0e0b]883{
[5aa96fc8]884        struct twitter_data *td = ic->proto_data;
[c9b5817]885        struct twitter_xml_status *txs;
[d1356cb]886        json_value *c;
[dff0e0b]887       
[c9b5817]888        if ((txs = twitter_xt_get_status(o))) {
[73ee390]889                txs->from_filter = from_filter;
[2dcde94]890                gboolean ret = twitter_stream_handle_status(ic, txs);
891                txs_free(txs);
892                return ret;
[d1356cb]893        } else if ((c = json_o_get(o, "direct_message")) &&
[2cd8540]894                   (txs = twitter_xt_get_dm(c))) {
[9f8bb17]895                if (g_strcasecmp(txs->user->screen_name, td->user) != 0)
[2cd8540]896                        imcb_buddy_msg(ic, txs->user->screen_name,
897                                       txs->text, 0, txs->created_at);
[d1356cb]898                txs_free(txs);
899                return TRUE;
[5aa96fc8]900        } else if ((c = json_o_get(o, "event")) && c->type == json_string) {
901                twitter_stream_handle_event(ic, o);
902                return TRUE;
903        } else if ((c = json_o_get(o, "disconnect")) && c->type == json_object) {
904                /* HACK: Because we're inside an event handler, we can't just
905                   disconnect here. Instead, just change the HTTP status string
906                   into a Twitter status string. */
907                char *reason = json_o_strdup(c, "reason");
908                if (reason) {
909                        g_free(td->stream->status_string);
910                        td->stream->status_string = reason;
911                }
912                return TRUE;
[dff0e0b]913        }
914        return FALSE;
915}
916
[c9b5817]917static gboolean twitter_stream_handle_status(struct im_connection *ic, struct twitter_xml_status *txs)
918{
919        struct twitter_data *td = ic->proto_data;
920        int i;
921       
922        for (i = 0; i < TWITTER_LOG_LENGTH; i++) {
923                if (td->log[i].id == txs->id) {
[29f72b7]924                        /* Got a duplicate (RT, probably). Drop it. */
[c9b5817]925                        return TRUE;
926                }
927        }
928       
[9f8bb17]929        if (!(g_strcasecmp(txs->user->screen_name, td->user) == 0 ||
[2dcde94]930              set_getbool(&ic->acc->set, "fetch_mentions") ||
[c9b5817]931              bee_user_by_handle(ic->bee, ic, txs->user->screen_name))) {
932                /* Tweet is from an unknown person and the user does not want
933                   to see @mentions, so drop it. twitter_stream_handle_event()
934                   picks up new follows so this simple filter should be safe. */
935                /* TODO: The streaming API seems to do poor @mention matching.
936                   I.e. I'm getting mentions for @WilmerSomething, not just for
937                   @Wilmer. But meh. You want spam, you get spam. */
938                return TRUE;
939        }
940       
[29f72b7]941        twitter_status_show(ic, txs);
942       
[c9b5817]943        return TRUE;
944}
945
[5aa96fc8]946static gboolean twitter_stream_handle_event(struct im_connection *ic, json_value *o)
947{
948        struct twitter_data *td = ic->proto_data;
949        json_value *source = json_o_get(o, "source");
950        json_value *target = json_o_get(o, "target");
951        const char *type = json_o_str(o, "event");
952       
953        if (!type || !source || source->type != json_object
954                  || !target || target->type != json_object) {
955                return FALSE;
956        }
957       
958        if (strcmp(type, "follow") == 0) {
959                struct twitter_xml_user *us = twitter_xt_get_user(source);
960                struct twitter_xml_user *ut = twitter_xt_get_user(target);
[9f8bb17]961                if (g_strcasecmp(us->screen_name, td->user) == 0) {
[5aa96fc8]962                        twitter_add_buddy(ic, ut->screen_name, ut->name);
963                }
964                txu_free(us);
965                txu_free(ut);
966        }
967       
968        return TRUE;
969}
970
[dff0e0b]971gboolean twitter_open_stream(struct im_connection *ic)
972{
973        struct twitter_data *td = ic->proto_data;
[62f6b45]974        char *args[2] = {"with", "followings"};
[dff0e0b]975       
976        if ((td->stream = twitter_http(ic, TWITTER_USER_STREAM_URL,
[62f6b45]977                                       twitter_http_stream, ic, 0, args, 2))) {
[dff0e0b]978                /* This flag must be enabled or we'll get no data until EOF
979                   (which err, kind of, defeats the purpose of a streaming API). */
980                td->stream->flags |= HTTPC_STREAMING;
981                return TRUE;
982        }
983       
984        return FALSE;
985}
986
[73ee390]987static gboolean twitter_filter_stream(struct im_connection *ic)
988{
989        struct twitter_data *td = ic->proto_data;
990        char *args[4] = {"follow", NULL, "track", NULL};
991        GString *followstr = g_string_new("");
992        GString *trackstr = g_string_new("");
993        gboolean ret = FALSE;
994        struct twitter_filter *tf;
995        GSList *l;
996
997        for (l = td->filters; l; l = g_slist_next(l)) {
998                tf = l->data;
999
1000                switch (tf->type) {
1001                case TWITTER_FILTER_TYPE_FOLLOW:
1002                        if (followstr->len > 0)
1003                                g_string_append_c(followstr, ',');
1004
1005                        g_string_append_printf(followstr, "%" G_GUINT64_FORMAT,
1006                                               tf->uid);
1007                        break;
1008
1009                case TWITTER_FILTER_TYPE_TRACK:
1010                        if (trackstr->len > 0)
1011                                g_string_append_c(trackstr, ',');
1012
1013                        g_string_append(trackstr, tf->text);
1014                        break;
1015
1016                default:
1017                        continue;
1018                }
1019        }
1020
1021        args[1] = followstr->str;
1022        args[3] = trackstr->str;
1023
1024        if (td->filter_stream)
1025                http_close(td->filter_stream);
1026
1027        if ((td->filter_stream = twitter_http(ic, TWITTER_FILTER_STREAM_URL,
1028                                              twitter_http_stream, ic, 0,
1029                                              args, 4))) {
1030                /* This flag must be enabled or we'll get no data until EOF
1031                   (which err, kind of, defeats the purpose of a streaming API). */
1032                td->filter_stream->flags |= HTTPC_STREAMING;
1033                ret = TRUE;
1034        }
1035
1036        g_string_free(followstr, TRUE);
1037        g_string_free(trackstr, TRUE);
1038
1039        return ret;
1040}
1041
1042static void twitter_filter_users_post(struct http_request *req)
1043{
1044        struct im_connection *ic = req->data;
1045        struct twitter_data *td;
1046        struct twitter_filter *tf;
1047        GList *users = NULL;
1048        json_value *parsed;
1049        json_value *id;
1050        const char *name;
1051        GString *fstr;
1052        GSList *l;
1053        GList *u;
1054        int i;
1055
1056        // Check if the connection is still active.
1057        if (!g_slist_find(twitter_connections, ic))
1058                return;
1059
1060        td = ic->proto_data;
1061
1062        if (!(parsed = twitter_parse_response(ic, req)))
1063                return;
1064
1065        for (l = td->filters; l; l = g_slist_next(l)) {
1066                tf = l->data;
1067
1068                if (tf->type == TWITTER_FILTER_TYPE_FOLLOW)
1069                        users = g_list_prepend(users, tf);
1070        }
1071
1072        if (parsed->type != json_array)
1073                goto finish;
1074
1075        for (i = 0; i < parsed->u.array.length; i++) {
1076                id = json_o_get(parsed->u.array.values[i], "id");
1077                name = json_o_str(parsed->u.array.values[i], "screen_name");
1078
1079                if (!name || !id || id->type != json_integer)
1080                        continue;
1081
1082                for (u = users; u; u = g_list_next(u)) {
1083                        tf = u->data;
1084
1085                        if (g_strcasecmp(tf->text, name) == 0) {
1086                                tf->uid = id->u.integer;
1087                                users = g_list_delete_link(users, u);
1088                                break;
1089                        }
1090                }
1091        }
1092
1093finish:
1094        json_value_free(parsed);
1095        twitter_filter_stream(ic);
1096
1097        if (!users)
1098                return;
1099
1100        fstr = g_string_new("");
1101
1102        for (u = users; u; u = g_list_next(u)) {
1103                if (fstr->len > 0)
1104                        g_string_append(fstr, ", ");
1105
1106                g_string_append(fstr, tf->text);
1107        }
1108
1109        imcb_error(ic, "Failed UID acquisitions: %s", fstr->str);
1110
1111        g_string_free(fstr, TRUE);
1112        g_list_free(users);
1113}
1114
1115gboolean twitter_open_filter_stream(struct im_connection *ic)
1116{
1117        struct twitter_data *td = ic->proto_data;
1118        char *args[2] = {"screen_name", NULL};
1119        GString *ustr = g_string_new("");
1120        struct twitter_filter *tf;
1121        struct http_request *req;
1122        GSList *l;
1123
1124        for (l = td->filters; l; l = g_slist_next(l)) {
1125                tf = l->data;
1126
1127                if (tf->type != TWITTER_FILTER_TYPE_FOLLOW || tf->uid != 0)
1128                        continue;
1129
1130                if (ustr->len > 0)
1131                        g_string_append_c(ustr, ',');
1132
1133                g_string_append(ustr, tf->text);
1134        }
1135
1136        if (ustr->len == 0) {
1137                g_string_free(ustr, TRUE);
1138                return twitter_filter_stream(ic);
1139        }
1140
1141        args[1] = ustr->str;
1142        req = twitter_http(ic, TWITTER_USERS_LOOKUP_URL,
1143                           twitter_filter_users_post,
1144                           ic, 0, args, 2);
1145
1146        g_string_free(ustr, TRUE);
1147        return req != NULL;
1148}
1149
[dff0e0b]1150static void twitter_get_home_timeline(struct im_connection *ic, gint64 next_cursor);
1151static void twitter_get_mentions(struct im_connection *ic, gint64 next_cursor);
1152
[2322a9f]1153/**
1154 * Get the timeline with optionally mentions
1155 */
[2f9027c]1156gboolean twitter_get_timeline(struct im_connection *ic, gint64 next_cursor)
[2322a9f]1157{
1158        struct twitter_data *td = ic->proto_data;
1159        gboolean include_mentions = set_getbool(&ic->acc->set, "fetch_mentions");
1160
1161        if (td->flags & TWITTER_DOING_TIMELINE) {
[11ec078]1162                if (++td->http_fails >= 5) {
1163                        imcb_error(ic, "Fetch timeout (%d)", td->flags);
1164                        imc_logout(ic, TRUE);
[2f9027c]1165                        return FALSE;
[11ec078]1166                }
[2322a9f]1167        }
1168
1169        td->flags |= TWITTER_DOING_TIMELINE;
1170
1171        twitter_get_home_timeline(ic, next_cursor);
1172
1173        if (include_mentions) {
1174                twitter_get_mentions(ic, next_cursor);
1175        }
[2f9027c]1176       
1177        return TRUE;
[2322a9f]1178}
1179
1180/**
1181 * Call this one after receiving timeline/mentions. Show to user once we have
1182 * both.
1183 */
1184void twitter_flush_timeline(struct im_connection *ic)
1185{
1186        struct twitter_data *td = ic->proto_data;
1187        gboolean include_mentions = set_getbool(&ic->acc->set, "fetch_mentions");
[b5fe39b]1188        int show_old_mentions = set_getint(&ic->acc->set, "show_old_mentions");
[2322a9f]1189        struct twitter_xml_list *home_timeline = td->home_timeline_obj;
1190        struct twitter_xml_list *mentions = td->mentions_obj;
[29f72b7]1191        guint64 last_id = 0;
[2322a9f]1192        GSList *output = NULL;
1193        GSList *l;
1194
[29f72b7]1195        imcb_connected(ic);
1196       
[2322a9f]1197        if (!(td->flags & TWITTER_GOT_TIMELINE)) {
1198                return;
1199        }
1200
1201        if (include_mentions && !(td->flags & TWITTER_GOT_MENTIONS)) {
1202                return;
1203        }
1204
1205        if (home_timeline && home_timeline->list) {
1206                for (l = home_timeline->list; l; l = g_slist_next(l)) {
1207                        output = g_slist_insert_sorted(output, l->data, twitter_compare_elements);
1208                }
1209        }
1210
1211        if (include_mentions && mentions && mentions->list) {
1212                for (l = mentions->list; l; l = g_slist_next(l)) {
[b5fe39b]1213                        if (show_old_mentions < 1 && output && twitter_compare_elements(l->data, output->data) < 0) {
[2322a9f]1214                                continue;
1215                        }
1216
1217                        output = g_slist_insert_sorted(output, l->data, twitter_compare_elements);
1218                }
1219        }
1220
1221        // See if the user wants to see the messages in a groupchat window or as private messages.
[29f72b7]1222        while (output) {
1223                struct twitter_xml_status *txs = output->data;
1224                if (txs->id != last_id)
1225                        twitter_status_show(ic, txs);
1226                last_id = txs->id;
1227                output = g_slist_remove(output, txs);
1228        }
[2322a9f]1229
[199fea6]1230        txl_free(home_timeline);
1231        txl_free(mentions);
[2322a9f]1232
1233        td->flags &= ~(TWITTER_DOING_TIMELINE | TWITTER_GOT_TIMELINE | TWITTER_GOT_MENTIONS);
[199fea6]1234        td->home_timeline_obj = td->mentions_obj = NULL;
[2322a9f]1235}
1236
[ddc2de5]1237static void twitter_http_get_home_timeline(struct http_request *req);
1238static void twitter_http_get_mentions(struct http_request *req);
1239
[2322a9f]1240/**
1241 * Get the timeline.
1242 */
[ddc2de5]1243static void twitter_get_home_timeline(struct im_connection *ic, gint64 next_cursor)
[2322a9f]1244{
1245        struct twitter_data *td = ic->proto_data;
1246
[199fea6]1247        txl_free(td->home_timeline_obj);
[2322a9f]1248        td->home_timeline_obj = NULL;
1249        td->flags &= ~TWITTER_GOT_TIMELINE;
1250
[429a9b1]1251        char *args[6];
[2322a9f]1252        args[0] = "cursor";
[85c3004]1253        args[1] = g_strdup_printf("%" G_GINT64_FORMAT, next_cursor);
[429a9b1]1254        args[2] = "include_entities";
1255        args[3] = "true";
[2322a9f]1256        if (td->timeline_id) {
[429a9b1]1257                args[4] = "since_id";
[7549d00]1258                args[5] = g_strdup_printf("%" G_GUINT64_FORMAT, td->timeline_id);
[2322a9f]1259        }
1260
[90fc864]1261        if (twitter_http(ic, TWITTER_HOME_TIMELINE_URL, twitter_http_get_home_timeline, ic, 0, args,
1262                     td->timeline_id ? 6 : 4) == NULL) {
1263                if (++td->http_fails >= 5)
1264                        imcb_error(ic, "Could not retrieve %s: %s",
1265                                   TWITTER_HOME_TIMELINE_URL, "connection failed");
1266                td->flags |= TWITTER_GOT_TIMELINE;
1267                twitter_flush_timeline(ic);
1268        }
[2322a9f]1269
1270        g_free(args[1]);
1271        if (td->timeline_id) {
[429a9b1]1272                g_free(args[5]);
[2322a9f]1273        }
1274}
1275
1276/**
1277 * Get mentions.
1278 */
[ddc2de5]1279static void twitter_get_mentions(struct im_connection *ic, gint64 next_cursor)
[2322a9f]1280{
1281        struct twitter_data *td = ic->proto_data;
1282
[199fea6]1283        txl_free(td->mentions_obj);
[2322a9f]1284        td->mentions_obj = NULL;
1285        td->flags &= ~TWITTER_GOT_MENTIONS;
1286
[429a9b1]1287        char *args[6];
[2322a9f]1288        args[0] = "cursor";
[85c3004]1289        args[1] = g_strdup_printf("%" G_GINT64_FORMAT, next_cursor);
[429a9b1]1290        args[2] = "include_entities";
1291        args[3] = "true";
[2322a9f]1292        if (td->timeline_id) {
[429a9b1]1293                args[4] = "since_id";
[85c3004]1294                args[5] = g_strdup_printf("%" G_GUINT64_FORMAT, td->timeline_id);
[b5fe39b]1295        } else {
1296                args[4] = "count";
1297                args[5] = g_strdup_printf("%d", set_getint(&ic->acc->set, "show_old_mentions"));
[2322a9f]1298        }
1299
[b5fe39b]1300        if (twitter_http(ic, TWITTER_MENTIONS_URL, twitter_http_get_mentions,
1301                         ic, 0, args, 6) == NULL) {
[90fc864]1302                if (++td->http_fails >= 5)
1303                        imcb_error(ic, "Could not retrieve %s: %s",
1304                                   TWITTER_MENTIONS_URL, "connection failed");
1305                td->flags |= TWITTER_GOT_MENTIONS;
1306                twitter_flush_timeline(ic);
1307        }
[2322a9f]1308
1309        g_free(args[1]);
[2fb1262]1310        g_free(args[5]);
[2322a9f]1311}
1312
[1b221e0]1313/**
1314 * Callback for getting the home timeline.
1315 */
1316static void twitter_http_get_home_timeline(struct http_request *req)
1317{
[62d2cfb]1318        struct im_connection *ic = req->data;
[37aa317]1319        struct twitter_data *td;
[8e3b7ac]1320        json_value *parsed;
[1b221e0]1321        struct twitter_xml_list *txl;
[62d2cfb]1322
1323        // Check if the connection is still active.
[5983eca]1324        if (!g_slist_find(twitter_connections, ic))
[62d2cfb]1325                return;
[5983eca]1326
[37aa317]1327        td = ic->proto_data;
[1b221e0]1328
[2322a9f]1329        txl = g_new0(struct twitter_xml_list, 1);
1330        txl->list = NULL;
1331
1332        // The root <statuses> node should hold the list of statuses <status>
[2a6da96]1333        if (!(parsed = twitter_parse_response(ic, req)))
1334                goto end;
[d0752e8]1335        twitter_xt_get_status_list(ic, parsed, txl);
[2fb1262]1336        json_value_free(parsed);
[2322a9f]1337
1338        td->home_timeline_obj = txl;
1339
1340      end:
[fb351ce]1341        if (!g_slist_find(twitter_connections, ic))
1342                return;
1343
[2322a9f]1344        td->flags |= TWITTER_GOT_TIMELINE;
1345
1346        twitter_flush_timeline(ic);
1347}
1348
1349/**
1350 * Callback for getting mentions.
1351 */
1352static void twitter_http_get_mentions(struct http_request *req)
1353{
1354        struct im_connection *ic = req->data;
1355        struct twitter_data *td;
[8e3b7ac]1356        json_value *parsed;
[2322a9f]1357        struct twitter_xml_list *txl;
1358
1359        // Check if the connection is still active.
1360        if (!g_slist_find(twitter_connections, ic))
[1b221e0]1361                return;
[2322a9f]1362
1363        td = ic->proto_data;
1364
[1b221e0]1365        txl = g_new0(struct twitter_xml_list, 1);
1366        txl->list = NULL;
[62d2cfb]1367
[1b221e0]1368        // The root <statuses> node should hold the list of statuses <status>
[2a6da96]1369        if (!(parsed = twitter_parse_response(ic, req)))
1370                goto end;
[d0752e8]1371        twitter_xt_get_status_list(ic, parsed, txl);
[2fb1262]1372        json_value_free(parsed);
[1b221e0]1373
[2322a9f]1374        td->mentions_obj = txl;
[1b221e0]1375
[2322a9f]1376      end:
[fb351ce]1377        if (!g_slist_find(twitter_connections, ic))
1378                return;
1379
[2322a9f]1380        td->flags |= TWITTER_GOT_MENTIONS;
1381
1382        twitter_flush_timeline(ic);
[1b221e0]1383}
1384
1385/**
[de923d5]1386 * Callback to use after sending a POST request to twitter.
1387 * (Generic, used for a few kinds of queries.)
[1b221e0]1388 */
[7d53efb]1389static void twitter_http_post(struct http_request *req)
[1b221e0]1390{
1391        struct im_connection *ic = req->data;
[7b87539]1392        struct twitter_data *td;
[24132ec]1393        json_value *parsed, *id;
[1b221e0]1394
[62d2cfb]1395        // Check if the connection is still active.
[5983eca]1396        if (!g_slist_find(twitter_connections, ic))
[62d2cfb]1397                return;
1398
[7b87539]1399        td = ic->proto_data;
1400        td->last_status_id = 0;
[5983eca]1401
[2a6da96]1402        if (!(parsed = twitter_parse_response(ic, req)))
[1b221e0]1403                return;
[2a6da96]1404       
[67f6828]1405        if ((id = json_o_get(parsed, "id")) && id->type == json_integer) {
[24132ec]1406                td->last_status_id = id->u.integer;
[67f6828]1407        }
[c751e51]1408       
1409        json_value_free(parsed);
[b235228]1410       
1411        if (req->flags & TWITTER_HTTP_USER_ACK)
1412                twitter_log(ic, "Command processed successfully");
[1b221e0]1413}
1414
1415/**
1416 * Function to POST a new status to twitter.
[5983eca]1417 */
[b890626]1418void twitter_post_status(struct im_connection *ic, char *msg, guint64 in_reply_to)
[1b221e0]1419{
[5983eca]1420        char *args[4] = {
[b890626]1421                "status", msg,
1422                "in_reply_to_status_id",
[85c3004]1423                g_strdup_printf("%" G_GUINT64_FORMAT, in_reply_to)
[b890626]1424        };
1425        twitter_http(ic, TWITTER_STATUS_UPDATE_URL, twitter_http_post, ic, 1,
[5983eca]1426                     args, in_reply_to ? 4 : 2);
[b890626]1427        g_free(args[3]);
[1b221e0]1428}
1429
1430
[62d2cfb]1431/**
1432 * Function to POST a new message to twitter.
1433 */
1434void twitter_direct_messages_new(struct im_connection *ic, char *who, char *msg)
1435{
[5983eca]1436        char *args[4];
[62d2cfb]1437        args[0] = "screen_name";
1438        args[1] = who;
1439        args[2] = "text";
1440        args[3] = msg;
1441        // Use the same callback as for twitter_post_status, since it does basically the same.
[ba3233c]1442        twitter_http(ic, TWITTER_DIRECT_MESSAGES_NEW_URL, twitter_http_post, ic, 1, args, 4);
[62d2cfb]1443}
[7d53efb]1444
1445void twitter_friendships_create_destroy(struct im_connection *ic, char *who, int create)
1446{
[5983eca]1447        char *args[2];
[7d53efb]1448        args[0] = "screen_name";
1449        args[1] = who;
[5983eca]1450        twitter_http(ic, create ? TWITTER_FRIENDSHIPS_CREATE_URL : TWITTER_FRIENDSHIPS_DESTROY_URL,
1451                     twitter_http_post, ic, 1, args, 2);
[a26af5c]1452}
[7b87539]1453
1454void twitter_status_destroy(struct im_connection *ic, guint64 id)
1455{
1456        char *url;
[85c3004]1457        url = g_strdup_printf("%s%" G_GUINT64_FORMAT "%s",
1458                              TWITTER_STATUS_DESTROY_URL, id, ".json");
[b235228]1459        twitter_http_f(ic, url, twitter_http_post, ic, 1, NULL, 0,
1460                       TWITTER_HTTP_USER_ACK);
[7b87539]1461        g_free(url);
1462}
[b890626]1463
1464void twitter_status_retweet(struct im_connection *ic, guint64 id)
1465{
1466        char *url;
[85c3004]1467        url = g_strdup_printf("%s%" G_GUINT64_FORMAT "%s",
1468                              TWITTER_STATUS_RETWEET_URL, id, ".json");
[b235228]1469        twitter_http_f(ic, url, twitter_http_post, ic, 1, NULL, 0,
1470                       TWITTER_HTTP_USER_ACK);
[b890626]1471        g_free(url);
1472}
[d18dee42]1473
1474/**
1475 * Report a user for sending spam.
1476 */
1477void twitter_report_spam(struct im_connection *ic, char *screen_name)
1478{
1479        char *args[2] = {
1480                "screen_name",
1481                NULL,
1482        };
1483        args[1] = screen_name;
[b235228]1484        twitter_http_f(ic, TWITTER_REPORT_SPAM_URL, twitter_http_post,
1485                       ic, 1, args, 2, TWITTER_HTTP_USER_ACK);
[d18dee42]1486}
[b61c74c]1487
1488/**
1489 * Favourite a tweet.
1490 */
1491void twitter_favourite_tweet(struct im_connection *ic, guint64 id)
1492{
[75bda8b]1493        char *args[2] = {
1494                "id",
1495                NULL,
1496        };
[85c3004]1497        args[1] = g_strdup_printf("%" G_GUINT64_FORMAT, id);
[75bda8b]1498        twitter_http_f(ic, TWITTER_FAVORITE_CREATE_URL, twitter_http_post,
1499                       ic, 1, args, 2, TWITTER_HTTP_USER_ACK);
1500        g_free(args[1]);
[b61c74c]1501}
Note: See TracBrowser for help on using the repository browser.