source: python/wa.py @ 15c3a6b

Last change on this file since 15c3a6b was 15c3a6b, checked in by Wilmer van der Gaast <wilmer@…>, at 2015-06-22T09:24:59Z

Stop trying to get group participants list because WA/YS broke it.

  • Property mode set to 100755
File size: 16.3 KB
RevLine 
[63b017e]1#!/usr/bin/python
2
[b73409f]3import collections
[63b017e]4import logging
5import threading
[2b4402f]6import time
[63b017e]7
8import yowsup
9
10from yowsup.layers.auth                        import YowAuthenticationProtocolLayer
[5f8ad281]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
[63b017e]17from yowsup.layers.protocol_messages           import YowMessagesProtocolLayer
[5f8ad281]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
[63b017e]22from yowsup.layers.protocol_receipts           import YowReceiptProtocolLayer
23from yowsup.layers.network                     import YowNetworkLayer
24from yowsup.layers.coder                       import YowCoderLayer
[2b4402f]25from yowsup.stacks import YowStack, YowStackBuilder
[63b017e]26from yowsup.common import YowConstants
27from yowsup.layers import YowLayerEvent
28from yowsup.stacks import YowStack, YOWSUP_CORE_LAYERS
29from yowsup import env
30
[5f8ad281]31from yowsup.layers.interface                             import YowInterfaceLayer, ProtocolEntityCallback
[63b017e]32from yowsup.layers.protocol_acks.protocolentities        import *
[5f8ad281]33from yowsup.layers.protocol_chatstate.protocolentities   import *
34from yowsup.layers.protocol_contacts.protocolentities    import *
35from yowsup.layers.protocol_groups.protocolentities      import *
[63b017e]36from yowsup.layers.protocol_ib.protocolentities          import *
37from yowsup.layers.protocol_iq.protocolentities          import *
38from yowsup.layers.protocol_media.mediauploader import MediaUploader
[5f8ad281]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 *
[63b017e]44from yowsup.layers.protocol_profiles.protocolentities    import *
[5f8ad281]45from yowsup.layers.protocol_receipts.protocolentities    import *
[63b017e]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
[15c3a6b]52logger = logging.getLogger("yowsup.layers.logger.layer")
[63b017e]53logger.setLevel(logging.DEBUG)
54ch = logging.StreamHandler()
55ch.setLevel(logging.DEBUG)
56logger.addHandler(ch)
57
[114154c]58"""
59TODO/Things I'm unhappy about:
60
[15c3a6b]61About the fact that WhatsApp is a rubbish protocol that happily rejects
62every second stanza you send it if you're trying to implement a client that
63doesn't keep local state. See how to cope with that.. It'd help if Yowsup
64came with docs on what a normal login sequence looks like instead of just
65throwing some stanzas over a wall but hey.
66
[114154c]67The randomness of where which bits/state live, in the implugin and the
68yowsup layer. Can't really merge this but at least state should live in
69one place.
70
71Mix of silly CamelCase and proper_style. \o/
72
73Most important: This is NOT thread-clean. implugin can call into yowsup
74cleanly by throwing closures into a queue, but there's no mechanism in
75the opposite direction, I'll need to cook up some hack to make this
76possible through bjsonrpc's tiny event loop. I think I know how...
77
78And more. But let's first get this into a state where it even works..
79"""
[2700925]80
[63b017e]81class BitlBeeLayer(YowInterfaceLayer):
82
83        def __init__(self, *a, **kwa):
84                super(BitlBeeLayer, self).__init__(*a, **kwa)
[114154c]85                # Offline messages are sent while we're still logging in.
86                self.msg_queue = []
[63b017e]87
88        def receive(self, entity):
[2b4402f]89                print "Received: %r" % entity
[b09ce17]90                #print entity
[63b017e]91                super(BitlBeeLayer, self).receive(entity)
92
93        def Ship(self, entity):
94                """Send an entity into Yowsup, but through the correct thread."""
95                print "Queueing: %s" % entity.getTag()
[b09ce17]96                #print entity
[63b017e]97                def doit():
98                        self.toLower(entity)
99                self.getStack().execDetached(doit)
100
101        @ProtocolEntityCallback("success")
102        def onSuccess(self, entity):
103                self.b = self.getStack().getProp("org.bitlbee.Bijtje")
104                self.cb = self.b.bee
105                self.b.yow = self
[a852b2b]106               
107                self.cb.log("Authenticated, syncing contact list")
108               
109                # We're done once this set is empty.
[d832164]110                self.todo = set(["contacts", "groups", "ping"])
[a852b2b]111               
112                # Supposedly WA can also do national-style phone numbers without
113                # a + prefix BTW (relative to I guess the user's country?). I
114                # don't want to support this at least for now.
115                numbers = [("+" + x.split("@")[0]) for x in self.cb.get_local_contacts()]
116                self.toLower(GetSyncIqProtocolEntity(numbers))
[cb1b973]117                self.toLower(ListGroupsIqProtocolEntity())
[d832164]118                self.b.keepalive()
[a852b2b]119               
[b09ce17]120                try:
121                        self.toLower(PresenceProtocolEntity(name=self.b.setting("name")))
122                except KeyError:
123                        pass
[a852b2b]124
125        def check_connected(self, done):
[114154c]126                if not self.todo:
[a852b2b]127                        return
128                self.todo.remove(done)
129                if not self.todo:
130                        self.cb.connected()
[114154c]131                        self.flush_msg_queue()
132       
133        def flush_msg_queue(self):
134                for msg in self.msg_queue:
135                        self.onMessage(msg)
136                self.msg_queue = None
[63b017e]137       
138        @ProtocolEntityCallback("failure")
139        def onFailure(self, entity):
140                self.b = self.getStack().getProp("org.bitlbee.Bijtje")
141                self.cb = self.b.bee
142                self.cb.error(entity.getReason())
143                self.cb.logout(False)
[5f8ad281]144
145        def onEvent(self, event):
[b73409f]146                # TODO: Make this work without, hmm, over-recursing. (This handler
147                # getting called when we initiated the disconnect, which upsets yowsup.)
148                if event.getName() == "orgopenwhatsapp.yowsup.event.network.disconnected":
149                        self.cb.error(event.getArg("reason"))
150                        self.cb.logout(True)
[5f8ad281]151                        self.getStack().execDetached(self.daemon.StopDaemon)
[b73409f]152                else:
153                        print "Received event: %s name %s" % (event, event.getName())
[5f8ad281]154       
155        @ProtocolEntityCallback("presence")
156        def onPresence(self, pres):
[a852b2b]157                if pres.getFrom() == self.b.account["user"]:
158                        # WA returns our own presence. Meh.
159                        return
160               
[c82a88d]161                # Online/offline is not really how WA works. Let's show everyone
162                # as online but unavailable folks as away. This also solves the
163                # problem of offline->IRC /quit causing the persons to leave chat
164                # channels as well (and not reappearing there when they return).
165                status = 8 | 1  # MOBILE | ONLINE
166                if pres.getType() == "unavailable":
167                        status |= 4  # AWAY
[b09ce17]168                self.cb.buddy_status(pres.getFrom(), status, None, None)
[a852b2b]169               
[cb1b973]170                try:
171                        # Last online time becomes idle time which I guess is
172                        # sane enough?
173                        self.cb.buddy_times(pres.getFrom(), 0, int(pres.getLast()))
[2446e4c]174                except (ValueError, TypeError):
175                        # Could be "error" or, more likely, "deny", or None.
[cb1b973]176                        pass
[63b017e]177       
178        @ProtocolEntityCallback("message")
179        def onMessage(self, msg):
[114154c]180                if self.todo:
181                        # We're still logging in, so wait.
182                        self.msg_queue.append(msg)
183                        return
[63b017e]184
[114154c]185                self.b.show_message(msg)
[b73409f]186
187                # ACK is required! So only use return above in case of errors.
188                # (So that we will/might get a retry after restarting.)
189                self.toLower(OutgoingReceiptProtocolEntity(msg.getId(), msg.getFrom()))
[b09ce17]190
[63b017e]191        @ProtocolEntityCallback("receipt")
192        def onReceipt(self, entity):
[5f8ad281]193                ack = OutgoingAckProtocolEntity(entity.getId(), entity.getTag(),
194                                                entity.getType(), entity.getFrom())
[63b017e]195                self.toLower(ack)
196
[2b4402f]197        @ProtocolEntityCallback("iq")
198        def onIq(self, entity):
199                if isinstance(entity, ResultSyncIqProtocolEntity):
200                        return self.onSyncResult(entity)
[433c90b]201                elif isinstance(entity, ListParticipantsResultIqProtocolEntity):
202                        return self.b.chat_join_participants(entity)
[cb1b973]203                elif isinstance(entity, ListGroupsResultIqProtocolEntity):
204                        return self.onListGroupsResult(entity)
[d832164]205                elif "ping" in self.todo: # Pong has no type, sigh.
206                        if "contacts" in self.todo:
207                                # Shitty Whatsapp rejected the sync request, and
208                                # annoying Yowsup doesn't inform on error responses.
209                                # So instead, if we received no response to it but
210                                # did get our ping back, declare failure.
211                                self.onSyncResultFail()
[15c3a6b]212                        if "groups" in self.todo:
213                                # Well fuck this. Just reject ALL the things!
214                                # Maybe I don't need this one then.
215                                self.check_connected("groups")
[d832164]216                        self.check_connected("ping")
[2b4402f]217       
218        def onSyncResult(self, entity):
[433c90b]219                # TODO HERE AND ELSEWHERE: Thread idiocy happens when going
[2b4402f]220                # from here to the IMPlugin. Check how bjsonrpc lets me solve that.
[a852b2b]221                for num, jid in entity.inNumbers.iteritems():
222                        self.toLower(SubscribePresenceProtocolEntity(jid))
223                        self.cb.add_buddy(jid, "")
[2b4402f]224                if entity.outNumbers:
[433c90b]225                        self.cb.error("Not on WhatsApp: %s" %
226                                      ", ".join(entity.outNumbers.keys()))
[2b4402f]227                if entity.invalidNumbers:
[433c90b]228                        self.cb.error("Invalid numbers: %s" %
[c82a88d]229                                      ", ".join(entity.invalidNumbers))
[2b4402f]230
[d832164]231                #self.getStatuses(entity.inNumbers.values())
232                self.check_connected("contacts")
233
234        def onSyncResultFail(self):
235                # Whatsapp rate-limits sync stanzas, so in case of failure
236                # just assume all contacts are valid.
237                for jid in self.cb.get_local_contacts():
238                        self.toLower(SubscribePresenceProtocolEntity(jid))
239                        self.cb.add_buddy(jid, "")
240                #self.getStatuses?
[a852b2b]241                self.check_connected("contacts")
242
[cb1b973]243        def onListGroupsResult(self, groups):
244                """Save group info for later if the user decides to join."""
245                for g in groups.getGroups():
246                        jid = g.getId()
247                        if "@" not in jid:
248                                jid += "@g.us"
[b73409f]249                        group = self.b.groups[jid]
250                       
251                        # Save it. We're going to mix ListGroups elements and
252                        # Group-Subject notifications there, which don't have
253                        # consistent fieldnames for the same bits of info \o/
254                        g.getSubjectTimestamp = g.getSubjectTime
255                        group["topic"] = g
[cb1b973]256
[a852b2b]257                self.check_connected("groups")
258
[d832164]259        def getStatuses(self, contacts):
260                return # Disabled since yowsup won't give us the result...
261                self.toLower(GetStatusIqProtocolEntity(contacts))
262                self.todo.add("statuses")
263
[2b4402f]264        @ProtocolEntityCallback("notification")
265        def onNotification(self, ent):
266                if isinstance(ent, StatusNotificationProtocolEntity):
267                        return self.onStatusNotification(ent)
[b73409f]268                elif isinstance(ent, SubjectGroupsNotificationProtocolEntity):
269                        return self.onGroupSubjectNotification(ent)
[cb1b973]270
[2b4402f]271        def onStatusNotification(self, status):
272                print "New status for %s: %s" % (status.getFrom(), status.status)
[cb1b973]273                self.bee.buddy_status_msg(status.getFrom(), status.status)
[b73409f]274       
275        def onGroupSubjectNotification(self, sub):
276                print "New /topic for %s: %s" % (sub.getFrom(), sub.getSubject())
277                group = self.b.groups[sub.getFrom()]
278                group["topic"] = sub
279                id = group.get("id", None)
280                if id is not None:
281                        self.cb.chat_topic(id, sub.getSubjectOwner(),
282                                           sub.getSubject(), sub.getSubjectTimestamp())
[cb1b973]283
284        @ProtocolEntityCallback("media")
285        def onMedia(self, med):
286                """Your PC better be MPC3 compliant!"""
287                print "YAY MEDIA! %r" % med
288                print med
[2b4402f]289
[b09ce17]290        #@ProtocolEntityCallback("chatstate")
291        #def onChatstate(self, entity):
292        #       print(entity)
[5f8ad281]293
294
[63b017e]295class YowsupDaemon(threading.Thread):
296        daemon = True
297        stack = None
298
299        class Terminate(Exception):
300                pass
301
302        def run(self):
303                try:
304                        self.stack.loop(timeout=0.2, discrete=0.2, count=1)
305                except YowsupDaemon.Terminate:
306                        print "Exiting loop!"
307                        pass
308       
309        def StopDaemon(self):
310                # Ugly, but yowsup offers no "run single iteration" version
311                # of their event loop :-(
312                raise YowsupDaemon.Terminate
313
[2b4402f]314
[63b017e]315class YowsupIMPlugin(implugin.BitlBeeIMPlugin):
316        NAME = "wa"
317        SETTINGS = {
318                "cc": {
[a852b2b]319                        # Country code. Seems to be required for registration only.
[63b017e]320                        "type": "int",
321                },
322                "name": {
323                        "flags": 0x100, # NULL_OK
324                },
325        }
[b09ce17]326        AWAY_STATES = ["Away"]
[5f8ad281]327        ACCOUNT_FLAGS = 14 # HANDLE_DOMAINS + STATUS_MESSAGE + LOCAL_CONTACTS
[63b017e]328        # TODO: HANDLE_DOMAIN in right place (add ... ... nick bug)
[d832164]329        PING_INTERVAL = 299 # seconds
[5f8ad281]330
[63b017e]331        def login(self, account):
332                self.stack = self.build_stack(account)
333                self.daemon = YowsupDaemon(name="yowsup")
334                self.daemon.stack = self.stack
335                self.daemon.start()
336                self.bee.log("Started yowsup thread")
[5f8ad281]337               
[b73409f]338                self.groups = collections.defaultdict(dict)
[b09ce17]339                self.groups_by_id = {}
[63b017e]340
[d832164]341                self.next_ping = None
342
[63b017e]343        def keepalive(self):
[d832164]344                if self.next_ping and (time.time() < self.next_ping):
345                        return
346                self.yow.Ship(PingIqProtocolEntity(to="s.whatsapp.net"))
347                self.next_ping = time.time() + self.PING_INTERVAL
[63b017e]348
349        def logout(self):
350                self.stack.broadcastEvent(YowLayerEvent(YowNetworkLayer.EVENT_STATE_DISCONNECT))
351                self.stack.execDetached(self.daemon.StopDaemon)
352
353        def buddy_msg(self, to, text, flags):
354                msg = TextMessageProtocolEntity(text, to=to)
355                self.yow.Ship(msg)
356
357        def add_buddy(self, handle, _group):
[a852b2b]358                self.yow.Ship(GetSyncIqProtocolEntity(
359                    ["+" + handle.split("@")[0]], mode=GetSyncIqProtocolEntity.MODE_DELTA))
[63b017e]360
361        def remove_buddy(self, handle, _group):
362                self.yow.Ship(UnsubscribePresenceProtocolEntity(handle))
363
[b09ce17]364        def set_away(self, state, status):
365                print "Trying to set status to %r, %r" % (state, status)
366                if state:
367                        # Only one option offered so None = available, not None = away.
368                        self.yow.Ship(AvailablePresenceProtocolEntity())
369                else:
370                        self.yow.Ship(UnavailablePresenceProtocolEntity())
371                if status:
372                        self.yow.Ship(SetStatusIqProtocolEntity(status))
[63b017e]373
374        def set_set_name(self, _key, value):
[2b4402f]375                self.yow.Ship(PresenceProtocolEntity(name=value))
[63b017e]376
[b09ce17]377        def chat_join(self, id, name, _nick, _password, settings):
378                print "New chat created with id: %d" % id
[cb1b973]379                group = self.groups[name]
[b73409f]380                group.update({"id": id, "name": name})
[cb1b973]381                self.groups_by_id[id] = group
382               
[b73409f]383                gi = group.get("topic", None)
[cb1b973]384                if gi:
385                        self.bee.chat_topic(id, gi.getSubjectOwner(),
[b73409f]386                                            gi.getSubject(), gi.getSubjectTimestamp())
[cb1b973]387               
388                # WA doesn't really have a concept of joined or not, just
[b73409f]389                # long-term membership. Let's just sync state (we have
390                # basic info but not yet a member list) and ACK the join
391                # once that's done.
[15c3a6b]392                # Well except that WA/YS killed this one. \o/
393                #self.yow.Ship(ParticipantsGroupsIqProtocolEntity(name))
394               
395                # So for now do without a participant list..
396                #self.chat_join_participants(None)
397                self.chat_send_backlog(group)
[433c90b]398
399        def chat_join_participants(self, entity):
[15c3a6b]400                """
[433c90b]401                group = self.groups[entity.getFrom()]
402                id = group["id"]
403                for p in entity.getParticipants():
404                        if p != self.account["user"]:
405                                self.bee.chat_add_buddy(id, p)
[15c3a6b]406                """
[cb1b973]407
[15c3a6b]408        def chat_send_backlog(self, group):
[433c90b]409                # Add the user themselves last to avoid a visible join flood.
[15c3a6b]410                self.bee.chat_add_buddy(group["id"], self.account["user"])
[cb1b973]411                for msg in group.setdefault("queue", []):
[114154c]412                        self.b.show_message(msg)
[cb1b973]413                del group["queue"]
[b09ce17]414       
415        def chat_msg(self, id, text, flags):
416                msg = TextMessageProtocolEntity(text, to=self.groups_by_id[id]["name"])
417                self.yow.Ship(msg)
418
[cb1b973]419        def chat_leave(self, id):
420                # WA never really let us leave, so just disconnect id and jid.
421                group = self.groups_by_id[id]
422                del self.groups_by_id[id]
423                del group["id"]
424
[63b017e]425        def build_stack(self, account):
[b09ce17]426                self.account = account
[63b017e]427                creds = (account["user"].split("@")[0], account["pass"])
428
[2b4402f]429                stack = (YowStackBuilder()
430                         .pushDefaultLayers(False)
431                         .push(BitlBeeLayer)
432                         .build())
[63b017e]433                stack.setProp(YowAuthenticationProtocolLayer.PROP_CREDENTIALS, creds)
434                stack.setProp(YowNetworkLayer.PROP_ENDPOINT, YowConstants.ENDPOINTS[0])
435                stack.setProp(YowCoderLayer.PROP_DOMAIN, YowConstants.DOMAIN)
436                stack.setProp(YowCoderLayer.PROP_RESOURCE, env.CURRENT_ENV.getResource())
[dcfa886]437                try:
438                        stack.setProp(YowIqProtocolLayer.PROP_PING_INTERVAL, 0)
439                except AttributeError:
440                        # Ping setting only exists since May 2015.
441                        from yowsup.layers.protocol_iq.layer import YowPingThread
442                        YowPingThread.start = lambda x: None
443
[63b017e]444                stack.setProp("org.bitlbee.Bijtje", self)
445
446                stack.broadcastEvent(YowLayerEvent(YowNetworkLayer.EVENT_STATE_CONNECT))
447
448                return stack
449
[b73409f]450
[114154c]451        # Not RPCs from here on.
452        def show_message(self, msg):
453                if hasattr(msg, "getBody"):
454                        text = msg.getBody()
455                elif hasattr(msg, "getCaption") and hasattr(msg, "getMediaUrl"):
456                        lines = []
457                        if msg.getMediaUrl():
458                                lines.append(msg.getMediaUrl())
459                        else:
460                                lines.append("<Broken link>")
461                        if msg.getCaption():
462                                lines.append(msg.getCaption())
463                        text = "\n".join(lines)
464
465                if msg.getParticipant():
466                        group = self.groups[msg.getFrom()]
467                        if "id" in group:
[15c3a6b]468                                self.bee.chat_add_buddy(group["id"], msg.getParticipant())
[114154c]469                                self.bee.chat_msg(group["id"], msg.getParticipant(), text, 0, msg.getTimestamp())
470                        else:
471                                self.bee.log("Warning: Activity in room %s" % msg.getFrom())
472                                self.groups[msg.getFrom()].setdefault("queue", []).append(msg)
473                else:
474                        self.bee.buddy_msg(msg.getFrom(), text, 0, msg.getTimestamp())
475
476
[63b017e]477implugin.RunPlugin(YowsupIMPlugin, debug=True)
Note: See TracBrowser for help on using the repository browser.