]> git.rmz.io Git - dotfiles.git/blobdiff - mbsync/parse-mail.py
mbsync: rename deprecated isync to mbsync
[dotfiles.git] / mbsync / parse-mail.py
diff --git a/mbsync/parse-mail.py b/mbsync/parse-mail.py
new file mode 100755 (executable)
index 0000000..a72e768
--- /dev/null
@@ -0,0 +1,69 @@
+#!/usr/bin/env python3
+
+from datetime import timedelta
+from email import message_from_file
+import re
+import sys
+import youtube_dl
+
+
+FROM    = "{uploader} <noreply@youtube.com>"
+SUBJECT = "{title}"
+CONTENT = """\
+{uploader} just uploaded a video
+{title} ({duration})
+
+{webpage_url}
+
+Description
+───────────────────────────────────────────────────────────────────────
+
+{description}
+
+───────────────────────────────────────────────────────────────────────
+
+Manage notifications: https://www.youtube.com/subscription_manager
+"""
+
+
+def parse_file(fd):
+    msg = message_from_file(fd)
+
+    payload = ""
+    if msg.is_multipart():
+        for part in msg.get_payload():
+            if part.get_content_type() != 'text/plain':
+                continue
+            charset = part.get_content_charset()
+            payload = part.get_payload(decode=True).decode(charset)
+    else:
+        payload = msg.get_payload(decode=True).decode(charset)
+
+    url = re.search(r'^https?://www.youtube.com/watch\?v=[\w-]{11}', payload, re.MULTILINE).group()
+    # print(url)
+    with youtube_dl.YoutubeDL({'quiet' : True}) as ytdl:
+        info = ytdl.extract_info(url, download=False, force_generic_extractor=True)
+
+    if info is None:
+        return False
+
+    info['duration'] = timedelta(seconds=info['duration'])
+
+    del msg['From']
+    msg['From'] = FROM.format(**info)
+
+    del msg['Subject']
+    msg['Subject'] = SUBJECT.format(**info)
+
+    msg.set_payload(CONTENT.format(**info))
+
+    return msg
+
+
+if __name__ == "__main__":
+    if len(sys.argv) == 1:
+        msg = parse_file(sys.stdin)
+    else:
+        with open(sys.argv[1], 'r') as fd:
+            msg = parse_file(fd)
+    print(msg)