Messages new API adaption
[rainbowstream.git] / rainbowstream / rainbow.py
index 27d7ef1..e231ba0 100644 (file)
@@ -322,6 +322,26 @@ def trend():
                     print_trends(trends)
 
 
+def poll():
+    """
+    Fetch stream based on since_id
+    """
+    t = Twitter(auth=authen())
+
+    num = c['HOME_TWEET_NUM']
+    kwargs = {'count': num}
+
+    if 'since_id' in g:
+        kwargs['since_id'] = g['since_id']
+
+    kwargs = add_tweetmode_parameter(kwargs)
+    result = t.statuses.home_timeline(**kwargs)
+    if result:
+        g['since_id'] = result[0]['id']
+    for tweet in reversed(result):
+        draw(t=tweet)
+    printNicely('')
+
 def home():
     """
     Home
@@ -331,8 +351,7 @@ def home():
     if g['stuff'].isdigit():
         num = int(g['stuff'])
     kwargs = {'count': num}
-    if not c.get('DISABLE_EXTENDED_TWEETS'):
-        kwargs['tweet_mode'] = 'extended'
+    kwargs = add_tweetmode_parameter(kwargs)
     for tweet in reversed(t.statuses.home_timeline(**kwargs)):
         draw(t=tweet)
     printNicely('')
@@ -359,8 +378,7 @@ def mentions():
     if g['stuff'].isdigit():
         num = int(g['stuff'])
     kwargs = {'count': num}
-    if not c.get('DISABLE_EXTENDED_TWEETS'):
-          kwargs['tweet_mode'] = 'extended'
+    kwargs = add_tweetmode_parameter(kwargs)
     for tweet in reversed(t.statuses.mentions_timeline(**kwargs)):
         draw(t=tweet)
     printNicely('')
@@ -405,8 +423,7 @@ def view():
         except:
             num = c['HOME_TWEET_NUM']
         kwargs = {'count': num, 'screen_name': user[1:]}
-        if not c.get('DISABLE_EXTENDED_TWEETS'):
-            kwargs['tweet_mode'] = 'extended'
+        kwargs = add_tweetmode_parameter(kwargs)
         for tweet in reversed(t.statuses.user_timeline(**kwargs)):
             draw(t=tweet)
         printNicely('')
@@ -424,8 +441,7 @@ def view_my_tweets():
     except:
         num = c['HOME_TWEET_NUM']
     kwargs = {'count': num, 'screen_name': g['original_name']}
-    if not c.get('DISABLE_EXTENDED_TWEETS'):
-        kwargs['tweet_mode'] = 'extended'
+    kwargs = add_tweetmode_parameter(kwargs)
     for tweet in reversed(
             t.statuses.user_timeline(**kwargs)):
         draw(t=tweet)
@@ -452,8 +468,7 @@ def search():
         'type': type,
         'count': count,
     }
-    if not c.get('DISABLE_EXTENDED_TWEETS'):
-        kwargs['tweet_mode'] = 'extended'
+    kwargs = add_tweetmode_parameter(kwargs)
     # Perform search
     rel = t.search.tweets(**kwargs)['statuses']
     # Return results
@@ -550,8 +565,7 @@ def quote():
         return
     tid = c['tweet_dict'][id]
     kwargs = {'id': tid}
-    if not c.get('DISABLE_EXTENDED_TWEETS'):
-        kwargs['tweet_mode'] = 'extended'
+    kwargs = add_tweetmode_parameter(kwargs)
     tweet = t.statuses.show(**kwargs)
     # Get formater
     formater = format_quote(tweet)
@@ -587,8 +601,7 @@ def allretweet():
         num = c['RETWEETS_SHOW_NUM']
     # Get result and display
     kwargs = {'id': tid, 'count': num}
-    if not c.get('DISABLE_EXTENDED_TWEETS'):
-        kwargs['tweet_mode'] = 'extended'
+    kwargs = add_tweetmode_parameter(kwargs)
     rt_ary = t.statuses.retweets(**kwargs)
     if not rt_ary:
         printNicely(magenta('This tweet has no retweet.'))
@@ -610,8 +623,7 @@ def conversation():
         return
     tid = c['tweet_dict'][id]
     kwargs = {'id': tid}
-    if not c.get('DISABLE_EXTENDED_TWEETS'):
-        kwargs['tweet_mode'] = 'extended'
+    kwargs = add_tweetmode_parameter(kwargs)
     tweet = t.statuses.show(**kwargs)
     limit = c['CONVERSATION_MAX']
     thread_ref = []
@@ -688,8 +700,7 @@ def favorite():
     t.favorites.create(_id=tid, include_entities=False)
     printNicely(green('Favorited.'))
     kwargs = {'id': tid}
-    if not c.get('DISABLE_EXTENDED_TWEETS'):
-        kwargs['tweet_mode'] = 'extended'
+    kwargs = add_tweetmode_parameter(kwargs)
     draw(t.statuses.show(**kwargs))
     printNicely('')
 
@@ -708,8 +719,7 @@ def unfavorite():
     t.favorites.destroy(_id=tid)
     printNicely(green('Okay it\'s unfavorited.'))
     kwargs = {'id': tid}
-    if not c.get('DISABLE_EXTENDED_TWEETS'):
-        kwargs['tweet_mode'] = 'extended'
+    kwargs = add_tweetmode_parameter(kwargs)
     draw(t.statuses.show(**kwargs))
     printNicely('')
 
@@ -726,8 +736,7 @@ def share():
         printNicely(red('Tweet id is not valid.'))
         return
     kwargs = {'id': tid}
-    if not c.get('DISABLE_EXTENDED_TWEETS'):
-        kwargs['tweet_mode'] = 'extended'
+    kwargs = add_tweetmode_parameter(kwargs)
     tweet = t.statuses.show(**kwargs)
     url = 'https://twitter.com/' + \
         tweet['user']['screen_name'] + '/status/' + str(tid)
@@ -807,45 +816,17 @@ def inbox():
     num = c['MESSAGES_DISPLAY']
     if g['stuff'].isdigit():
         num = g['stuff']
+
+    def inboxFilter(message):
+        return message['sender_screen_name'] == g['original_name']
+    def sentFilter(message):
+        return message['recipient_screen_name'] == g['original_name']
+
     # Get inbox messages
-    cur_page = 1
-    inbox = []
-    while num > 20:
-        inbox = inbox + t.direct_messages(
-            count=20,
-            page=cur_page,
-            include_entities=False,
-            skip_status=False
-        )
-        num -= 20
-        cur_page += 1
-    inbox = inbox + t.direct_messages(
-        count=num,
-        page=cur_page,
-        include_entities=False,
-        skip_status=False
-    )
-    # Get sent messages
-    num = c['MESSAGES_DISPLAY']
-    if g['stuff'].isdigit():
-        num = g['stuff']
-    cur_page = 1
-    sent = []
-    while num > 20:
-        sent = sent + t.direct_messages.sent(
-            count=20,
-            page=cur_page,
-            include_entities=False,
-            skip_status=False
-        )
-        num -= 20
-        cur_page += 1
-    sent = sent + t.direct_messages.sent(
-        count=num,
-        page=cur_page,
-        include_entities=False,
-        skip_status=False
-    )
+    messages = []
+    messages = messages + t.direct_messages.events.list()['events']
+    inbox = filter(inboxFilter, messages)
+    sent = filter(inboxFilter, messages)
 
     d = {}
     uniq_inbox = list(set(
@@ -2167,98 +2148,11 @@ def stream(domain, args, name='Rainbow Stream'):
     query_args = dict()
     if args.track_keywords:
         query_args['track'] = args.track_keywords
-    # Get stream
-    stream = TwitterStream(
-        auth=authen(),
-        domain=domain,
-        **stream_args)
-    try:
-        if domain == c['USER_DOMAIN']:
-            tweet_iter = stream.user(**query_args)
-        elif domain == c['SITE_DOMAIN']:
-            tweet_iter = stream.site(**query_args)
-        else:
-            if args.track_keywords:
-                tweet_iter = stream.statuses.filter(**query_args)
-            else:
-                tweet_iter = stream.statuses.sample()
-        # Block new stream until other one exits
-        StreamLock.acquire()
-        g['stream_stop'] = False
-        last_tweet_time = time.time()
-        for tweet in tweet_iter:
-            if tweet is None:
-                printNicely('-- None --')
-            elif tweet is Timeout:
-                # Because the stream check for each 0.3s
-                # so we shouldn't output anything here
-                if(g['stream_stop']):
-                    StreamLock.release()
-                    break
-            elif tweet is HeartbeatTimeout:
-                printNicely('-- Heartbeat Timeout --')
-                reconn_notice()
-                StreamLock.release()
-                break
-            elif tweet is Hangup:
-                printNicely('-- Hangup --')
-                reconn_notice()
-                StreamLock.release()
-                break
-            elif tweet.get('text'):
-                # Slow down the stream by STREAM_DELAY config key
-                if time.time() - last_tweet_time < c['STREAM_DELAY']:
-                    continue
-                last_tweet_time = time.time()
-                # Check the semaphore pause and lock (stream process only)
-                if g['pause']:
-                    continue
-                while c['lock']:
-                    time.sleep(0.5)
-                # Draw the tweet
-                draw(
-                    t=tweet,
-                    keyword=args.track_keywords,
-                    humanize=False,
-                    fil=args.filter,
-                    ig=args.ignore,
-                )
-                # Current readline buffer
-                current_buffer = readline.get_line_buffer().strip()
-                # There is an unexpected behaviour in MacOSX readline + Python 2:
-                # after completely delete a word after typing it,
-                # somehow readline buffer still contains
-                # the 1st character of that word
-                if current_buffer and g['cmd'] != current_buffer:
-                    sys.stdout.write(
-                        g['decorated_name'](g['PREFIX']) + current_buffer)
-                    sys.stdout.flush()
-                elif not c['HIDE_PROMPT']:
-                    sys.stdout.write(g['decorated_name'](g['PREFIX']))
-                    sys.stdout.flush()
-            elif tweet.get('direct_message'):
-                # Check the semaphore pause and lock (stream process only)
-                if g['pause']:
-                    continue
-                while c['lock']:
-                    time.sleep(0.5)
-                print_message(tweet['direct_message'])
-            elif tweet.get('event'):
-                c['events'].append(tweet)
-                print_event(tweet)
-    except TwitterHTTPError as e:
-        printNicely('')
-        printNicely(
-            magenta('We have connection problem with twitter stream API right now :('))
-        detail_twitter_error(e)
-        sys.stdout.write(g['decorated_name'](g['PREFIX']))
-        sys.stdout.flush()
-    except (URLError):
-        printNicely(
-            magenta('There seems to be a connection problem.'))
-        save_history()
-        sys.exit()
 
+    polling_time = 90
+    while True:
+        time.sleep(polling_time)
+        poll()
 
 def spawn_public_stream(args, keyword=None):
     """