Add `DISABLE_EXTENDED_TWEETS` config option to disable extended tweets support
[rainbowstream.git] / rainbowstream / rainbow.py
index 8e9e22b6dfa4ec504f2d0a12ce1a2a12a578bf24..27d7ef1eb24c8b3e868846c8300ad7272969023e 100644 (file)
@@ -221,12 +221,12 @@ def upgrade_center():
             notice += light_yellow(current) + '\n'
             notice += light_magenta('You should upgrade with ')
             notice += light_green('pip install -U rainbowstream')
-            printNicely(notice)
         else:
             notice = light_yellow('You are running latest version (')
             notice += light_green(current)
             notice += light_yellow(')')
             notice += '\n'
+        printNicely(notice)
     except:
         pass
 
@@ -271,7 +271,6 @@ def init(args):
     c['message_dict'] = []
     # Image on term
     c['IMAGE_ON_TERM'] = args.image_on_term
-    set_config('IMAGE_ON_TERM', str(c['IMAGE_ON_TERM']))
     # Use 24 bit color
     c['24BIT'] = args.color_24bit
     # Check type of ONLY_LIST and IGNORE_LIST
@@ -331,7 +330,10 @@ def home():
     num = c['HOME_TWEET_NUM']
     if g['stuff'].isdigit():
         num = int(g['stuff'])
-    for tweet in reversed(t.statuses.home_timeline(count=num)):
+    kwargs = {'count': num}
+    if not c.get('DISABLE_EXTENDED_TWEETS'):
+        kwargs['tweet_mode'] = 'extended'
+    for tweet in reversed(t.statuses.home_timeline(**kwargs)):
         draw(t=tweet)
     printNicely('')
 
@@ -356,7 +358,10 @@ def mentions():
     num = c['HOME_TWEET_NUM']
     if g['stuff'].isdigit():
         num = int(g['stuff'])
-    for tweet in reversed(t.statuses.mentions_timeline(count=num)):
+    kwargs = {'count': num}
+    if not c.get('DISABLE_EXTENDED_TWEETS'):
+          kwargs['tweet_mode'] = 'extended'
+    for tweet in reversed(t.statuses.mentions_timeline(**kwargs)):
         draw(t=tweet)
     printNicely('')
 
@@ -399,14 +404,34 @@ def view():
             num = int(g['stuff'].split()[1])
         except:
             num = c['HOME_TWEET_NUM']
-        for tweet in reversed(
-                t.statuses.user_timeline(count=num, screen_name=user[1:])):
+        kwargs = {'count': num, 'screen_name': user[1:]}
+        if not c.get('DISABLE_EXTENDED_TWEETS'):
+            kwargs['tweet_mode'] = 'extended'
+        for tweet in reversed(t.statuses.user_timeline(**kwargs)):
             draw(t=tweet)
         printNicely('')
     else:
         printNicely(red('A name should begin with a \'@\''))
 
 
+def view_my_tweets():
+    """
+    Display user's recent tweets.
+    """
+    t = Twitter(auth=authen())
+    try:
+        num = int(g['stuff'])
+    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'
+    for tweet in reversed(
+            t.statuses.user_timeline(**kwargs)):
+        draw(t=tweet)
+    printNicely('')
+
+
 def search():
     """
     Search
@@ -422,12 +447,15 @@ def search():
         type = 'mixed'
     max_record = c['SEARCH_MAX_RECORD']
     count = min(max_record, 100)
+    kwargs = {
+        'q': query,
+        'type': type,
+        'count': count,
+    }
+    if not c.get('DISABLE_EXTENDED_TWEETS'):
+        kwargs['tweet_mode'] = 'extended'
     # Perform search
-    rel = t.search.tweets(
-        q=query,
-        type=type,
-        count=count
-    )['statuses']
+    rel = t.search.tweets(**kwargs)['statuses']
     # Return results
     if rel:
         printNicely('Newest tweets:')
@@ -451,7 +479,8 @@ def pocket():
     Add new link to Pocket along with tweet id
     """
     if not c['POCKET_SUPPORT']:
-        printNicely(red('Pocket isn\'t enabled.'))
+        printNicely(yellow('Pocket isn\'t enabled.'))
+        printNicely(yellow('You need to "config POCKET_SUPPORT = true"'))
         return
 
     # Get tweet infos
@@ -520,7 +549,10 @@ def quote():
         printNicely(red('Sorry I can\'t understand.'))
         return
     tid = c['tweet_dict'][id]
-    tweet = t.statuses.show(id=tid)
+    kwargs = {'id': tid}
+    if not c.get('DISABLE_EXTENDED_TWEETS'):
+        kwargs['tweet_mode'] = 'extended'
+    tweet = t.statuses.show(**kwargs)
     # Get formater
     formater = format_quote(tweet)
     if not formater:
@@ -554,7 +586,10 @@ def allretweet():
     except:
         num = c['RETWEETS_SHOW_NUM']
     # Get result and display
-    rt_ary = t.statuses.retweets(id=tid, count=num)
+    kwargs = {'id': tid, 'count': num}
+    if not c.get('DISABLE_EXTENDED_TWEETS'):
+        kwargs['tweet_mode'] = 'extended'
+    rt_ary = t.statuses.retweets(**kwargs)
     if not rt_ary:
         printNicely(magenta('This tweet has no retweet.'))
         return
@@ -574,14 +609,18 @@ def conversation():
         printNicely(red('Sorry I can\'t understand.'))
         return
     tid = c['tweet_dict'][id]
-    tweet = t.statuses.show(id=tid)
+    kwargs = {'id': tid}
+    if not c.get('DISABLE_EXTENDED_TWEETS'):
+        kwargs['tweet_mode'] = 'extended'
+    tweet = t.statuses.show(**kwargs)
     limit = c['CONVERSATION_MAX']
     thread_ref = []
     thread_ref.append(tweet)
     prev_tid = tweet['in_reply_to_status_id']
     while prev_tid and limit:
         limit -= 1
-        tweet = t.statuses.show(id=prev_tid)
+        kwargs['id'] = prev_tid
+        tweet = t.statuses.show(**kwargs)
         prev_tid = tweet['in_reply_to_status_id']
         thread_ref.append(tweet)
 
@@ -603,7 +642,12 @@ def reply():
     tid = c['tweet_dict'][id]
     user = t.statuses.show(id=tid)['user']['screen_name']
     status = ' '.join(g['stuff'].split()[1:])
-    status = '@' + user + ' ' + str2u(status)
+    # don't include own username for tweet chains
+    # for details see issue https://github.com/DTVD/rainbowstream/issues/163
+    if user == g['original_name']:
+        status = str2u(status)
+    else:
+        status = '@' + user + ' ' + str2u(status)
     t.statuses.update(status=status, in_reply_to_status_id=tid)
 
 
@@ -643,7 +687,10 @@ def favorite():
     tid = c['tweet_dict'][id]
     t.favorites.create(_id=tid, include_entities=False)
     printNicely(green('Favorited.'))
-    draw(t.statuses.show(id=tid))
+    kwargs = {'id': tid}
+    if not c.get('DISABLE_EXTENDED_TWEETS'):
+        kwargs['tweet_mode'] = 'extended'
+    draw(t.statuses.show(**kwargs))
     printNicely('')
 
 
@@ -660,7 +707,10 @@ def unfavorite():
     tid = c['tweet_dict'][id]
     t.favorites.destroy(_id=tid)
     printNicely(green('Okay it\'s unfavorited.'))
-    draw(t.statuses.show(id=tid))
+    kwargs = {'id': tid}
+    if not c.get('DISABLE_EXTENDED_TWEETS'):
+        kwargs['tweet_mode'] = 'extended'
+    draw(t.statuses.show(**kwargs))
     printNicely('')
 
 
@@ -675,7 +725,10 @@ def share():
     except:
         printNicely(red('Tweet id is not valid.'))
         return
-    tweet = t.statuses.show(id=tid)
+    kwargs = {'id': tid}
+    if not c.get('DISABLE_EXTENDED_TWEETS'):
+        kwargs['tweet_mode'] = 'extended'
+    tweet = t.statuses.show(**kwargs)
     url = 'https://twitter.com/' + \
         tweet['user']['screen_name'] + '/status/' + str(tid)
     import platform
@@ -888,24 +941,41 @@ def ls():
     d = {'fl': 'followers', 'fr': 'friends'}
     next_cursor = -1
     rel = {}
+
+    printNicely('All ' + d[target] + ':')
+
     # Cursor loop
+    number_of_users = 0
     while next_cursor != 0:
+
         list = getattr(t, d[target]).list(
             screen_name=name,
             cursor=next_cursor,
             skip_status=True,
             include_entities=False,
         )
+
         for u in list['users']:
-            rel[u['name']] = '@' + u['screen_name']
+
+            number_of_users += 1
+
+            # Print out result
+            printNicely(   '  '                                               \
+                         + cycle_color( u['name'] )                           \
+                         + color_func(c['TWEET']['nick'])(    ' @'            \
+                                                           + u['screen_name'] \
+                                                           + ' ' ) )
+
         next_cursor = list['next_cursor']
-    # Print out result
-    printNicely('All: ' + str(len(rel)) + ' ' + d[target] + '.')
-    for name in rel:
-        user = '  ' + cycle_color(name)
-        user += color_func(c['TWEET']['nick'])(' ' + rel[name] + ' ')
-        printNicely(user)
 
+        # 300 users means 15 calls to the related API. The rate limit is 15
+        # calls per 15mn periods (see Twitter documentation).
+        if ( number_of_users % 300 == 0 ):
+            printNicely(light_yellow( 'We reached the limit of Twitter API.' ))
+            printNicely(light_yellow( 'You may need to wait about 15 minutes.' ))
+            break
+
+    printNicely('All: ' + str(number_of_users) + ' ' + d[target] + '.')
 
 def follow():
     """
@@ -950,7 +1020,7 @@ def mute():
             rel = t.mutes.users.create(screen_name=screen_name[1:])
             if isinstance(rel, dict):
                 printNicely(green(screen_name + ' is muted.'))
-                c['IGNORE_LIST'] += [unc(screen_name)]
+                c['IGNORE_LIST'] += [screen_name]
                 c['IGNORE_LIST'] = list(set(c['IGNORE_LIST']))
             else:
                 printNicely(red(rel))
@@ -1374,8 +1444,8 @@ def switch():
                 printNicely(light_magenta(guide))
                 only = raw_input('Only nicks [Ex: @xxx,@yy]: ')
                 ignore = raw_input('Ignore nicks [Ex: @xxx,@yy]: ')
-                args.filter = filter(None, only.split(','))
-                args.ignore = filter(None, ignore.split(','))
+                args.filter = list(filter(None, only.split(',')))
+                args.ignore = list(filter(None, ignore.split(',')))
         except:
             printNicely(red('Sorry, wrong format.'))
             return
@@ -1520,6 +1590,8 @@ def help_discover():
         light_green('trend JP Tokyo') + '.\n'
     usage += s * 2 + light_green('home') + ' will show your timeline. ' + \
         light_green('home 7') + ' will show 7 tweets.\n'
+    usage += s * 2 + light_green('me') + ' will show your latest tweets. ' + \
+        light_green('me 2') + ' will show your last 2 tweets.\n'
     usage += s * 2 + \
         light_green('notification') + ' will show your recent notification.\n'
     usage += s * 2 + light_green('mentions') + ' will show mentions timeline. ' + \
@@ -1846,6 +1918,7 @@ cmdset = [
     't',
     'rt',
     'quote',
+    'me',
     'allrt',
     'conversation',
     'fav',
@@ -1895,6 +1968,7 @@ funcset = [
     tweet,
     retweet,
     quote,
+    view_my_tweets,
     allretweet,
     conversation,
     favorite,
@@ -1957,6 +2031,7 @@ def listen():
             [],  # tweet
             [],  # retweet
             [],  # quote
+            [],  # view_my_tweets
             [],  # allretweet
             [],  # conversation
             [],  # favorite
@@ -2044,8 +2119,6 @@ def listen():
                 g['prefix'] = False
             else:
                 g['prefix'] = True
-            # Release the semaphore lock
-            c['lock'] = False
         except EOFError:
             printNicely('')
         except TwitterHTTPError as e:
@@ -2053,6 +2126,9 @@ def listen():
         except Exception:
             debug_option()
             printNicely(red('OMG something is wrong with Twitter API right now.'))
+        finally:
+            # Release the semaphore lock
+            c['lock'] = False
 
 
 def reconn_notice():