source: python/wa.py @ c82a88d

Last change on this file since c82a88d was c82a88d, checked in by Wilmer van der Gaast <wilmer@…>, at 2015-06-08T20:22:08Z

Show presence as awayness instead of "onlineness".

  • Property mode set to 100755
File size: 14.5 KB
Line 
1#!/usr/bin/python
2
3import collections
4import logging
5import threading
6import time
7
8import yowsup
9
10from yowsup.layers.auth                        import YowAuthenticationProtocolLayer
11from yowsup.layers.protocol_acks               import YowAckProtocolLayer
12from yowsup.layers.protocol_chatstate          import YowChatstateProtocolLayer
13from yowsup.layers.protocol_contacts           import YowContactsIqProtocolLayer
14from yowsup.layers.protocol_groups             import YowGroupsProtocolLayer
15from yowsup.layers.protocol_ib                 import YowIbProtocolLayer
16from yowsup.layers.protocol_iq                 import YowIqProtocolLayer
17from yowsup.layers.protocol_messages           import YowMessagesProtocolLayer
18from yowsup.layers.protocol_notifications      import YowNotificationsProtocolLayer
19from yowsup.layers.protocol_presence           import YowPresenceProtocolLayer
20from yowsup.layers.protocol_privacy            import YowPrivacyProtocolLayer
21from yowsup.layers.protocol_profiles           import YowProfilesProtocolLayer
22from yowsup.layers.protocol_receipts           import YowReceiptProtocolLayer
23from yowsup.layers.network                     import YowNetworkLayer
24from yowsup.layers.coder                       import YowCoderLayer
25from yowsup.stacks import YowStack, YowStackBuilder
26from yowsup.common import YowConstants
27from yowsup.layers import YowLayerEvent
28from yowsup.stacks import YowStack, YOWSUP_CORE_LAYERS
29from yowsup import env
30
31from yowsup.layers.interface                             import YowInterfaceLayer, ProtocolEntityCallback
32from yowsup.layers.protocol_acks.protocolentities        import *
33from yowsup.layers.protocol_chatstate.protocolentities   import *
34from yowsup.layers.protocol_contacts.protocolentities    import *
35from yowsup.layers.protocol_groups.protocolentities      import *
36from yowsup.layers.protocol_ib.protocolentities          import *
37from yowsup.layers.protocol_iq.protocolentities          import *
38from yowsup.layers.protocol_media.mediauploader import MediaUploader
39from yowsup.layers.protocol_media.protocolentities       import *
40from yowsup.layers.protocol_messages.protocolentities    import *
41from yowsup.layers.protocol_notifications.protocolentities import *
42from yowsup.layers.protocol_presence.protocolentities    import *
43from yowsup.layers.protocol_privacy.protocolentities     import *
44from yowsup.layers.protocol_profiles.protocolentities    import *
45from yowsup.layers.protocol_receipts.protocolentities    import *
46from yowsup.layers.axolotl.protocolentities.iq_key_get import GetKeysIqProtocolEntity
47from yowsup.layers.axolotl import YowAxolotlLayer
48from yowsup.common.tools import ModuleTools
49
50import implugin
51
52logger = logging.getLogger("yowsup.layers.network.layer")
53logger.setLevel(logging.DEBUG)
54ch = logging.StreamHandler()
55ch.setLevel(logging.DEBUG)
56logger.addHandler(ch)
57
58
59# Tried this but yowsup is not passing back the result, will have to update the library. :-(
60class GetStatusIqProtocolEntity(IqProtocolEntity):
61        def __init__(self, jids=None):
62                super(GetStatusIqProtocolEntity, self).__init__("status", None, _type="get", to="s.whatsapp.net")
63                self.jids = jids or []
64
65        def toProtocolTreeNode(self):
66                from yowsup.structs import ProtocolTreeNode
67               
68                node = super(GetStatusIqProtocolEntity, self).toProtocolTreeNode()
69                sr = ProtocolTreeNode("status")
70                node.addChild(sr)
71                for jid in self.jids:
72                        sr.addChild(ProtocolTreeNode("user", {"jid": jid}))
73                return node
74
75
76class BitlBeeLayer(YowInterfaceLayer):
77
78        def __init__(self, *a, **kwa):
79                super(BitlBeeLayer, self).__init__(*a, **kwa)
80
81        def receive(self, entity):
82                print "Received: %r" % entity
83                #print entity
84                super(BitlBeeLayer, self).receive(entity)
85
86        def Ship(self, entity):
87                """Send an entity into Yowsup, but through the correct thread."""
88                print "Queueing: %s" % entity.getTag()
89                #print entity
90                def doit():
91                        self.toLower(entity)
92                self.getStack().execDetached(doit)
93
94        @ProtocolEntityCallback("success")
95        def onSuccess(self, entity):
96                self.b = self.getStack().getProp("org.bitlbee.Bijtje")
97                self.cb = self.b.bee
98                self.b.yow = self
99               
100                self.cb.log("Authenticated, syncing contact list")
101               
102                # We're done once this set is empty.
103                self.todo = set(["contacts", "groups"])
104               
105                # Supposedly WA can also do national-style phone numbers without
106                # a + prefix BTW (relative to I guess the user's country?). I
107                # don't want to support this at least for now.
108                numbers = [("+" + x.split("@")[0]) for x in self.cb.get_local_contacts()]
109                self.toLower(GetSyncIqProtocolEntity(numbers))
110                self.toLower(ListGroupsIqProtocolEntity())
111               
112                try:
113                        self.toLower(PresenceProtocolEntity(name=self.b.setting("name")))
114                except KeyError:
115                        pass
116
117        def check_connected(self, done):
118                if self.todo is None:
119                        return
120                self.todo.remove(done)
121                if not self.todo:
122                        self.todo = None
123                        self.cb.connected()
124       
125        @ProtocolEntityCallback("failure")
126        def onFailure(self, entity):
127                self.b = self.getStack().getProp("org.bitlbee.Bijtje")
128                self.cb = self.b.bee
129                self.cb.error(entity.getReason())
130                self.cb.logout(False)
131
132        def onEvent(self, event):
133                # TODO: Make this work without, hmm, over-recursing. (This handler
134                # getting called when we initiated the disconnect, which upsets yowsup.)
135                if event.getName() == "orgopenwhatsapp.yowsup.event.network.disconnected":
136                        self.cb.error(event.getArg("reason"))
137                        self.cb.logout(True)
138                        self.getStack().execDetached(self.daemon.StopDaemon)
139                else:
140                        print "Received event: %s name %s" % (event, event.getName())
141       
142        @ProtocolEntityCallback("presence")
143        def onPresence(self, pres):
144                if pres.getFrom() == self.b.account["user"]:
145                        # WA returns our own presence. Meh.
146                        return
147               
148                # Online/offline is not really how WA works. Let's show everyone
149                # as online but unavailable folks as away. This also solves the
150                # problem of offline->IRC /quit causing the persons to leave chat
151                # channels as well (and not reappearing there when they return).
152                status = 8 | 1  # MOBILE | ONLINE
153                if pres.getType() == "unavailable":
154                        status |= 4  # AWAY
155                self.cb.buddy_status(pres.getFrom(), status, None, None)
156               
157                try:
158                        # Last online time becomes idle time which I guess is
159                        # sane enough?
160                        self.cb.buddy_times(pres.getFrom(), 0, int(pres.getLast()))
161                except (ValueError, TypeError):
162                        # Could be "error" or, more likely, "deny", or None.
163                        pass
164       
165        @ProtocolEntityCallback("message")
166        def onMessage(self, msg):
167                if hasattr(msg, "getBody"):
168                        text = msg.getBody()
169                elif hasattr(msg, "getCaption") and hasattr(msg, "getMediaUrl"):
170                        lines = []
171                        if msg.getMediaUrl():
172                                lines.append(msg.getMediaUrl())
173                        else:
174                                lines.append("<Broken link>")
175                        if msg.getCaption():
176                                lines.append(msg.getCaption())
177                        text = "\n".join(lines)
178
179                if msg.getParticipant():
180                        group = self.b.groups[msg.getFrom()]
181                        if "id" in group:
182                                self.cb.chat_msg(group["id"], msg.getParticipant(), text, 0, msg.getTimestamp())
183                        else:
184                                self.cb.log("Warning: Activity in room %s" % msg.getFrom())
185                                self.b.groups[msg.getFrom()].setdefault("queue", []).append(msg)
186                else:
187                        self.cb.buddy_msg(msg.getFrom(), text, 0, msg.getTimestamp())
188
189                # ACK is required! So only use return above in case of errors.
190                # (So that we will/might get a retry after restarting.)
191                self.toLower(OutgoingReceiptProtocolEntity(msg.getId(), msg.getFrom()))
192
193        @ProtocolEntityCallback("receipt")
194        def onReceipt(self, entity):
195                ack = OutgoingAckProtocolEntity(entity.getId(), entity.getTag(),
196                                                entity.getType(), entity.getFrom())
197                self.toLower(ack)
198
199        @ProtocolEntityCallback("iq")
200        def onIq(self, entity):
201                if isinstance(entity, ResultSyncIqProtocolEntity):
202                        return self.onSyncResult(entity)
203                elif isinstance(entity, ListParticipantsResultIqProtocolEntity):
204                        return self.b.chat_join_participants(entity)
205                elif isinstance(entity, ListGroupsResultIqProtocolEntity):
206                        return self.onListGroupsResult(entity)
207       
208        def onSyncResult(self, entity):
209                # TODO HERE AND ELSEWHERE: Thread idiocy happens when going
210                # from here to the IMPlugin. Check how bjsonrpc lets me solve that.
211                for num, jid in entity.inNumbers.iteritems():
212                        self.toLower(SubscribePresenceProtocolEntity(jid))
213                        self.cb.add_buddy(jid, "")
214                if entity.outNumbers:
215                        self.cb.error("Not on WhatsApp: %s" %
216                                      ", ".join(entity.outNumbers.keys()))
217                if entity.invalidNumbers:
218                        self.cb.error("Invalid numbers: %s" %
219                                      ", ".join(entity.invalidNumbers))
220
221                # Disabled since yowsup won't give us the result...
222                if entity.inNumbers and False:
223                        self.toLower(GetStatusIqProtocolEntity(entity.inNumbers.values()))
224                        self.todo.add("statuses")
225                       
226                self.check_connected("contacts")
227
228        def onListGroupsResult(self, groups):
229                """Save group info for later if the user decides to join."""
230                for g in groups.getGroups():
231                        jid = g.getId()
232                        if "@" not in jid:
233                                jid += "@g.us"
234                        group = self.b.groups[jid]
235                       
236                        # Save it. We're going to mix ListGroups elements and
237                        # Group-Subject notifications there, which don't have
238                        # consistent fieldnames for the same bits of info \o/
239                        g.getSubjectTimestamp = g.getSubjectTime
240                        group["topic"] = g
241
242                self.check_connected("groups")
243
244        @ProtocolEntityCallback("notification")
245        def onNotification(self, ent):
246                if isinstance(ent, StatusNotificationProtocolEntity):
247                        return self.onStatusNotification(ent)
248                elif isinstance(ent, SubjectGroupsNotificationProtocolEntity):
249                        return self.onGroupSubjectNotification(ent)
250
251        def onStatusNotification(self, status):
252                print "New status for %s: %s" % (status.getFrom(), status.status)
253                self.bee.buddy_status_msg(status.getFrom(), status.status)
254       
255        def onGroupSubjectNotification(self, sub):
256                print "New /topic for %s: %s" % (sub.getFrom(), sub.getSubject())
257                group = self.b.groups[sub.getFrom()]
258                group["topic"] = sub
259                id = group.get("id", None)
260                if id is not None:
261                        self.cb.chat_topic(id, sub.getSubjectOwner(),
262                                           sub.getSubject(), sub.getSubjectTimestamp())
263
264        @ProtocolEntityCallback("media")
265        def onMedia(self, med):
266                """Your PC better be MPC3 compliant!"""
267                print "YAY MEDIA! %r" % med
268                print med
269
270        #@ProtocolEntityCallback("chatstate")
271        #def onChatstate(self, entity):
272        #       print(entity)
273
274
275class YowsupDaemon(threading.Thread):
276        daemon = True
277        stack = None
278
279        class Terminate(Exception):
280                pass
281
282        def run(self):
283                try:
284                        self.stack.loop(timeout=0.2, discrete=0.2, count=1)
285                except YowsupDaemon.Terminate:
286                        print "Exiting loop!"
287                        pass
288       
289        def StopDaemon(self):
290                # Ugly, but yowsup offers no "run single iteration" version
291                # of their event loop :-(
292                raise YowsupDaemon.Terminate
293
294
295class YowsupIMPlugin(implugin.BitlBeeIMPlugin):
296        NAME = "wa"
297        SETTINGS = {
298                "cc": {
299                        # Country code. Seems to be required for registration only.
300                        "type": "int",
301                },
302                "name": {
303                        "flags": 0x100, # NULL_OK
304                },
305        }
306        AWAY_STATES = ["Away"]
307        ACCOUNT_FLAGS = 14 # HANDLE_DOMAINS + STATUS_MESSAGE + LOCAL_CONTACTS
308        # TODO: HANDLE_DOMAIN in right place (add ... ... nick bug)
309
310        def login(self, account):
311                self.stack = self.build_stack(account)
312                self.daemon = YowsupDaemon(name="yowsup")
313                self.daemon.stack = self.stack
314                self.daemon.start()
315                self.bee.log("Started yowsup thread")
316               
317                self.groups = collections.defaultdict(dict)
318                self.groups_by_id = {}
319
320        def keepalive(self):
321                # Too noisy while debugging
322                # WTF yowsup is SPAWNING A THREAD just for this. Figure out
323                # how to kill that nonsense.
324                pass
325                #self.yow.Ship(PingIqProtocolEntity(to="s.whatsapp.net"))
326
327        def logout(self):
328                self.stack.broadcastEvent(YowLayerEvent(YowNetworkLayer.EVENT_STATE_DISCONNECT))
329                self.stack.execDetached(self.daemon.StopDaemon)
330
331        def buddy_msg(self, to, text, flags):
332                msg = TextMessageProtocolEntity(text, to=to)
333                self.yow.Ship(msg)
334
335        def add_buddy(self, handle, _group):
336                self.yow.Ship(GetSyncIqProtocolEntity(
337                    ["+" + handle.split("@")[0]], mode=GetSyncIqProtocolEntity.MODE_DELTA))
338
339        def remove_buddy(self, handle, _group):
340                self.yow.Ship(UnsubscribePresenceProtocolEntity(handle))
341
342        def set_away(self, state, status):
343                print "Trying to set status to %r, %r" % (state, status)
344                if state:
345                        # Only one option offered so None = available, not None = away.
346                        self.yow.Ship(AvailablePresenceProtocolEntity())
347                else:
348                        self.yow.Ship(UnavailablePresenceProtocolEntity())
349                if status:
350                        self.yow.Ship(SetStatusIqProtocolEntity(status))
351
352        def set_set_name(self, _key, value):
353                self.yow.Ship(PresenceProtocolEntity(name=value))
354
355        def chat_join(self, id, name, _nick, _password, settings):
356                print "New chat created with id: %d" % id
357                group = self.groups[name]
358                group.update({"id": id, "name": name})
359                self.groups_by_id[id] = group
360               
361                gi = group.get("topic", None)
362                if gi:
363                        self.bee.chat_topic(id, gi.getSubjectOwner(),
364                                            gi.getSubject(), gi.getSubjectTimestamp())
365               
366                # WA doesn't really have a concept of joined or not, just
367                # long-term membership. Let's just sync state (we have
368                # basic info but not yet a member list) and ACK the join
369                # once that's done.
370                self.yow.Ship(ParticipantsGroupsIqProtocolEntity(name))
371
372        def chat_join_participants(self, entity):
373                group = self.groups[entity.getFrom()]
374                id = group["id"]
375                for p in entity.getParticipants():
376                        if p != self.account["user"]:
377                                self.bee.chat_add_buddy(id, p)
378
379                # Add the user themselves last to avoid a visible join flood.
380                self.bee.chat_add_buddy(id, self.account["user"])
381                for msg in group.setdefault("queue", []):
382                        ## TODO: getBody fails for media msgs.
383                        self.bee.chat_msg(group["id"], msg.getParticipant(), msg.getBody(), 0, msg.getTimestamp())
384                del group["queue"]
385       
386        def chat_msg(self, id, text, flags):
387                msg = TextMessageProtocolEntity(text, to=self.groups_by_id[id]["name"])
388                self.yow.Ship(msg)
389
390        def chat_leave(self, id):
391                # WA never really let us leave, so just disconnect id and jid.
392                group = self.groups_by_id[id]
393                del self.groups_by_id[id]
394                del group["id"]
395
396        def build_stack(self, account):
397                self.account = account
398                creds = (account["user"].split("@")[0], account["pass"])
399
400                stack = (YowStackBuilder()
401                         .pushDefaultLayers(False)
402                         .push(BitlBeeLayer)
403                         .build())
404                stack.setProp(YowAuthenticationProtocolLayer.PROP_CREDENTIALS, creds)
405                stack.setProp(YowNetworkLayer.PROP_ENDPOINT, YowConstants.ENDPOINTS[0])
406                stack.setProp(YowCoderLayer.PROP_DOMAIN, YowConstants.DOMAIN)
407                stack.setProp(YowCoderLayer.PROP_RESOURCE, env.CURRENT_ENV.getResource())
408                try:
409                        stack.setProp(YowIqProtocolLayer.PROP_PING_INTERVAL, 0)
410                except AttributeError:
411                        # Ping setting only exists since May 2015.
412                        from yowsup.layers.protocol_iq.layer import YowPingThread
413                        YowPingThread.start = lambda x: None
414
415                stack.setProp("org.bitlbee.Bijtje", self)
416
417                stack.broadcastEvent(YowLayerEvent(YowNetworkLayer.EVENT_STATE_CONNECT))
418
419                return stack
420
421
422implugin.RunPlugin(YowsupIMPlugin, debug=True)
Note: See TracBrowser for help on using the repository browser.