summaryrefslogtreecommitdiffstats
path: root/__init__.py
blob: b55f842120e591982a44dd1a4d6ee0ace7d072e6 (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
174
175
176
177
178
179
180
181
182
183
184
185
186
187
# coding=utf-8
from __future__ import absolute_import
import re
import io
import requests
import sleekxmpp

from octoprint.plugin import EventHandlerPlugin, SettingsPlugin


class OctoXMPP(EventHandlerPlugin, SettingsPlugin):

    def initialize(self):
        jid = self._settings.get(['xmpp', 'jid'])
        resource = self._settings.get(['xmpp', 'resource'])
        passwd = self._settings.get(['xmpp', 'password'])

        full_jid = sleekxmpp.JID(jid, resource=resource)
        self._xmpp = sleekxmpp.ClientXMPP(full_jid, passwd)

        def __session_start(event):
            self._xmpp.send_presence()
            self._xmpp.get_roster()
            self._join_groupchats()

        self._xmpp.add_event_handler('session_start', __session_start)
        self._xmpp.add_event_handler('message', self._process_message)

        self._xmpp.register_plugin('xep_0030') # disco
        self._xmpp.register_plugin('xep_0045') # muc
        self._xmpp.register_plugin('xep_0066') # oob
        self._xmpp.register_plugin('xep_0085') # chat state
        self._xmpp.register_plugin('xep_0184') # delivery receipts
        self._xmpp.register_plugin('xep_0363') # http upload

        self._xmpp.connect()
        self._xmpp.process(wait=True)

    def get_settings_defaults(self):
        return {
                'xmpp': {
                    'jid': "rupert@m3k.cc",
                    'resource': "Rupert",
                    'password': "KosselMini",
                    'recipients': [("groupchat", "3k@conference.m3k.cc"), ("chat", "derflob@derflob.de")]
                }
        }

    def _take_snapshot(self):
        snapshot = self._settings.global_get(['webcam', 'snapshot'])
        if (snapshot):
            req = requests.get(snapshot)

            if (req.ok):
                return (req.content, req.headers.get('content-type', None))

        return (None, None)

    def _msg_recipients(self, msg, send_image=True):
        for (chat_type, recipient) in self._settings.get(['xmpp', 'recipients']):
            self._xmpp.send_message(mto=recipient, mbody=msg, mtype=chat_type)

        if (send_image):
            (snapshot, content_type) = self._take_snapshot()
            if (snapshot):
                i = self._xmpp['xep_0363'].start_upload(
                        'rupert.jpg', io.BytesIO(snapshot), len(snapshot), content_type)

                def __send_get_url(get_url):
                    for (chat_type, recipient) in self._settings.get(['xmpp', 'recipients']):
                        m = self._xmpp.make_message(mto=recipient, mbody=get_url, mtype=chat_type)
                        m['oob']['url'] = get_url
                        m.send()

                self._xmpp.add_event_handler("http_upload::{}::finished".format(i),
                        __send_get_url, disposable=True)

    def _join_groupchats(self):
        nick = self._settings.get(['xmpp', 'resource'])
        for (chat_type, recipient) in self._settings.get(['xmpp', 'recipients']):
            if (chat_type == "groupchat"):
                self._xmpp['xep_0045'].joinMUC(recipient, nick)

    def on_event(self, event, data):
        if (event == "PrintDone"):
            self._msg_recipients("Zack, Feditsch!")
        elif (event == "PrintFailed"):
            self._msg_recipients("Da ging was schief!")
        elif (event == "PrintPaused"):
            self._msg_recipients("Druck pausiert.", False)
        elif (event == "PrintResumed"):
            self._msg_recipients("Druck resümiert.", False)
        elif (event == "PrintCancelled"):
            self._msg_recipients("Druck abgebrochen!")
        elif (event == "PrintStarted"):
            self._msg_recipients("Druck begonnen.")
        elif (event == "Connected"):
            self._msg_recipients("Connected to Rupert.")

    def _process_message(self, msg):
        if (msg.get_type() == "groupchat"):
            nick = self._settings.get(['xmpp', 'resource'])
            pattern = r"({}[\s\W]*)(?P<cmd>.*)".format(nick)
            m = re.match(pattern, msg['body'], re.I)
            if (m):
                cmd_str = m.group('cmd')
            else:
                return
        else:
            cmd_str = msg['body']

        if (' ' in cmd_str):
            (cmd, cmd_args) = cmd_str.split(' ', 1)
        else:
            cmd = cmd_str
            cmd_args = None

        if (cmd_args is not None):
            if (' ' in cmd_args):
                cmd_args = cmd_args.split(' ')
            else:
                cmd_args = [cmd_args]
        else:
            cmd_args = []

        fn = getattr(self, "_cmd_{}".format(cmd), self.__cmd_unknown(cmd))

        fn(msg, *cmd_args)

    def __cmd_unknown(self, cmd):
        def __cmd_unknown_reply(msg, *args):
            reply = msg.reply(body="Unknown command '{}' ({})!".format(cmd, ", ".join(args)))
            reply.send()

        return __cmd_unknown_reply

    def _cmd_status(self, msg, subsystem='all'):
        subsystems = ['temp', 'job', 'machine']

        if (subsystem == 'all'):
            reply = '\n\n'.join([getattr(self, "_status_{}".format(s))() for s in subsystems])
        elif (subsystem in subsystems):
            reply = getattr(self, "_status_{}".format(subsystem))()
        else:
            reply = "Unknown subsystem ({}).\nAvailable: {}".format(subsystem, ", ".join(['all'] + subsystems))

        msg.reply(body=reply).send()

    def _status_temp(self):
        if (self._printer.is_closed_or_error()):
            return "Temperatures:\nNo temperatures available."
        else:
            return "Temperatures:\n{}".format("\n".join(
                ["{tool}: {actual}°C (Target: {target}°C; Offset: {offset}°K".format(tool=tool, **temp)
                    for (tool, temp) in self._printer.get_current_temperatures()]))

    def _status_job(self):
        if (self._printer.is_printing()):
            return "Job state:\nSomething printing."
        else:
            return "Job state:\nNothing printing."

    def _status_machine(self):
        if (self._printer.is_closed_or_error()):
            return "Machine state:\nNot Connected/Error"
        else:
            return "Machine state:\n{}".format(self._printer.get_state_string())

    def _cmd_snapshot(self, msg):
        (snapshot, content_type) = self._take_snapshot()
        if (snapshot):
            i = self._xmpp['xep_0363'].start_upload(
                    'rupert.jpg', io.BytesIO(snapshot), len(snapshot), content_type)

            def __send_get_url(get_url):
                m = msg.reply(body=get_url)
                m['oob']['url'] = get_url
                m.send()

            self._xmpp.add_event_handler("http_upload::{}::finished".format(i),
                    __send_get_url, disposable=True)


__plugin_name__ = "OctoXMPP"
__plugin_version__ = "0.2.0"
__plugin_description__ = "Notify about some Events over XMPP."
__plugin_implementation__ = OctoXMPP()