]> git.rmz.io Git - dotfiles.git/blob - isync/parse-mail.py
Makefile: add target for git
[dotfiles.git] / isync / parse-mail.py
1 #!/usr/bin/env python3
2
3 from datetime import timedelta
4 from email import message_from_file
5 import re
6 import sys
7 import youtube_dl
8
9
10 FROM = "{uploader} <noreply@youtube.com>"
11 SUBJECT = "{title}"
12 CONTENT = """\
13 {uploader} just uploaded a video
14 {title} ({duration})
15
16 {webpage_url}
17
18 Description
19 ───────────────────────────────────────────────────────────────────────
20
21 {description}
22
23 ───────────────────────────────────────────────────────────────────────
24
25 Manage notifications: https://www.youtube.com/subscription_manager
26 """
27
28
29 def parse_file(fd):
30 msg = message_from_file(fd)
31
32 payload = ""
33 if msg.is_multipart():
34 for part in msg.get_payload():
35 if part.get_content_type() != 'text/plain':
36 continue
37 charset = part.get_content_charset()
38 payload = part.get_payload(decode=True).decode(charset)
39 else:
40 payload = msg.get_payload(decode=True).decode(charset)
41
42 url = re.search(r'^https?://www.youtube.com/watch\?v=[\w-]{11}', payload, re.MULTILINE).group()
43 # print(url)
44 with youtube_dl.YoutubeDL({'quiet' : True}) as ytdl:
45 info = ytdl.extract_info(url, download=False, force_generic_extractor=True)
46
47 if info is None:
48 return False
49
50 info['duration'] = timedelta(seconds=info['duration'])
51
52 del msg['From']
53 msg['From'] = FROM.format(**info)
54
55 del msg['Subject']
56 msg['Subject'] = SUBJECT.format(**info)
57
58 msg.set_payload(CONTENT.format(**info))
59
60 return msg
61
62
63 if __name__ == "__main__":
64 if len(sys.argv) == 1:
65 msg = parse_file(sys.stdin)
66 else:
67 with open(sys.argv[1], 'r') as fd:
68 msg = parse_file(fd)
69 print(msg)