source: python/wa.py @ dcfa886

Last change on this file since dcfa886 was dcfa886, checked in by Wilmer van der Gaast <wilmer@…>, at 2015-05-29T05:21:18Z

Try to disable the ping thread using a cleaner (very new) method.

  • Property mode set to 100755
File size: 14.2 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                status = 8 # MOBILE
149                if pres.getType() != "unavailable":
150                        status |= 1 # ONLINE
151                self.cb.buddy_status(pres.getFrom(), status, None, None)
152               
153                try:
154                        # Last online time becomes idle time which I guess is
155                        # sane enough?
156                        self.cb.buddy_times(pres.getFrom(), 0, int(pres.getLast()))
157                except (ValueError, TypeError):
158                        # Could be "error" or, more likely, "deny", or None.
159                        pass
160       
161        @ProtocolEntityCallback("message")
162        def onMessage(self, msg):
163                if hasattr(msg, "getBody"):
164                        text = msg.getBody()
165                elif hasattr(msg, "getCaption") and hasattr(msg, "getMediaUrl"):
166                        lines = []
167                        if msg.getMediaUrl():
168                                lines.append(msg.getMediaUrl())
169                        else:
170                                lines.append("<Broken link>")
171                        if msg.getCaption():
172                                lines.append(msg.getCaption())
173                        text = "\n".join(lines)
174
175                if msg.getParticipant():
176                        group = self.b.groups[msg.getFrom()]
177                        if "id" in group:
178                                self.cb.chat_msg(group["id"], msg.getParticipant(), text, 0, msg.getTimestamp())
179                        else:
180                                self.cb.log("Warning: Activity in room %s" % msg.getFrom())
181                                self.b.groups[msg.getFrom()].setdefault("queue", []).append(msg)
182                else:
183                        self.cb.buddy_msg(msg.getFrom(), text, 0, msg.getTimestamp())
184
185                # ACK is required! So only use return above in case of errors.
186                # (So that we will/might get a retry after restarting.)
187                self.toLower(OutgoingReceiptProtocolEntity(msg.getId(), msg.getFrom()))
188
189        @ProtocolEntityCallback("receipt")
190        def onReceipt(self, entity):
191                ack = OutgoingAckProtocolEntity(entity.getId(), entity.getTag(),
192                                                entity.getType(), entity.getFrom())
193                self.toLower(ack)
194
195        @ProtocolEntityCallback("iq")
196        def onIq(self, entity):
197                if isinstance(entity, ResultSyncIqProtocolEntity):
198                        return self.onSyncResult(entity)
199                elif isinstance(entity, ListParticipantsResultIqProtocolEntity):
200                        return self.b.chat_join_participants(entity)
201                elif isinstance(entity, ListGroupsResultIqProtocolEntity):
202                        return self.onListGroupsResult(entity)
203       
204        def onSyncResult(self, entity):
205                # TODO HERE AND ELSEWHERE: Thread idiocy happens when going
206                # from here to the IMPlugin. Check how bjsonrpc lets me solve that.
207                for num, jid in entity.inNumbers.iteritems():
208                        self.toLower(SubscribePresenceProtocolEntity(jid))
209                        self.cb.add_buddy(jid, "")
210                if entity.outNumbers:
211                        self.cb.error("Not on WhatsApp: %s" %
212                                      ", ".join(entity.outNumbers.keys()))
213                if entity.invalidNumbers:
214                        self.cb.error("Invalid numbers: %s" %
215                                      ", ".join(entity.invalidNumbers.keys()))
216
217                # Disabled since yowsup won't give us the result...
218                if entity.inNumbers and False:
219                        self.toLower(GetStatusIqProtocolEntity(entity.inNumbers.values()))
220                        self.todo.add("statuses")
221                       
222                self.check_connected("contacts")
223
224        def onListGroupsResult(self, groups):
225                """Save group info for later if the user decides to join."""
226                for g in groups.getGroups():
227                        jid = g.getId()
228                        if "@" not in jid:
229                                jid += "@g.us"
230                        group = self.b.groups[jid]
231                       
232                        # Save it. We're going to mix ListGroups elements and
233                        # Group-Subject notifications there, which don't have
234                        # consistent fieldnames for the same bits of info \o/
235                        g.getSubjectTimestamp = g.getSubjectTime
236                        group["topic"] = g
237
238                self.check_connected("groups")
239
240        @ProtocolEntityCallback("notification")
241        def onNotification(self, ent):
242                if isinstance(ent, StatusNotificationProtocolEntity):
243                        return self.onStatusNotification(ent)
244                elif isinstance(ent, SubjectGroupsNotificationProtocolEntity):
245                        return self.onGroupSubjectNotification(ent)
246
247        def onStatusNotification(self, status):
248                print "New status for %s: %s" % (status.getFrom(), status.status)
249                self.bee.buddy_status_msg(status.getFrom(), status.status)
250       
251        def onGroupSubjectNotification(self, sub):
252                print "New /topic for %s: %s" % (sub.getFrom(), sub.getSubject())
253                group = self.b.groups[sub.getFrom()]
254                group["topic"] = sub
255                id = group.get("id", None)
256                if id is not None:
257                        self.cb.chat_topic(id, sub.getSubjectOwner(),
258                                           sub.getSubject(), sub.getSubjectTimestamp())
259
260        @ProtocolEntityCallback("media")
261        def onMedia(self, med):
262                """Your PC better be MPC3 compliant!"""
263                print "YAY MEDIA! %r" % med
264                print med
265
266        #@ProtocolEntityCallback("chatstate")
267        #def onChatstate(self, entity):
268        #       print(entity)
269
270
271class YowsupDaemon(threading.Thread):
272        daemon = True
273        stack = None
274
275        class Terminate(Exception):
276                pass
277
278        def run(self):
279                try:
280                        self.stack.loop(timeout=0.2, discrete=0.2, count=1)
281                except YowsupDaemon.Terminate:
282                        print "Exiting loop!"
283                        pass
284       
285        def StopDaemon(self):
286                # Ugly, but yowsup offers no "run single iteration" version
287                # of their event loop :-(
288                raise YowsupDaemon.Terminate
289
290
291class YowsupIMPlugin(implugin.BitlBeeIMPlugin):
292        NAME = "wa"
293        SETTINGS = {
294                "cc": {
295                        # Country code. Seems to be required for registration only.
296                        "type": "int",
297                },
298                "name": {
299                        "flags": 0x100, # NULL_OK
300                },
301        }
302        AWAY_STATES = ["Away"]
303        ACCOUNT_FLAGS = 14 # HANDLE_DOMAINS + STATUS_MESSAGE + LOCAL_CONTACTS
304        # TODO: HANDLE_DOMAIN in right place (add ... ... nick bug)
305
306        def login(self, account):
307                self.stack = self.build_stack(account)
308                self.daemon = YowsupDaemon(name="yowsup")
309                self.daemon.stack = self.stack
310                self.daemon.start()
311                self.bee.log("Started yowsup thread")
312               
313                self.groups = collections.defaultdict(dict)
314                self.groups_by_id = {}
315
316        def keepalive(self):
317                # Too noisy while debugging
318                # WTF yowsup is SPAWNING A THREAD just for this. Figure out
319                # how to kill that nonsense.
320                pass
321                #self.yow.Ship(PingIqProtocolEntity(to="s.whatsapp.net"))
322
323        def logout(self):
324                self.stack.broadcastEvent(YowLayerEvent(YowNetworkLayer.EVENT_STATE_DISCONNECT))
325                self.stack.execDetached(self.daemon.StopDaemon)
326
327        def buddy_msg(self, to, text, flags):
328                msg = TextMessageProtocolEntity(text, to=to)
329                self.yow.Ship(msg)
330
331        def add_buddy(self, handle, _group):
332                self.yow.Ship(GetSyncIqProtocolEntity(
333                    ["+" + handle.split("@")[0]], mode=GetSyncIqProtocolEntity.MODE_DELTA))
334
335        def remove_buddy(self, handle, _group):
336                self.yow.Ship(UnsubscribePresenceProtocolEntity(handle))
337
338        def set_away(self, state, status):
339                print "Trying to set status to %r, %r" % (state, status)
340                if state:
341                        # Only one option offered so None = available, not None = away.
342                        self.yow.Ship(AvailablePresenceProtocolEntity())
343                else:
344                        self.yow.Ship(UnavailablePresenceProtocolEntity())
345                if status:
346                        self.yow.Ship(SetStatusIqProtocolEntity(status))
347
348        def set_set_name(self, _key, value):
349                self.yow.Ship(PresenceProtocolEntity(name=value))
350
351        def chat_join(self, id, name, _nick, _password, settings):
352                print "New chat created with id: %d" % id
353                group = self.groups[name]
354                group.update({"id": id, "name": name})
355                self.groups_by_id[id] = group
356               
357                gi = group.get("topic", None)
358                if gi:
359                        self.bee.chat_topic(id, gi.getSubjectOwner(),
360                                            gi.getSubject(), gi.getSubjectTimestamp())
361               
362                # WA doesn't really have a concept of joined or not, just
363                # long-term membership. Let's just sync state (we have
364                # basic info but not yet a member list) and ACK the join
365                # once that's done.
366                self.yow.Ship(ParticipantsGroupsIqProtocolEntity(name))
367
368        def chat_join_participants(self, entity):
369                group = self.groups[entity.getFrom()]
370                id = group["id"]
371                for p in entity.getParticipants():
372                        if p != self.account["user"]:
373                                self.bee.chat_add_buddy(id, p)
374
375                # Add the user themselves last to avoid a visible join flood.
376                self.bee.chat_add_buddy(id, self.account["user"])
377                for msg in group.setdefault("queue", []):
378                        self.bee.chat_msg(group["id"], msg.getParticipant(), msg.getBody(), 0, msg.getTimestamp())
379                del group["queue"]
380       
381        def chat_msg(self, id, text, flags):
382                msg = TextMessageProtocolEntity(text, to=self.groups_by_id[id]["name"])
383                self.yow.Ship(msg)
384
385        def chat_leave(self, id):
386                # WA never really let us leave, so just disconnect id and jid.
387                group = self.groups_by_id[id]
388                del self.groups_by_id[id]
389                del group["id"]
390
391        def build_stack(self, account):
392                self.account = account
393                creds = (account["user"].split("@")[0], account["pass"])
394
395                stack = (YowStackBuilder()
396                         .pushDefaultLayers(False)
397                         .push(BitlBeeLayer)
398                         .build())
399                stack.setProp(YowAuthenticationProtocolLayer.PROP_CREDENTIALS, creds)
400                stack.setProp(YowNetworkLayer.PROP_ENDPOINT, YowConstants.ENDPOINTS[0])
401                stack.setProp(YowCoderLayer.PROP_DOMAIN, YowConstants.DOMAIN)
402                stack.setProp(YowCoderLayer.PROP_RESOURCE, env.CURRENT_ENV.getResource())
403                try:
404                        stack.setProp(YowIqProtocolLayer.PROP_PING_INTERVAL, 0)
405                except AttributeError:
406                        # Ping setting only exists since May 2015.
407                        from yowsup.layers.protocol_iq.layer import YowPingThread
408                        YowPingThread.start = lambda x: None
409
410                stack.setProp("org.bitlbee.Bijtje", self)
411
412                stack.broadcastEvent(YowLayerEvent(YowNetworkLayer.EVENT_STATE_CONNECT))
413
414                return stack
415
416
417implugin.RunPlugin(YowsupIMPlugin, debug=True)
Note: See TracBrowser for help on using the repository browser.