check config and little refactoring
[rainbowstream.git] / rainbowstream / rainbow.py
index 3c401621c4f0ad1c60ad559971f207507d0698a3..94440877f32f09b14add6703ad3dad1a3344159b 100644 (file)
@@ -11,6 +11,7 @@ import argparse
 import time
 import requests
 import webbrowser
 import time
 import requests
 import webbrowser
+import json
 
 from twitter.stream import TwitterStream, Timeout, HeartbeatTimeout, Hangup
 from twitter.api import *
 
 from twitter.stream import TwitterStream, Timeout, HeartbeatTimeout, Hangup
 from twitter.api import *
@@ -140,13 +141,11 @@ def get_decorated_name():
     name = '@' + t.account.verify_credentials()['screen_name']
     g['original_name'] = name[1:]
     g['decorated_name'] = color_func(c['DECORATED_NAME'])('[' + name + ']: ')
     name = '@' + t.account.verify_credentials()['screen_name']
     g['original_name'] = name[1:]
     g['decorated_name'] = color_func(c['DECORATED_NAME'])('[' + name + ']: ')
-    g['ascii_art'] = True
 
     files = os.listdir(os.path.dirname(__file__) + '/colorset')
     themes = [f.split('.')[0] for f in files if f.split('.')[-1] == 'json']
 
     files = os.listdir(os.path.dirname(__file__) + '/colorset')
     themes = [f.split('.')[0] for f in files if f.split('.')[-1] == 'json']
-    themes += ['custom']
     g['themes'] = themes
     g['themes'] = themes
-    db.theme_store(c['theme'])
+    db.theme_store(c['THEME'])
 
 
 def switch():
 
 
 def switch():
@@ -207,7 +206,6 @@ def switch():
         if args.ignore:
             printNicely(red('Ignore: ' + str(args.ignore)))
         printNicely('')
         if args.ignore:
             printNicely(red('Ignore: ' + str(args.ignore)))
         printNicely('')
-        g['ascii_art'] = True
     except:
         printNicely(red('Sorry I can\'t understand.'))
 
     except:
         printNicely(red('Sorry I can\'t understand.'))
 
@@ -490,7 +488,7 @@ def show():
         media = tweet['entities']['media']
         for m in media:
             res = requests.get(m['media_url'])
         media = tweet['entities']['media']
         for m in media:
             res = requests.get(m['media_url'])
-            img = Image.open(StringIO(res.content))
+            img = Image.open(BytesIO(res.content))
             img.show()
     except:
         printNicely(red('Sorry I can\'t show this image.'))
             img.show()
     except:
         printNicely(red('Sorry I can\'t show this image.'))
@@ -799,6 +797,23 @@ def report():
         printNicely(red('Sorry I can\'t understand.'))
 
 
         printNicely(red('Sorry I can\'t understand.'))
 
 
+def get_slug():
+    """
+    Get Slug Decorator
+    """
+     # Get list name
+    list_name = raw_input(light_magenta('Give me the list\'s name: '))
+    # Get list name and owner
+    try:
+        owner, slug = list_name.split('/')
+        if slug.startswith('@'):
+            slug = slug[1:]
+        return owner, slug
+    except:
+        printNicely(light_magenta('List name should follow "@owner/list_name" format.'))
+        raise Exception('Wrong list name')
+
+
 def show_lists(t):
     """
     List list
 def show_lists(t):
     """
     List list
@@ -814,16 +829,7 @@ def list_home(t):
     """
     List home
     """
     """
     List home
     """
-    # Get list name
-    list_name = raw_input(light_magenta('Give me the list\'s name: '))
-    # Get list name and owner
-    try:
-        owner, slug = list_name.split('/')
-        if slug.startswith('@'):
-            slug = slug[1:]
-    except:
-        printNicely(light_magenta('Please follow "@owner/list_name" format.'))
-        return
+    owner, slug = get_slug()
     res = t.lists.statuses(
         slug=slug,
         owner_screen_name=owner,
     res = t.lists.statuses(
         slug=slug,
         owner_screen_name=owner,
@@ -838,16 +844,7 @@ def list_members(t):
     """
     List members
     """
     """
     List members
     """
-    # Get list name
-    list_name = raw_input(light_magenta('Give me the list\'s name: '))
-    # Get list name and owner
-    try:
-        owner, slug = list_name.split('/')
-        if slug.startswith('@'):
-            slug = slug[1:]
-    except:
-        printNicely(light_magenta('Please follow "@owner/list_name" format.'))
-        return
+    owner, slug = get_slug()
     # Get members
     rel = {}
     next_cursor = -1
     # Get members
     rel = {}
     next_cursor = -1
@@ -871,16 +868,7 @@ def list_subscribers(t):
     """
     List subscribers
     """
     """
     List subscribers
     """
-    # Get list name
-    list_name = raw_input(light_magenta('Give me the list\'s name: '))
-    # Get list name and owner
-    try:
-        owner, slug = list_name.split('/')
-        if slug.startswith('@'):
-            slug = slug[1:]
-    except:
-        printNicely(light_magenta('Please follow "@owner/list_name" format.'))
-        return
+    owner, slug = get_slug()
     # Get subscribers
     rel = {}
     next_cursor = -1
     # Get subscribers
     rel = {}
     next_cursor = -1
@@ -904,16 +892,7 @@ def list_add(t):
     """
     Add specific user to a list
     """
     """
     Add specific user to a list
     """
-    # Get list name
-    list_name = raw_input(light_magenta('Give me the list\'s name: '))
-    # Get list name and owner
-    try:
-        owner, slug = list_name.split('/')
-        if slug.startswith('@'):
-            slug = slug[1:]
-    except:
-        printNicely(light_magenta('Please follow "@owner/list_name" format.'))
-        return
+    owner, slug = get_slug()
     # Add
     user_name = raw_input(light_magenta('Give me name of the newbie: '))
     if user_name.startswith('@'):
     # Add
     user_name = raw_input(light_magenta('Give me name of the newbie: '))
     if user_name.startswith('@'):
@@ -932,16 +911,7 @@ def list_remove(t):
     """
     Remove specific user from a list
     """
     """
     Remove specific user from a list
     """
-    # Get list name
-    list_name = raw_input(light_magenta('Give me the list\'s name: '))
-    # Get list name and owner
-    try:
-        owner, slug = list_name.split('/')
-        if slug.startswith('@'):
-            slug = slug[1:]
-    except:
-        printNicely(light_magenta('Please follow "@owner/list_name" format.'))
-        return
+    owner, slug = get_slug()
     # Remove
     user_name = raw_input(light_magenta('Give me name of the unlucky one: '))
     if user_name.startswith('@'):
     # Remove
     user_name = raw_input(light_magenta('Give me name of the unlucky one: '))
     if user_name.startswith('@'):
@@ -960,16 +930,7 @@ def list_subscribe(t):
     """
     Subscribe to a list
     """
     """
     Subscribe to a list
     """
-    # Get list name
-    list_name = raw_input(light_magenta('Give me the list\'s name: '))
-    # Get list name and owner
-    try:
-        owner, slug = list_name.split('/')
-        if slug.startswith('@'):
-            slug = slug[1:]
-    except:
-        printNicely(light_magenta('Please follow "@owner/list_name" format.'))
-        return
+    owner, slug = get_slug()
     # Subscribe
     try:
         t.lists.subscribers.create(
     # Subscribe
     try:
         t.lists.subscribers.create(
@@ -985,16 +946,7 @@ def list_unsubscribe(t):
     """
     Unsubscribe a list
     """
     """
     Unsubscribe a list
     """
-    # Get list name
-    list_name = raw_input(light_magenta('Give me the list\'s name: '))
-    # Get list name and owner
-    try:
-        owner, slug = list_name.split('/')
-        if slug.startswith('@'):
-            slug = slug[1:]
-    except:
-        printNicely(light_magenta('Please follow "@owner/list_name" format.'))
-        return
+    owner, slug = get_slug()
     # Subscribe
     try:
         t.lists.subscribers.destroy(
     # Subscribe
     try:
         t.lists.subscribers.destroy(
@@ -1064,8 +1016,7 @@ def list_update(t):
                 mode=mode,
                 description=description)
         printNicely(light_green(slug + ' list is updated.'))
                 mode=mode,
                 description=description)
         printNicely(light_green(slug + ' list is updated.'))
-    except Exception as e:
-        print e
+    except:
         printNicely(red('Oops something is wrong with Twitter :('))
 
 
         printNicely(red('Oops something is wrong with Twitter :('))
 
 
@@ -1110,9 +1061,8 @@ def list():
     }
     try:
         return action_ary[g['list_action']](t)
     }
     try:
         return action_ary[g['list_action']](t)
-    except Exception as e:
-        print e
-        printNicely(red('Sorry I can\'t understand.'))
+    except:
+        printNicely(red('Please try again.'))
 
 
 def cal():
 
 
 def cal():
@@ -1133,32 +1083,31 @@ def theme():
     if not g['stuff']:
         # List themes
         for theme in g['themes']:
     if not g['stuff']:
         # List themes
         for theme in g['themes']:
-            line = ''
-            # Detect custom config
-            if theme == 'custom':
-                line += light_magenta('custom')
-                custom_path = os.environ.get(
-                    'HOME',
-                    os.environ.get('USERPROFILE',
-                                   '')) + os.sep + '.rainbow_config.json'
-                if not os.path.exists(custom_path):
-                    line += light_magenta(
-                        ' (create your own config file at ~/.rainbow_config.json)')
-                else:
-                    line += light_magenta(' (loaded)')
-            else:
-                line += light_magenta(theme)
-            if c['theme'] == theme:
+            line = light_magenta(theme)
+            if c['THEME'] == theme:
                 line = ' ' * 2 + light_yellow('* ') + line
             else:
                 line = ' ' * 4 + line
             printNicely(line)
     elif g['stuff'] == 'current_as_default':
                 line = ' ' * 2 + light_yellow('* ') + line
             else:
                 line = ' ' * 4 + line
             printNicely(line)
     elif g['stuff'] == 'current_as_default':
-        # Set default
-        path = os.path.dirname(__file__) + '/colorset/init'
-        f = open(path, 'w')
-        f.write(c['theme'])
-        f.close()
+        # Set as default
+        def fixup(adict, k, v):
+            for key in adict.keys():
+                if key == k:
+                    adict[key] = v
+                elif type(adict[key]) is dict:
+                    fixup(adict[key], k, v)
+        # Modify
+        path = os.environ.get(
+            'HOME',
+            os.environ.get(
+                'USERPROFILE',
+                '')) + os.sep + '.rainbow_config.json'
+        data = load_config(rainbow_config)
+        fixup(data, 'THEME', c['THEME'])
+        # Save
+        with open(path, 'w') as out:
+            json.dump(data, out, indent = 4)
         os.system('chmod 777 ' + path)
         printNicely(light_green('Okay it will be applied from next time :)'))
     else:
         os.system('chmod 777 ' + path)
         printNicely(light_green('Okay it will be applied from next time :)'))
     else:
@@ -1179,17 +1128,14 @@ def theme():
                     c[nc] = new_config[nc]
             # Update db and reset colors
             db.theme_update(g['stuff'])
                     c[nc] = new_config[nc]
             # Update db and reset colors
             db.theme_update(g['stuff'])
-            c['theme'] = g['stuff']
+            c['THEME'] = g['stuff']
             reset_cycle()
             g['decorated_name'] = color_func(
                 c['DECORATED_NAME'])(
                 '[@' + g['original_name'] + ']: ')
             printNicely(green('Theme changed.'))
         except:
             reset_cycle()
             g['decorated_name'] = color_func(
                 c['DECORATED_NAME'])(
                 '[@' + g['original_name'] + ']: ')
             printNicely(green('Theme changed.'))
         except:
-            if g['stuff'] == 'custom':
-                printNicely(red('~/.rainbow_config.json is not exists!'))
-            else:
-                printNicely(red('No such theme exists.'))
+            printNicely(red('No such theme exists.'))
 
 
 def help_discover():
 
 
 def help_discover():
@@ -1317,7 +1263,7 @@ def help_list():
     usage += s * 2 + light_green('list') + \
         ' will show all lists you are belong to.\n'
     usage += s * 2 + light_green('list home') + \
     usage += s * 2 + light_green('list') + \
         ' will show all lists you are belong to.\n'
     usage += s * 2 + light_green('list home') + \
-        ' will show timeline of list. You will be asked for list\'s name\n'
+        ' will show timeline of list. You will be asked for list\'s name.\n'
     usage += s * 2 + light_green('list all_mem') + \
         ' will show list\'s all members.\n'
     usage += s * 2 + light_green('list all_sub') + \
     usage += s * 2 + light_green('list all_mem') + \
         ' will show list\'s all members.\n'
     usage += s * 2 + light_green('list all_sub') + \
@@ -1614,9 +1560,9 @@ def stream(domain, args, name='Rainbow Stream'):
     art_dict = {
         c['USER_DOMAIN']: name,
         c['PUBLIC_DOMAIN']: args.track_keywords,
     art_dict = {
         c['USER_DOMAIN']: name,
         c['PUBLIC_DOMAIN']: args.track_keywords,
-        c['SITE_DOMAIN']: 'Site Stream',
+        c['SITE_DOMAIN']: name,
     }
     }
-    if g['ascii_art']:
+    if c['ASCII_ART']:
         ascii_art(art_dict[domain])
 
     # These arguments are optional:
         ascii_art(art_dict[domain])
 
     # These arguments are optional:
@@ -1683,8 +1629,9 @@ def fly():
     except TwitterHTTPError:
         printNicely('')
         printNicely(
     except TwitterHTTPError:
         printNicely('')
         printNicely(
-            magenta("I'm afraid we have maximum connection problem with twitter right now :("))
-        printNicely(magenta("Let's try again later."))
+            magenta("Something wrong with Twitter Oauth right now :("))
+        printNicely(
+            magenta("Please delete ~/.rainbow_oauth and try again."))
         save_history()
         os.system('rm -rf rainbow.db')
         sys.exit()
         save_history()
         os.system('rm -rf rainbow.db')
         sys.exit()