summaryrefslogtreecommitdiff
path: root/user-profiles/feeds/imm-notmuch-insert.py
blob: b19651364ae6ed14efa59cbb83ab5f954cd578d3 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
#!@python@/bin/python

import json
import sys
import subprocess
from io import BytesIO
from email.message import EmailMessage
import configparser
from os import environ
from datetime import *
from dateutil.tz import *
from dateutil.parser import isoparse
from html2text import html2text

def main():
    notmuchConfig = configparser.ConfigParser()
    notmuchConfig.read(environ.get('NOTMUCH_CONFIG'))

    callbackMessage = json.load(sys.stdin)

    msg = EmailMessage()
    authors = ', '.join(map(lambda author: author['name'], callbackMessage['feed_item']['authors']))
    if authors:
        msg['From'] = f"{callbackMessage['feed_definition']['title']} ({authors}) <imm@imm.invalid>"
    else:
        msg['From'] = f"{callbackMessage['feed_definition']['title']} <imm@imm.invalid>"
    msg['To'] = f"{notmuchConfig['user']['name']} <{notmuchConfig['user']['primary_email']}>"
    msg['Subject'] = callbackMessage['feed_item']['title']
    msg['Item-Identifier'] = f"{callbackMessage['feed_item']['identifier']}"
    for link in callbackMessage['feed_item']['links']:
        linkArgs={}
        if 'relation' in link:
            linkArgs['relation'] = link['relation']
        if 'type' in link:
            linkArgs['type'] = link['type']
        if 'title' in link and link['title']:
            linkArgs['title'] = link['title']
        msg.add_header('Link', link['uri'], **linkArgs)
    date = None
    if 'date' in callbackMessage['feed_item']:
        date = isoparse(callbackMessage['feed_item']['date'])
    else:
        date = datetime.now(tzlocal())
    msg['Date'] = date.strftime('%a, %e %b %Y %T %z')

    msg.set_content(html2text(callbackMessage['feed_item']['content']))
    msg.add_alternative(callbackMessage['feed_item']['content'], subtype='html')


    subprocess.run(
        args=['notmuch', 'insert'],
        check=True,
        input=bytes(msg)
    )

if __name__ == '__main__':
    sys.exit(main())