source: protocols/twitter/twitter_lib.c @ 3fbce97

Last change on this file since 3fbce97 was 3fbce97, checked in by Wilmer van der Gaast <wilmer@…>, at 2016-09-24T20:14:34Z

Merge branch 'master' into parson

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