config

betoissues' dotfiles
git clone git://git.betoissues.com/config.git
Historial | Archivos | Refs | Subm├│dulos | README

launch.py (2095B)


      1 #!/usr/bin/env python
      2 
      3 import time
      4 import argparse
      5 import subprocess
      6 from pathlib import Path
      7 from googleapiclient import discovery, errors
      8 from google.oauth2.credentials import Credentials
      9 from httplib2 import ServerNotFoundError
     10 
     11 parser = argparse.ArgumentParser()
     12 parser.add_argument('-l', '--label', default='INBOX')
     13 parser.add_argument('-p', '--prefix', default='\uf0e0')
     14 parser.add_argument('-c', '--color', default='#e06c75')
     15 parser.add_argument('-ns', '--nosound', action='store_true')
     16 args = parser.parse_args()
     17 
     18 DIR = Path(__file__).resolve().parent
     19 CREDENTIALS_PATH = Path(DIR, 'credentials.json')
     20 
     21 unread_prefix = '%{F' + args.color + '}' + args.prefix + ' %{F-}'
     22 error_prefix = '%{F' + args.color + '}\uf06a %{F-}'
     23 count_was = 0
     24 
     25 def print_count(count, is_odd=False):
     26     tilde = '~' if is_odd else ''
     27     output = ''
     28     if count > 0:
     29         output = unread_prefix + tilde + str(count)
     30     else:
     31         output = (args.prefix + ' ' + tilde).strip()
     32     print(output, flush=True)
     33 
     34 def update_count(count_was):
     35     creds = Credentials.from_authorized_user_file(CREDENTIALS_PATH)
     36     gmail = discovery.build('gmail', 'v1', credentials=creds)
     37     labels = gmail.users().labels().get(userId='me', id=args.label).execute()
     38     count = labels['messagesUnread']
     39     print_count(count)
     40     if not args.nosound and count_was < count and count > 0:
     41         subprocess.run(['canberra-gtk-play', '-i', 'message'])
     42     return count
     43 
     44 print_count(0, True)
     45 
     46 while True:
     47     try:
     48         if Path(CREDENTIALS_PATH).is_file():
     49             count_was = update_count(count_was)
     50             time.sleep(10)
     51         else:
     52             print(error_prefix + 'credentials not found', flush=True)
     53             time.sleep(2)
     54     except errors.HttpError as error:
     55         if error.resp.status == 404:
     56             print(error_prefix + f'"{args.label}" label not found', flush=True)
     57         else:
     58             print_count(count_was, True)
     59         time.sleep(5)
     60     except (ServerNotFoundError, OSError) as e:
     61         print(error_prefix + str(e), flush=True)
     62         print_count(count_was, True)
     63         time.sleep(5)