reset cache
[rainbowstream.git] / rainbowstream / rainbow.py
index 00e01eb9e6079175e5ba9c1ba7b315b3e2ee3109..b7042876ce613fb704b557373acb6e5dd576ed60 100644 (file)
@@ -137,10 +137,11 @@ def get_decorated_name():
     g['decorated_name'] = color_func(c['DECORATED_NAME'])('[' + name + ']: ')
     g['ascii_art'] = True
 
-    files = os.listdir('rainbowstream/colorset')
+    files = os.listdir(os.path.dirname(__file__)+'/colorset')
     themes = [f.split('.')[0] for f in files if f.split('.')[-1] == 'json']
-    themes += ['user']
+    themes += ['custom']
     g['themes'] = themes
+    db.theme_store(c['theme'])
 
 
 def switch():
@@ -750,17 +751,8 @@ def cal():
     # Format
     rel = os.popen('cal').read().split('\n')
     month = rel.pop(0)
-    month = random_rainbow(month)
     date = rel.pop(0)
-    date = ' '.join([cycle_color(i) for i in date.split(' ')])
-    today = str(int(os.popen('date +\'%d\'').read().strip()))
-    # Display
-    printNicely(month)
-    printNicely(date)
-    for line in rel:
-        ary = line.split(' ')
-        ary = map(lambda x: on_grey(x) if x == today else grey(x), ary)
-        printNicely(' '.join(ary))
+    show_calendar(month, date, rel)
 
 
 def theme():
@@ -769,36 +761,54 @@ def theme():
     """
     if not g['stuff']:
         # List themes
-        line = ' ' * 2 + light_yellow('* ')
         for theme in g['themes']:
+            line = ''
             # Detect custom config
-            if theme == 'user':
+            if theme == 'custom':
                 line += light_magenta('custom')
-                exists = db.theme_query()
-                themes = [t.theme_name for t in exists]
-                if themes[0] == 'user':
-                    line += light_magenta(' (applied)')
+                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(' (not specified)')
+                    line += light_magenta(' (loaded)')
             else:
                 line += light_magenta(theme)
+            if c['theme'] == theme :
+                line = ' '*2 + light_yellow('* ') + line
+            else:
+                line = ' '*4 + line
             printNicely(line)
     else:
         # Change theme
         try:
             # Load new config
-            new_config = 'rainbowstream/colorset/' + g['stuff'] + '.json'
+            if g['stuff'] != 'custom':
+                new_config = os.path.dirname(__file__) + '/colorset/' + g['stuff'] + '.json'
+            else:
+                new_config = os.environ.get(
+                    'HOME',os.environ.get(
+                        'USERPROFILE',
+                        '')) + os.sep + '.rainbow_config.json'
             new_config = load_config(new_config)
-            for nc in new_config:
-                c[nc] = new_config[nc]
-            # Update db
-            theme_update(g['stuff'])
+            if new_config:
+                for nc in new_config:
+                    c[nc] = new_config[nc]
+            # Update db and reset colors
+            db.theme_update(g['stuff'])
+            c['theme'] = g['stuff']
+            reset_cycle()
             g['decorated_name'] = color_func(
                 c['DECORATED_NAME'])(
                 '[@' + g['original_name'] + ']: ')
             printNicely(green('Theme changed.'))
         except:
-            printNicely(red('Sorry, config file is broken!'))
+            if g['stuff'] == 'custom':
+                printNicely(red('~/.rainbow_config.json is not exists!'))
+            else:
+                printNicely(red('No such theme exists.'))
 
 
 def help():
@@ -965,8 +975,8 @@ def reset():
         printNicely(magenta('Need tips ? Type "h" and hit Enter key!'))
     g['reset'] = False
     try:
-        printNicely(eval(g['cmd']))
-    except:
+        printNicely(str(eval(g['cmd'])))
+    except Exception:
         pass
 
 
@@ -1073,8 +1083,7 @@ def listen():
         try:
             g['stuff'] = ' '.join(line.split()[1:])
             process(cmd)()
-        except Exception as e:
-            print e
+        except Exception:
             printNicely(red('OMG something is wrong with Twitter right now.'))
         # Not redisplay prefix
         if cmd in ['switch', 't', 'rt', 'rep']:
@@ -1114,18 +1123,18 @@ def stream(domain, args, name='Rainbow Stream'):
         domain=domain,
         **stream_args)
 
-    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)
+    try:
+        if domain == c['USER_DOMAIN']:
+            tweet_iter = stream.user(**query_args)
+        elif domain == c['SITE_DOMAIN']:
+            tweet_iter = stream.site(**query_args)
         else:
-            tweet_iter = stream.statuses.sample()
+            if args.track_keywords:
+                tweet_iter = stream.statuses.filter(**query_args)
+            else:
+                tweet_iter = stream.statuses.sample()
 
-    # Iterate over the stream.
-    try:
+        # Iterate over the stream.
         for tweet in tweet_iter:
             if tweet is None:
                 printNicely("-- None --")
@@ -1143,10 +1152,10 @@ def stream(domain, args, name='Rainbow Stream'):
                     fil=args.filter,
                     ig=args.ignore,
                 )
-    except:
+    except TwitterHTTPError:
+        printNicely('')
         printNicely(
-            magenta("I'm afraid we have problem with twitter'S maximum connection."))
-        printNicely(magenta("Let's try again later."))
+            magenta("We have maximum connection problem with twitter'stream API right now :("))
 
 
 def fly():
@@ -1155,11 +1164,22 @@ def fly():
     """
     # Spawn stream process
     args = parse_arguments()
-    get_decorated_name()
+    try:
+        get_decorated_name()
+
+    except TwitterHTTPError:
+        printNicely('')
+        printNicely(
+            magenta("I'm afraid we have maximum connection problem with twitter right now :("))
+        printNicely(magenta("Let's try again later."))
+        save_history()
+        os.system('rm -rf rainbow.db')
+        sys.exit()
+
     p = Process(
         target=stream,
         args=(
-            c['USER_DOMAIN'],
+        c['USER_DOMAIN'],
             args,
             g['original_name']))
     p.start()