1 | #!/usr/bin/python |
---|
2 | |
---|
3 | import logging |
---|
4 | import threading |
---|
5 | import time |
---|
6 | |
---|
7 | import yowsup |
---|
8 | |
---|
9 | from yowsup.layers.auth import YowAuthenticationProtocolLayer |
---|
10 | from yowsup.layers.protocol_acks import YowAckProtocolLayer |
---|
11 | from yowsup.layers.protocol_chatstate import YowChatstateProtocolLayer |
---|
12 | from yowsup.layers.protocol_contacts import YowContactsIqProtocolLayer |
---|
13 | from yowsup.layers.protocol_groups import YowGroupsProtocolLayer |
---|
14 | from yowsup.layers.protocol_ib import YowIbProtocolLayer |
---|
15 | from yowsup.layers.protocol_iq import YowIqProtocolLayer |
---|
16 | from yowsup.layers.protocol_messages import YowMessagesProtocolLayer |
---|
17 | from yowsup.layers.protocol_notifications import YowNotificationsProtocolLayer |
---|
18 | from yowsup.layers.protocol_presence import YowPresenceProtocolLayer |
---|
19 | from yowsup.layers.protocol_privacy import YowPrivacyProtocolLayer |
---|
20 | from yowsup.layers.protocol_profiles import YowProfilesProtocolLayer |
---|
21 | from yowsup.layers.protocol_receipts import YowReceiptProtocolLayer |
---|
22 | from yowsup.layers.network import YowNetworkLayer |
---|
23 | from yowsup.layers.coder import YowCoderLayer |
---|
24 | from yowsup.stacks import YowStack, YowStackBuilder |
---|
25 | from yowsup.common import YowConstants |
---|
26 | from yowsup.layers import YowLayerEvent |
---|
27 | from yowsup.stacks import YowStack, YOWSUP_CORE_LAYERS |
---|
28 | from yowsup import env |
---|
29 | |
---|
30 | from yowsup.layers.interface import YowInterfaceLayer, ProtocolEntityCallback |
---|
31 | from yowsup.layers.protocol_acks.protocolentities import * |
---|
32 | from yowsup.layers.protocol_chatstate.protocolentities import * |
---|
33 | from yowsup.layers.protocol_contacts.protocolentities import * |
---|
34 | from yowsup.layers.protocol_groups.protocolentities import * |
---|
35 | from yowsup.layers.protocol_ib.protocolentities import * |
---|
36 | from yowsup.layers.protocol_iq.protocolentities import * |
---|
37 | from yowsup.layers.protocol_media.mediauploader import MediaUploader |
---|
38 | from yowsup.layers.protocol_media.protocolentities import * |
---|
39 | from yowsup.layers.protocol_messages.protocolentities import * |
---|
40 | from yowsup.layers.protocol_notifications.protocolentities import * |
---|
41 | from yowsup.layers.protocol_presence.protocolentities import * |
---|
42 | from yowsup.layers.protocol_privacy.protocolentities import * |
---|
43 | from yowsup.layers.protocol_profiles.protocolentities import * |
---|
44 | from yowsup.layers.protocol_receipts.protocolentities import * |
---|
45 | from yowsup.layers.axolotl.protocolentities.iq_key_get import GetKeysIqProtocolEntity |
---|
46 | from yowsup.layers.axolotl import YowAxolotlLayer |
---|
47 | from yowsup.common.tools import ModuleTools |
---|
48 | |
---|
49 | import implugin |
---|
50 | |
---|
51 | logger = logging.getLogger("yowsup.layers.network.layer") |
---|
52 | logger.setLevel(logging.DEBUG) |
---|
53 | ch = logging.StreamHandler() |
---|
54 | ch.setLevel(logging.DEBUG) |
---|
55 | logger.addHandler(ch) |
---|
56 | |
---|
57 | class BitlBeeLayer(YowInterfaceLayer): |
---|
58 | |
---|
59 | def __init__(self, *a, **kwa): |
---|
60 | super(BitlBeeLayer, self).__init__(*a, **kwa) |
---|
61 | |
---|
62 | def receive(self, entity): |
---|
63 | print "Received: %r" % entity |
---|
64 | #print entity |
---|
65 | super(BitlBeeLayer, self).receive(entity) |
---|
66 | |
---|
67 | def Ship(self, entity): |
---|
68 | """Send an entity into Yowsup, but through the correct thread.""" |
---|
69 | print "Queueing: %s" % entity.getTag() |
---|
70 | #print entity |
---|
71 | def doit(): |
---|
72 | self.toLower(entity) |
---|
73 | self.getStack().execDetached(doit) |
---|
74 | |
---|
75 | @ProtocolEntityCallback("success") |
---|
76 | def onSuccess(self, entity): |
---|
77 | self.b = self.getStack().getProp("org.bitlbee.Bijtje") |
---|
78 | self.cb = self.b.bee |
---|
79 | self.b.yow = self |
---|
80 | self.cb.connected() |
---|
81 | self.toLower(ListGroupsIqProtocolEntity()) |
---|
82 | try: |
---|
83 | self.toLower(PresenceProtocolEntity(name=self.b.setting("name"))) |
---|
84 | except KeyError: |
---|
85 | pass |
---|
86 | # Should send the contact list now, but BitlBee hasn't given |
---|
87 | # it yet. See set_away() and send_initial_contacts() below. |
---|
88 | |
---|
89 | @ProtocolEntityCallback("failure") |
---|
90 | def onFailure(self, entity): |
---|
91 | self.b = self.getStack().getProp("org.bitlbee.Bijtje") |
---|
92 | self.cb = self.b.bee |
---|
93 | self.cb.error(entity.getReason()) |
---|
94 | self.cb.logout(False) |
---|
95 | |
---|
96 | def onEvent(self, event): |
---|
97 | print "Received event: %s name %s" % (event, event.getName()) |
---|
98 | if event.getName() == "disconnect": |
---|
99 | self.getStack().execDetached(self.daemon.StopDaemon) |
---|
100 | |
---|
101 | @ProtocolEntityCallback("presence") |
---|
102 | def onPresence(self, pres): |
---|
103 | status = 8 # MOBILE |
---|
104 | if pres.getType() != "unavailable": |
---|
105 | status |= 1 # ONLINE |
---|
106 | self.cb.buddy_status(pres.getFrom(), status, None, None) |
---|
107 | try: |
---|
108 | # Last online time becomes idle time which I guess is |
---|
109 | # sane enough? |
---|
110 | self.cb.buddy_times(pres.getFrom(), 0, int(pres.getLast())) |
---|
111 | except (ValueError, TypeError): |
---|
112 | # Could be "error" or, more likely, "deny", or None. |
---|
113 | pass |
---|
114 | |
---|
115 | @ProtocolEntityCallback("message") |
---|
116 | def onMessage(self, msg): |
---|
117 | receipt = OutgoingReceiptProtocolEntity(msg.getId(), msg.getFrom()) |
---|
118 | self.toLower(receipt) |
---|
119 | |
---|
120 | if msg.getParticipant(): |
---|
121 | group = self.b.groups.get(msg.getFrom(), None) |
---|
122 | if not group or "id" not in group: |
---|
123 | self.cb.log("Warning: Activity in room %s" % msg.getFrom()) |
---|
124 | self.b.groups.setdefault(msg.getFrom(), {}).setdefault("queue", []).append(msg) |
---|
125 | return |
---|
126 | self.cb.chat_msg(group["id"], msg.getParticipant(), msg.getBody(), 0, msg.getTimestamp()) |
---|
127 | else: |
---|
128 | self.cb.buddy_msg(msg.getFrom(), msg.getBody(), 0, msg.getTimestamp()) |
---|
129 | |
---|
130 | @ProtocolEntityCallback("receipt") |
---|
131 | def onReceipt(self, entity): |
---|
132 | ack = OutgoingAckProtocolEntity(entity.getId(), entity.getTag(), |
---|
133 | entity.getType(), entity.getFrom()) |
---|
134 | self.toLower(ack) |
---|
135 | |
---|
136 | @ProtocolEntityCallback("iq") |
---|
137 | def onIq(self, entity): |
---|
138 | if isinstance(entity, ResultSyncIqProtocolEntity): |
---|
139 | print "XXX SYNC RESULT RECEIVED!" |
---|
140 | return self.onSyncResult(entity) |
---|
141 | elif isinstance(entity, ListParticipantsResultIqProtocolEntity): |
---|
142 | return self.b.chat_join_participants(entity) |
---|
143 | elif isinstance(entity, ListGroupsResultIqProtocolEntity): |
---|
144 | return self.onListGroupsResult(entity) |
---|
145 | |
---|
146 | def onSyncResult(self, entity): |
---|
147 | # TODO HERE AND ELSEWHERE: Thread idiocy happens when going |
---|
148 | # from here to the IMPlugin. Check how bjsonrpc lets me solve that. |
---|
149 | # ALSO TODO: See why this one doesn't seem to be called for adds later. |
---|
150 | ok = set(jid.lower() for jid in entity.inNumbers.values()) |
---|
151 | for handle in self.b.contacts: |
---|
152 | if handle.lower() in ok: |
---|
153 | self.toLower(SubscribePresenceProtocolEntity(handle)) |
---|
154 | self.cb.add_buddy(handle, "") |
---|
155 | if entity.outNumbers: |
---|
156 | self.cb.error("Not on WhatsApp: %s" % |
---|
157 | ", ".join(entity.outNumbers.keys())) |
---|
158 | if entity.invalidNumbers: |
---|
159 | self.cb.error("Invalid numbers: %s" % |
---|
160 | ", ".join(entity.invalidNumbers.keys())) |
---|
161 | |
---|
162 | def onListGroupsResult(self, groups): |
---|
163 | """Save group info for later if the user decides to join.""" |
---|
164 | for g in groups.getGroups(): |
---|
165 | jid = g.getId() |
---|
166 | if "@" not in jid: |
---|
167 | jid += "@g.us" |
---|
168 | group = self.b.groups.setdefault(jid, {}) |
---|
169 | group["info"] = g |
---|
170 | |
---|
171 | @ProtocolEntityCallback("notification") |
---|
172 | def onNotification(self, ent): |
---|
173 | if isinstance(ent, StatusNotificationProtocolEntity): |
---|
174 | return self.onStatusNotification(ent) |
---|
175 | |
---|
176 | def onStatusNotification(self, status): |
---|
177 | print "New status for %s: %s" % (status.getFrom(), status.status) |
---|
178 | self.bee.buddy_status_msg(status.getFrom(), status.status) |
---|
179 | |
---|
180 | @ProtocolEntityCallback("media") |
---|
181 | def onMedia(self, med): |
---|
182 | """Your PC better be MPC3 compliant!""" |
---|
183 | print "YAY MEDIA! %r" % med |
---|
184 | print med |
---|
185 | |
---|
186 | #@ProtocolEntityCallback("chatstate") |
---|
187 | #def onChatstate(self, entity): |
---|
188 | # print(entity) |
---|
189 | |
---|
190 | |
---|
191 | class YowsupDaemon(threading.Thread): |
---|
192 | daemon = True |
---|
193 | stack = None |
---|
194 | |
---|
195 | class Terminate(Exception): |
---|
196 | pass |
---|
197 | |
---|
198 | def run(self): |
---|
199 | try: |
---|
200 | self.stack.loop(timeout=0.2, discrete=0.2, count=1) |
---|
201 | except YowsupDaemon.Terminate: |
---|
202 | print "Exiting loop!" |
---|
203 | pass |
---|
204 | |
---|
205 | def StopDaemon(self): |
---|
206 | # Ugly, but yowsup offers no "run single iteration" version |
---|
207 | # of their event loop :-( |
---|
208 | raise YowsupDaemon.Terminate |
---|
209 | |
---|
210 | |
---|
211 | class YowsupIMPlugin(implugin.BitlBeeIMPlugin): |
---|
212 | NAME = "wa" |
---|
213 | SETTINGS = { |
---|
214 | "cc": { |
---|
215 | "type": "int", |
---|
216 | }, |
---|
217 | "name": { |
---|
218 | "flags": 0x100, # NULL_OK |
---|
219 | }, |
---|
220 | } |
---|
221 | AWAY_STATES = ["Away"] |
---|
222 | ACCOUNT_FLAGS = 14 # HANDLE_DOMAINS + STATUS_MESSAGE + LOCAL_CONTACTS |
---|
223 | # TODO: LOCAL LIST CAUSES CRASH! |
---|
224 | # TODO: HANDLE_DOMAIN in right place (add ... ... nick bug) |
---|
225 | # TODO? Allow set_away (for status msg) even if AWAY_STATES not set? |
---|
226 | # and/or, see why with the current value set_away state is None. |
---|
227 | |
---|
228 | def login(self, account): |
---|
229 | self.stack = self.build_stack(account) |
---|
230 | self.daemon = YowsupDaemon(name="yowsup") |
---|
231 | self.daemon.stack = self.stack |
---|
232 | self.daemon.start() |
---|
233 | self.bee.log("Started yowsup thread") |
---|
234 | |
---|
235 | self.logging_in = True |
---|
236 | self.contacts = set() |
---|
237 | self.groups = {} |
---|
238 | self.groups_by_id = {} |
---|
239 | |
---|
240 | def keepalive(self): |
---|
241 | # Too noisy while debugging |
---|
242 | pass |
---|
243 | #self.yow.Ship(PingIqProtocolEntity(to="s.whatsapp.net")) |
---|
244 | |
---|
245 | def logout(self): |
---|
246 | self.stack.broadcastEvent(YowLayerEvent(YowNetworkLayer.EVENT_STATE_DISCONNECT)) |
---|
247 | self.stack.execDetached(self.daemon.StopDaemon) |
---|
248 | |
---|
249 | def buddy_msg(self, to, text, flags): |
---|
250 | msg = TextMessageProtocolEntity(text, to=to) |
---|
251 | self.yow.Ship(msg) |
---|
252 | |
---|
253 | def add_buddy(self, handle, _group): |
---|
254 | if self.logging_in: |
---|
255 | # Need to batch up the initial adds. This is a "little" ugly. |
---|
256 | self.contacts.add(handle) |
---|
257 | else: |
---|
258 | self.yow.Ship(GetSyncIqProtocolEntity( |
---|
259 | ["+" + handle.split("@")[0]], mode=GetSyncIqProtocolEntity.MODE_DELTA)) |
---|
260 | self.yow.Ship(SubscribePresenceProtocolEntity(handle)) |
---|
261 | |
---|
262 | def remove_buddy(self, handle, _group): |
---|
263 | self.yow.Ship(UnsubscribePresenceProtocolEntity(handle)) |
---|
264 | |
---|
265 | def set_away(self, state, status): |
---|
266 | # When our first status is set, we've finalised login. |
---|
267 | # Which means sync the full contact list now. |
---|
268 | if self.logging_in: |
---|
269 | self.logging_in = False |
---|
270 | self.send_initial_contacts() |
---|
271 | |
---|
272 | print "Trying to set status to %r, %r" % (state, status) |
---|
273 | if state: |
---|
274 | # Only one option offered so None = available, not None = away. |
---|
275 | self.yow.Ship(AvailablePresenceProtocolEntity()) |
---|
276 | else: |
---|
277 | self.yow.Ship(UnavailablePresenceProtocolEntity()) |
---|
278 | if status: |
---|
279 | self.yow.Ship(SetStatusIqProtocolEntity(status)) |
---|
280 | |
---|
281 | def send_initial_contacts(self): |
---|
282 | if not self.contacts: |
---|
283 | return |
---|
284 | numbers = [("+" + x.split("@")[0]) for x in self.contacts] |
---|
285 | self.yow.Ship(GetSyncIqProtocolEntity(numbers)) |
---|
286 | |
---|
287 | def set_set_name(self, _key, value): |
---|
288 | self.yow.Ship(PresenceProtocolEntity(name=value)) |
---|
289 | |
---|
290 | def chat_join(self, id, name, _nick, _password, settings): |
---|
291 | print "New chat created with id: %d" % id |
---|
292 | self.groups.setdefault(name, {}).update({"id": id, "name": name}) |
---|
293 | group = self.groups[name] |
---|
294 | self.groups_by_id[id] = group |
---|
295 | |
---|
296 | gi = group.get("info", None) |
---|
297 | if gi: |
---|
298 | self.bee.chat_topic(id, gi.getSubjectOwner(), |
---|
299 | gi.getSubject(), gi.getSubjectTime()) |
---|
300 | |
---|
301 | # WA doesn't really have a concept of joined or not, just |
---|
302 | # long-term membership. Let's just get a list of members and |
---|
303 | # pretend we've "joined" then. |
---|
304 | self.yow.Ship(ParticipantsGroupsIqProtocolEntity(name)) |
---|
305 | |
---|
306 | def chat_join_participants(self, entity): |
---|
307 | group = self.groups[entity.getFrom()] |
---|
308 | id = group["id"] |
---|
309 | for p in entity.getParticipants(): |
---|
310 | if p != self.account["user"]: |
---|
311 | self.bee.chat_add_buddy(id, p) |
---|
312 | |
---|
313 | # Add the user themselves last to avoid a visible join flood. |
---|
314 | self.bee.chat_add_buddy(id, self.account["user"]) |
---|
315 | for msg in group.setdefault("queue", []): |
---|
316 | self.bee.chat_msg(group["id"], msg.getParticipant(), msg.getBody(), 0, msg.getTimestamp()) |
---|
317 | del group["queue"] |
---|
318 | |
---|
319 | def chat_msg(self, id, text, flags): |
---|
320 | msg = TextMessageProtocolEntity(text, to=self.groups_by_id[id]["name"]) |
---|
321 | self.yow.Ship(msg) |
---|
322 | |
---|
323 | def chat_leave(self, id): |
---|
324 | # WA never really let us leave, so just disconnect id and jid. |
---|
325 | group = self.groups_by_id[id] |
---|
326 | del self.groups_by_id[id] |
---|
327 | del group["id"] |
---|
328 | |
---|
329 | def build_stack(self, account): |
---|
330 | self.account = account |
---|
331 | creds = (account["user"].split("@")[0], account["pass"]) |
---|
332 | |
---|
333 | stack = (YowStackBuilder() |
---|
334 | .pushDefaultLayers(False) |
---|
335 | .push(BitlBeeLayer) |
---|
336 | .build()) |
---|
337 | stack.setProp(YowAuthenticationProtocolLayer.PROP_CREDENTIALS, creds) |
---|
338 | stack.setProp(YowNetworkLayer.PROP_ENDPOINT, YowConstants.ENDPOINTS[0]) |
---|
339 | stack.setProp(YowCoderLayer.PROP_DOMAIN, YowConstants.DOMAIN) |
---|
340 | stack.setProp(YowCoderLayer.PROP_RESOURCE, env.CURRENT_ENV.getResource()) |
---|
341 | stack.setProp("org.bitlbee.Bijtje", self) |
---|
342 | |
---|
343 | stack.broadcastEvent(YowLayerEvent(YowNetworkLayer.EVENT_STATE_CONNECT)) |
---|
344 | |
---|
345 | return stack |
---|
346 | |
---|
347 | implugin.RunPlugin(YowsupIMPlugin, debug=True) |
---|