helm/themes/pianocat/polybar/modules/mail

93 lines
2.2 KiB
Plaintext
Raw Normal View History

2019-08-06 11:29:33 -07:00
#!/usr/bin/env python3
import imaplib
import os
import sys
import socket
from subprocess import Popen
CONFIG_FILE = os.path.expanduser("~/.secrets/email")
CACHE_FILE = "/tmp/polybar-mail"
ICON = ""
try:
import gnupg
from pathlib import Path
except ImportError:
print("%{{F{}}}*".format("#555856", ICON))
sys.exit(1)
#
def internet_is_on():
try:
host = socket.gethostbyname("www.google.com")
socket.create_connection((host, 80), 2)
return True
except:
pass
return False
def unread_count(address, password):
imap = imaplib.IMAP4_SSL('imap.gmail.com', 993)
imap.login(address, password)
imap.select('INBOX')
status, resp = imap.search(None, 'UNSEEN')
imap.close()
imap.logout()
return len(resp[0].split())
def ding():
Popen(["{}/bin/ding".format(os.getenv("DOTFILES", os.expanduser("~/.dotfiles")))])
#
def main():
try:
if not internet_is_on():
raise IOError("Internet is off")
secrets = Path(CONFIG_FILE)
if not secrets.exists():
raise IOError("Can't find secrets")
gpg = gnupg.GPG()
gpgdata = gpg.decrypt(secrets.read_bytes())
if not gpgdata.ok:
raise IOError("Couldn't decrypt secrets: {}".format(gpgdata.status))
accounts = [line.split(':') for line in gpgdata.data.decode('utf-8').strip().split('\n')]
last_total = 0
cache = Path(CACHE_FILE)
if cache.exists():
cache_text = cache.read_text()
last_total = int(cache.read_text())
total = 0
for addr, pwd in accounts:
total += unread_count(addr, pwd)
if total != last_total:
ding()
if total != 0:
print("%{{F{}}}{}{}".format("#f0c674", ICON, total))
else:
print("%{{F{}}}{}".format("#555856", ICON))
cache.write_text(str(total))
except IOError as e:
print("ERROR: {}".format(e), file=sys.stderr)
print("%{{F{}}}{}!".format("#cc6666", ICON))
sys.exit(1)
#
if __name__ == '__main__':
if sys.argv[1:]:
print("%{{F{}}}{}".format("#555856", ICON))
else:
main()