summaryrefslogtreecommitdiff
path: root/mqtt-notify.py
blob: bf245385a2af465c90a8652aca487c4ed6efc27f (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
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# SPDX-License-Identifier: GPL-3.0-or-later

# Relevant API docs:
#   https://pypi.org/project/paho-mqtt/
#   https://lazka.github.io/pgi-docs/#Notify-0.7
#   https://lazka.github.io/pgi-docs/#Secret-1
#   https://lazka.github.io/pgi-docs/#GLib-2.0
#   https://dbus.freedesktop.org/doc/dbus-python/dbus.mainloop.html

import argparse
import configparser
import re
import signal
import sys
import paho.mqtt.client as mqtt
import gi
gi.require_version('Notify', '0.7')
gi.require_version('Secret', '1')
from gi.repository import GLib, Notify, Secret

from dbus.mainloop.glib import DBusGMainLoop
DBusGMainLoop(set_as_default=True)

chan_msg = re.compile(r'\[(?P<channel>#.*?)\]\n<\s*(?P<nick>.*?)> \| (?P<msg>.*)')
priv_msg = re.compile(r'\(PM: (?P<nick>.*?)\)\n(?P<msg>.*)')
subj_fmt = re.compile(r'IRC message (on|from) (?P<key>.*)')

notification_map = {}

class Signaler:
    def __init__(self, loop):
        self.loop = loop

    def handler(self, *_):
        self.loop.quit()

def on_connect(client, userdata, flags, rc):
    print("Connected")

    # Subscribing in on_connect() means that if we lose the connection and
    # reconnect then subscriptions will be renewed.
    client.subscribe(userdata)

def on_close(notification):
    key = ''
    if (m := subj_fmt.match(notification.props.summary)) is not None:
        key = m.group('key')

    if key in notification_map:
        for i in notification_map[key]:
            if i is not notification:
                i.close()
        del notification_map[key]

def on_message(client, userdata, msg):
    icon = '/usr/share/icons/HighContrast/scalable/apps-extra/internet-group-chat.svg'
    message = msg.payload.decode('utf-8')

    if (m := re.match(chan_msg, message)) is not None:
        subject = 'IRC message on {}'.format(m.group('channel'))
        body = '<{}> {}'.format(m.group('nick'), m.group('msg'))
        key = m.group('channel')
    if (m := re.match(priv_msg, message)) is not None:
        subject = 'IRC message from {}'.format(m.group('nick'))
        body = '<{}> {}'.format(m.group('nick'), m.group('msg'))
        key = m.group('nick')
    else:
        subject = 'IRC'
        body = message
        key = ''

    if key not in notification_map or len(notification_map[key]) == 1:
        n = Notify.Notification.new(subject, body, icon)
        n.set_category('im.received')
        n.connect('closed', on_close)

        if key not in notification_map:
            notification_map[key] = [n]
        else:
            notification_map[key].append(n)
    else:
        n = notification_map[key][1]
        n.update(subject, body, icon)

    n.show()

def on_disconnect(client, userdata, rc):
    print("Disconnected")

def password(loop, user, host):
    # Insert password with secret-tool(1). E.g.,
    #   secret-tool store --label="mqtts://example.com" user myuser service mqtt host example.com

    schema = Secret.Schema.new("org.freedesktop.Secret.Generic",
        Secret.SchemaFlags.NONE,
        {
            "user": Secret.SchemaAttributeType.STRING,
            "service": Secret.SchemaAttributeType.STRING,
            "host": Secret.SchemaAttributeType.STRING,
        }
    )
    attributes = {
        "user": user,
        "service": "mqtt",
        "host": host,
    }

    pw = None
    def on_password_lookup(source, result, unused):
        loop.quit()

        nonlocal pw
        pw = Secret.password_lookup_finish(result)

    while pw is None:
        Secret.password_lookup(schema, attributes, None, on_password_lookup, None)

        loop.run()
    return pw

def config(filename):
    try:
        with open(filename) as file:
            config = configparser.ConfigParser()
            config.read_file(file)

            cfg = config[configparser.DEFAULTSECT]
            broker = cfg['broker']
            topic = cfg['topic']
            port = int(cfg['port'])
            user = cfg['user']

            return user, broker, port, topic
    except:
        print("Failed to parse {}".format(filename), file=sys.stderr)
        sys.exit(-1)

def main(argv):
    loop = GLib.MainLoop()

    do = Signaler(loop)
    signal.signal(signal.SIGINT,  do.handler)
    signal.signal(signal.SIGTERM, do.handler)

    parser = argparse.ArgumentParser()
    parser.add_argument('-c', '--config', help='configuration file',
        type=argparse.FileType('r'), required=True)
    args = parser.parse_args()

    user, broker, port, topic = config(args.config.name)

    Notify.init('MQTT to Notify bridge')
    client = mqtt.Client(userdata=topic)

    client.tls_set()
    client.username_pw_set(user, password(loop, user, broker))
    client.on_connect = on_connect
    client.on_message = on_message
    client.on_disconnect = on_disconnect
    client.connect_async(broker, port, 60)

    client.loop_start()

    loop.run()

    client.loop_stop()
    client.disconnect()
    Notify.uninit()

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