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
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.logger.layer")
53logger.setLevel(logging.DEBUG)
54ch = logging.StreamHandler()
55ch.setLevel(logging.DEBUG)
56logger.addHandler(ch)
57
58"""
59TODO/Things I'm unhappy about:
60
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
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"""
80
81class BitlBeeLayer(YowInterfaceLayer):
82
83        def __init__(self, *a, **kwa):
84                super(BitlBeeLayer, self).__init__(*a, **kwa)
85                # Offline messages are sent while we're still logging in.
86                self.msg_queue = []
87
88        def receive(self, entity):
89                print "Received: %r" % entity
90                #print entity
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()
96                #print entity
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
106               
107                self.cb.log("Authenticated, syncing contact list")
108               
109                # We're done once this set is empty.
110                self.todo = set(["contacts", "groups", "ping"])
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))
117                self.toLower(ListGroupsIqProtocolEntity())
118                self.b.keepalive()
119               
120                try:
121                        self.toLower(PresenceProtocolEntity(name=self.b.setting("name")))
122                except KeyError:
123                        pass
124
125        def check_connected(self, done):
126                if not self.todo:
127                        return
128                self.todo.remove(done)
129                if not self.todo:
130                        self.cb.connected()
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
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)
144
145        def onEvent(self, event):
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)
151                        self.getStack().execDetached(self.daemon.StopDaemon)
152                else:
153                        print "Received event: %s name %s" % (event, event.getName())
154       
155        @ProtocolEntityCallback("presence")
156        def onPresence(self, pres):
157                if pres.getFrom() == self.b.account["user"]:
158                        # WA returns our own presence. Meh.
159                        return
160               
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
168                self.cb.buddy_status(pres.getFrom(), status, None, None)
169               
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()))
174                except (ValueError, TypeError):
175                        # Could be "error" or, more likely, "deny", or None.
176                        pass
177       
178        @ProtocolEntityCallback("message")
179        def onMessage(self, msg):
180                if self.todo:
181                        # We're still logging in, so wait.
182                        self.msg_queue.append(msg)
183                        return
184
185                self.b.show_message(msg)
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()))
190
191        @ProtocolEntityCallback("receipt")
192        def onReceipt(self, entity):
193                ack = OutgoingAckProtocolEntity(entity.getId(), entity.getTag(),
194                                                entity.getType(), entity.getFrom())
195                self.toLower(ack)
196
197        @ProtocolEntityCallback("iq")
198        def onIq(self, entity):
199                if isinstance(entity, ResultSyncIqProtocolEntity):
200                        return self.onSyncResult(entity)
201                elif isinstance(entity, ListParticipantsResultIqProtocolEntity):
202                        return self.b.chat_join_participants(entity)
203                elif isinstance(entity, ListGroupsResultIqProtocolEntity):
204                        return self.onListGroupsResult(entity)
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()
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")
216                        self.check_connected("ping")
217       
218        def onSyncResult(self, entity):
219                # TODO HERE AND ELSEWHERE: Thread idiocy happens when going
220                # from here to the IMPlugin. Check how bjsonrpc lets me solve that.
221                for num, jid in entity.inNumbers.iteritems():
222                        self.toLower(SubscribePresenceProtocolEntity(jid))
223                        self.cb.add_buddy(jid, "")
224                if entity.outNumbers:
225                        self.cb.error("Not on WhatsApp: %s" %
226                                      ", ".join(entity.outNumbers.keys()))
227                if entity.invalidNumbers:
228                        self.cb.error("Invalid numbers: %s" %
229                                      ", ".join(entity.invalidNumbers))
230
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?
241                self.check_connected("contacts")
242
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"
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
256
257                self.check_connected("groups")
258
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
264        @ProtocolEntityCallback("notification")
265        def onNotification(self, ent):
266                if isinstance(ent, StatusNotificationProtocolEntity):
267                        return self.onStatusNotification(ent)
268                elif isinstance(ent, SubjectGroupsNotificationProtocolEntity):
269                        return self.onGroupSubjectNotification(ent)
270
271        def onStatusNotification(self, status):
272                print "New status for %s: %s" % (status.getFrom(), status.status)
273                self.bee.buddy_status_msg(status.getFrom(), status.status)
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())
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
289
290        #@ProtocolEntityCallback("chatstate")
291        #def onChatstate(self, entity):
292        #       print(entity)
293
294
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
314
315class YowsupIMPlugin(implugin.BitlBeeIMPlugin):
316        NAME = "wa"
317        SETTINGS = {
318                "cc": {
319                        # Country code. Seems to be required for registration only.
320                        "type": "int",
321                },
322                "name": {
323                        "flags": 0x100, # NULL_OK
324                },
325        }
326        AWAY_STATES = ["Away"]
327        ACCOUNT_FLAGS = 14 # HANDLE_DOMAINS + STATUS_MESSAGE + LOCAL_CONTACTS
328        # TODO: HANDLE_DOMAIN in right place (add ... ... nick bug)
329        PING_INTERVAL = 299 # seconds
330
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")
337               
338                self.groups = collections.defaultdict(dict)
339                self.groups_by_id = {}
340
341                self.next_ping = None
342
343        def keepalive(self):
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
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):
358                self.yow.Ship(GetSyncIqProtocolEntity(
359                    ["+" + handle.split("@")[0]], mode=GetSyncIqProtocolEntity.MODE_DELTA))
360
361        def remove_buddy(self, handle, _group):
362                self.yow.Ship(UnsubscribePresenceProtocolEntity(handle))
363
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))
373
374        def set_set_name(self, _key, value):
375                self.yow.Ship(PresenceProtocolEntity(name=value))
376
377        def chat_join(self, id, name, _nick, _password, settings):
378                print "New chat created with id: %d" % id
379                group = self.groups[name]
380                group.update({"id": id, "name": name})
381                self.groups_by_id[id] = group
382               
383                gi = group.get("topic", None)
384                if gi:
385                        self.bee.chat_topic(id, gi.getSubjectOwner(),
386                                            gi.getSubject(), gi.getSubjectTimestamp())
387               
388                # WA doesn't really have a concept of joined or not, just
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.
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)
398
399        def chat_join_participants(self, entity):
400                """
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)
406                """
407
408        def chat_send_backlog(self, group):
409                # Add the user themselves last to avoid a visible join flood.
410                self.bee.chat_add_buddy(group["id"], self.account["user"])
411                for msg in group.setdefault("queue", []):
412                        self.b.show_message(msg)
413                del group["queue"]
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
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
425        def build_stack(self, account):
426                self.account = account
427                creds = (account["user"].split("@")[0], account["pass"])
428
429                stack = (YowStackBuilder()
430                         .pushDefaultLayers(False)
431                         .push(BitlBeeLayer)
432                         .build())
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())
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
444                stack.setProp("org.bitlbee.Bijtje", self)
445
446                stack.broadcastEvent(YowLayerEvent(YowNetworkLayer.EVENT_STATE_CONNECT))
447
448                return stack
449
450
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:
468                                self.bee.chat_add_buddy(group["id"], msg.getParticipant())
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
477implugin.RunPlugin(YowsupIMPlugin, debug=True)
Note: See TracBrowser for help on using the repository browser.