polybar: rewrite + simplify mail module

This commit is contained in:
Henrik Lissner 2017-10-07 17:37:41 +02:00
parent a48b455bf1
commit 149e871001
No known key found for this signature in database
GPG key ID: 5F6C0EA160557395

View file

@ -1,94 +1,93 @@
#!/usr/bin/env python3 #!/usr/bin/env python3
import imaplib import imaplib
import email
import os import os
import sys import sys
import re
import html
import socket import socket
from shlex import quote from pathlib import Path
ICON = "" ICON = ""
CONFIG_FILE = os.path.expanduser("~/.private/config/email") CONFIG_FILE = os.path.expanduser("~/.private/config/email")
CACHE_FILE = "/tmp/polybar-mail" CACHE_FILE = "/tmp/polybar-mail"
COLOR_HL = "B48EAD" COLOR_HL = "3E86B8"
COLOR_NONE = "65737E" COLOR_NONE = "5C6370"
COLOR_ERR = "D08770" COLOR_ERR = "CC626A"
# #
def internet_is_on(): def internet_is_on():
try: try:
host = socket.gethostbyname("www.google.com") host = socket.gethostbyname("www.google.com")
s = socket.create_connection((host, 80), 2) socket.create_connection((host, 80), 2)
return True return True
except: except:
pass pass
return False return False
def recent_messages(address, password):
obj = imaplib.IMAP4_SSL('imap.gmail.com', 993)
obj.login(address, password)
try:
obj.select('Inbox')
ret, resp = obj.search(None, '(UNSEEN)')
if ret == 'OK':
uids = resp[0].split()
if uids:
ret, data = obj.fetch(b",".join(uids), '(BODY.PEEK[])')
if ret == 'OK':
for m in filter(lambda x: len(x) > 1, data):
yield email.message_from_string(m[1].decode('utf-8'))
else:
print("Error: fetch")
else:
print("Error: lookup")
finally:
obj.close()
obj.logout()
def notify(sender, subject): def unread_count(address, password):
if not sender[0].isalnum() and "<" in sender: imap = imaplib.IMAP4_SSL('imap.gmail.com', 993)
sender = sender.split("<")[1].split(">")[0] imap.login(address, password)
os.system("/usr/bin/notify-send {} {}".format(quote("<b>{}</b>".format(html.escape(sender))), quote(html.escape(subject)))) imap.select('INBOX')
status, resp = imap.search(None, 'UNSEEN')
imap.close()
imap.logout()
return len(resp[0].split())
def ding(): def ding():
os.system("/usr/bin/aplay -N -q '{}'".format(os.path.expanduser("~/.config/polybar/sounds/robinhood76-music-box.wav"))) os.system("/usr/bin/aplay -N -q '{}'".format(os.path.expanduser("~/.config/polybar/sounds/robinhood76-music-box.wav")))
# def unread_messages(address, password):
# try:
# imap = imaplib.IMAP4_SSL('imap.gmail.com', 993)
# imap.login(address, password)
# imap.select('INBOX')
# ret, resp = obj.search(None, '(UNSEEN)')
# if ret == 'OK':
# uids = resp[0].split()
# if uids:
# # ret, data = obj.fetch(b",".join(uids), '(BODY.PEEK[])')
# if ret == 'OK':
# for m in filter(lambda x: len(x) > 1, data):
# yield email.message_from_string(m[1].decode('utf-8'))
# else:
# print("Error: fetch")
# else:
# print("Error: lookup")
# finally:
# imap.close()
# imap.logout()
# #
if __name__ == '__main__': def main():
if os.path.isfile(CONFIG_FILE): if os.path.isfile(CONFIG_FILE) and internet_is_on():
if not internet_is_on():
print("%{{F#{}}}{} !".format(COLOR_ERR, ICON))
sys.exit(2)
cache = []
if os.path.isfile(CACHE_FILE):
with open(CACHE_FILE, 'r') as fp:
cache = fp.read().strip().split("\n")
with open(CONFIG_FILE, 'r') as fp: with open(CONFIG_FILE, 'r') as fp:
accounts = [line.strip().split(",") for line in fp if line] accounts = [line.strip().split(",") for line in fp if line]
cache = Path(CACHE_FILE)
cache_text = cache.read_text()
last_total = int(cache.read_text() if cache_text else 0)
total = 0 total = 0
unique = 0
for addr, pwd in accounts: for addr, pwd in accounts:
for msg in recent_messages(addr, pwd): total += unread_count(addr, pwd)
total += 1
if msg['Message-Id'] not in cache: if total != last_total:
notify(msg['From'], msg['Subject']) ding()
cache.append(msg['Message-Id'].strip())
unique += 1
color = COLOR_HL if total > 0 else COLOR_NONE color = COLOR_HL if total > 0 else COLOR_NONE
print("%{{u#{}}}%{{F#{}}}{} {}".format(color, color, ICON, total)) print("%{{u#{}}}%{{F#{}}}{} {}".format(color, color, ICON, total))
if unique > 0:
ding() cache.write_text(str(total))
with open(CACHE_FILE, 'w') as fp:
fp.write("\n".join(cache[-75:]))
else: else:
print("%{{F#{}}}{} -".format(COLOR_ERR, ICON)) print("%{{F#{}}}{} !".format(COLOR_ERR, ICON))
sys.exit(1) sys.exit(1)
#
if __name__ == '__main__':
main()