1 | #!/usr/bin/python |
---|
2 | |
---|
3 | import collections |
---|
4 | import logging |
---|
5 | import threading |
---|
6 | import time |
---|
7 | |
---|
8 | import yowsup |
---|
9 | |
---|
10 | from yowsup.layers.auth import YowAuthenticationProtocolLayer |
---|
11 | from yowsup.layers.protocol_acks import YowAckProtocolLayer |
---|
12 | from yowsup.layers.protocol_chatstate import YowChatstateProtocolLayer |
---|
13 | from yowsup.layers.protocol_contacts import YowContactsIqProtocolLayer |
---|
14 | from yowsup.layers.protocol_groups import YowGroupsProtocolLayer |
---|
15 | from yowsup.layers.protocol_ib import YowIbProtocolLayer |
---|
16 | from yowsup.layers.protocol_iq import YowIqProtocolLayer |
---|
17 | from yowsup.layers.protocol_messages import YowMessagesProtocolLayer |
---|
18 | from yowsup.layers.protocol_notifications import YowNotificationsProtocolLayer |
---|
19 | from yowsup.layers.protocol_presence import YowPresenceProtocolLayer |
---|
20 | from yowsup.layers.protocol_privacy import YowPrivacyProtocolLayer |
---|
21 | from yowsup.layers.protocol_profiles import YowProfilesProtocolLayer |
---|
22 | from yowsup.layers.protocol_receipts import YowReceiptProtocolLayer |
---|
23 | from yowsup.layers.network import YowNetworkLayer |
---|
24 | from yowsup.layers.coder import YowCoderLayer |
---|
25 | from yowsup.stacks import YowStack, YowStackBuilder |
---|
26 | from yowsup.common import YowConstants |
---|
27 | from yowsup.layers import YowLayerEvent |
---|
28 | from yowsup.stacks import YowStack, YOWSUP_CORE_LAYERS |
---|
29 | from yowsup import env |
---|
30 | |
---|
31 | from yowsup.layers.interface import YowInterfaceLayer, ProtocolEntityCallback |
---|
32 | from yowsup.layers.protocol_acks.protocolentities import * |
---|
33 | from yowsup.layers.protocol_chatstate.protocolentities import * |
---|
34 | from yowsup.layers.protocol_contacts.protocolentities import * |
---|
35 | from yowsup.layers.protocol_groups.protocolentities import * |
---|
36 | from yowsup.layers.protocol_ib.protocolentities import * |
---|
37 | from yowsup.layers.protocol_iq.protocolentities import * |
---|
38 | from yowsup.layers.protocol_media.mediauploader import MediaUploader |
---|
39 | from yowsup.layers.protocol_media.protocolentities import * |
---|
40 | from yowsup.layers.protocol_messages.protocolentities import * |
---|
41 | from yowsup.layers.protocol_notifications.protocolentities import * |
---|
42 | from yowsup.layers.protocol_presence.protocolentities import * |
---|
43 | from yowsup.layers.protocol_privacy.protocolentities import * |
---|
44 | from yowsup.layers.protocol_profiles.protocolentities import * |
---|
45 | from yowsup.layers.protocol_receipts.protocolentities import * |
---|
46 | from yowsup.layers.axolotl.protocolentities.iq_key_get import GetKeysIqProtocolEntity |
---|
47 | from yowsup.layers.axolotl import YowAxolotlLayer |
---|
48 | from yowsup.common.tools import ModuleTools |
---|
49 | |
---|
50 | import implugin |
---|
51 | |
---|
52 | logger = logging.getLogger("yowsup.layers.logger.layer") |
---|
53 | logger.setLevel(logging.DEBUG) |
---|
54 | ch = logging.StreamHandler() |
---|
55 | ch.setLevel(logging.DEBUG) |
---|
56 | logger.addHandler(ch) |
---|
57 | |
---|
58 | """ |
---|
59 | TODO/Things I'm unhappy about: |
---|
60 | |
---|
61 | About the fact that WhatsApp is a rubbish protocol that happily rejects |
---|
62 | every second stanza you send it if you're trying to implement a client that |
---|
63 | doesn't keep local state. See how to cope with that.. It'd help if Yowsup |
---|
64 | came with docs on what a normal login sequence looks like instead of just |
---|
65 | throwing some stanzas over a wall but hey. |
---|
66 | |
---|
67 | The randomness of where which bits/state live, in the implugin and the |
---|
68 | yowsup layer. Can't really merge this but at least state should live in |
---|
69 | one place. |
---|
70 | |
---|
71 | Mix of silly CamelCase and proper_style. \o/ |
---|
72 | |
---|
73 | Most important: This is NOT thread-clean. implugin can call into yowsup |
---|
74 | cleanly by throwing closures into a queue, but there's no mechanism in |
---|
75 | the opposite direction, I'll need to cook up some hack to make this |
---|
76 | possible through bjsonrpc's tiny event loop. I think I know how... |
---|
77 | |
---|
78 | And more. But let's first get this into a state where it even works.. |
---|
79 | """ |
---|
80 | |
---|
81 | class 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, ListGroupsResultIqProtocolEntity): |
---|
202 | return self.onListGroupsResult(entity) |
---|
203 | elif type(entity) == IqProtocolEntity: # Pong has no type, sigh. |
---|
204 | self.b.last_pong = time.time() |
---|
205 | if self.todo: |
---|
206 | return self.onLoginPong() |
---|
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 | #self.getStatuses(entity.inNumbers.values()) |
---|
222 | self.check_connected("contacts") |
---|
223 | |
---|
224 | def onSyncResultFail(self): |
---|
225 | # Whatsapp rate-limits sync stanzas, so in case of failure |
---|
226 | # just assume all contacts are valid. |
---|
227 | for jid in self.cb.get_local_contacts(): |
---|
228 | self.toLower(SubscribePresenceProtocolEntity(jid)) |
---|
229 | self.cb.add_buddy(jid, "") |
---|
230 | #self.getStatuses? |
---|
231 | self.check_connected("contacts") |
---|
232 | |
---|
233 | def onListGroupsResult(self, groups): |
---|
234 | """Save group info for later if the user decides to join.""" |
---|
235 | for g in groups.getGroups(): |
---|
236 | jid = g.getId() |
---|
237 | if "@" not in jid: |
---|
238 | jid += "@g.us" |
---|
239 | group = self.b.groups[jid] |
---|
240 | try: |
---|
241 | group["participants"] = g.getParticipants().keys() |
---|
242 | except AttributeError: |
---|
243 | # Depends on a change I made to yowsup that may |
---|
244 | # or may not get merged.. |
---|
245 | group["participants"] = [] |
---|
246 | |
---|
247 | # Save it. We're going to mix ListGroups elements and |
---|
248 | # Group-Subject notifications there, which don't have |
---|
249 | # consistent fieldnames for the same bits of info \o/ |
---|
250 | g.getSubjectTimestamp = g.getSubjectTime |
---|
251 | group["topic"] = g |
---|
252 | |
---|
253 | self.check_connected("groups") |
---|
254 | |
---|
255 | def onLoginPong(self): |
---|
256 | if "contacts" in self.todo: |
---|
257 | # Shitty Whatsapp rejected the sync request, and |
---|
258 | # annoying Yowsup doesn't inform on error responses. |
---|
259 | # So instead, if we received no response to it but |
---|
260 | # did get our ping back, declare failure. |
---|
261 | self.onSyncResultFail() |
---|
262 | if "groups" in self.todo: |
---|
263 | # Well fuck this. Just reject ALL the things! |
---|
264 | # Maybe I don't need this one then. |
---|
265 | self.check_connected("groups") |
---|
266 | self.check_connected("ping") |
---|
267 | |
---|
268 | def getStatuses(self, contacts): |
---|
269 | return # Disabled since yowsup won't give us the result... |
---|
270 | self.toLower(GetStatusIqProtocolEntity(contacts)) |
---|
271 | self.todo.add("statuses") |
---|
272 | |
---|
273 | @ProtocolEntityCallback("notification") |
---|
274 | def onNotification(self, ent): |
---|
275 | if isinstance(ent, StatusNotificationProtocolEntity): |
---|
276 | return self.onStatusNotification(ent) |
---|
277 | elif isinstance(ent, SubjectGroupsNotificationProtocolEntity): |
---|
278 | return self.onGroupSubjectNotification(ent) |
---|
279 | |
---|
280 | def onStatusNotification(self, status): |
---|
281 | print "New status for %s: %s" % (status.getFrom(), status.status) |
---|
282 | self.cb.buddy_status_msg(status.getFrom(), status.status) |
---|
283 | |
---|
284 | def onGroupSubjectNotification(self, sub): |
---|
285 | print "New /topic for %s: %s" % (sub.getFrom(), sub.getSubject()) |
---|
286 | group = self.b.groups[sub.getFrom()] |
---|
287 | group["topic"] = sub |
---|
288 | id = group.get("id", None) |
---|
289 | if id is not None: |
---|
290 | self.cb.chat_topic(id, sub.getSubjectOwner(), |
---|
291 | sub.getSubject(), sub.getSubjectTimestamp()) |
---|
292 | |
---|
293 | @ProtocolEntityCallback("media") |
---|
294 | def onMedia(self, med): |
---|
295 | """Your PC better be MPC3 compliant!""" |
---|
296 | print "YAY MEDIA! %r" % med |
---|
297 | print med |
---|
298 | |
---|
299 | #@ProtocolEntityCallback("chatstate") |
---|
300 | #def onChatstate(self, entity): |
---|
301 | # print(entity) |
---|
302 | |
---|
303 | |
---|
304 | class YowsupDaemon(threading.Thread): |
---|
305 | daemon = True |
---|
306 | stack = None |
---|
307 | |
---|
308 | class Terminate(Exception): |
---|
309 | pass |
---|
310 | |
---|
311 | def run(self): |
---|
312 | try: |
---|
313 | self.stack.loop(timeout=0.2, discrete=0.2, count=1) |
---|
314 | except YowsupDaemon.Terminate: |
---|
315 | print "Exiting loop!" |
---|
316 | pass |
---|
317 | |
---|
318 | def StopDaemon(self): |
---|
319 | # Ugly, but yowsup offers no "run single iteration" version |
---|
320 | # of their event loop :-( |
---|
321 | raise YowsupDaemon.Terminate |
---|
322 | |
---|
323 | |
---|
324 | class YowsupIMPlugin(implugin.BitlBeeIMPlugin): |
---|
325 | NAME = "wa" |
---|
326 | SETTINGS = { |
---|
327 | "cc": { |
---|
328 | # Country code. Seems to be required for registration only. |
---|
329 | "type": "int", |
---|
330 | }, |
---|
331 | "reg_mode": { |
---|
332 | "default": "sms", |
---|
333 | }, |
---|
334 | "name": { |
---|
335 | "flags": 0x100, # NULL_OK |
---|
336 | }, |
---|
337 | # EW! Need to include this setting to trick BitlBee into |
---|
338 | # doing registration instead of refusing to login w/o pwd. |
---|
339 | # TODO: Make this a flag instead of faking oauth. |
---|
340 | "oauth": { |
---|
341 | "default": True, |
---|
342 | }, |
---|
343 | } |
---|
344 | AWAY_STATES = ["Away"] |
---|
345 | ACCOUNT_FLAGS = 14 # HANDLE_DOMAINS + STATUS_MESSAGE + LOCAL_CONTACTS |
---|
346 | # TODO: HANDLE_DOMAIN in right place (add ... ... nick bug) |
---|
347 | PING_INTERVAL = 299 # seconds |
---|
348 | PING_TIMEOUT = 360 # seconds |
---|
349 | |
---|
350 | def login(self, account): |
---|
351 | super(YowsupIMPlugin, self).login(account) |
---|
352 | self.account = account |
---|
353 | self.number = self.account["user"].split("@")[0] |
---|
354 | self.registering = False |
---|
355 | if not self.account["pass"]: |
---|
356 | return self._register() |
---|
357 | |
---|
358 | self.stack = self._build_stack() |
---|
359 | self.daemon = YowsupDaemon(name="yowsup") |
---|
360 | self.daemon.stack = self.stack |
---|
361 | self.daemon.start() |
---|
362 | self.bee.log("Started yowsup thread") |
---|
363 | |
---|
364 | self.groups = collections.defaultdict(dict) |
---|
365 | self.groups_by_id = {} |
---|
366 | |
---|
367 | self.next_ping = None |
---|
368 | self.last_pong = time.time() |
---|
369 | |
---|
370 | def keepalive(self): |
---|
371 | if (time.time() - self.last_pong) > self.PING_TIMEOUT: |
---|
372 | self.bee.error("Ping timeout") |
---|
373 | self.bee.logout(True) |
---|
374 | return |
---|
375 | if self.next_ping and (time.time() < self.next_ping): |
---|
376 | return |
---|
377 | self.yow.Ship(PingIqProtocolEntity(to="s.whatsapp.net")) |
---|
378 | self.next_ping = time.time() + self.PING_INTERVAL |
---|
379 | |
---|
380 | def logout(self): |
---|
381 | self.stack.broadcastEvent(YowLayerEvent(YowNetworkLayer.EVENT_STATE_DISCONNECT)) |
---|
382 | self.stack.execDetached(self.daemon.StopDaemon) |
---|
383 | |
---|
384 | def _register(self): |
---|
385 | self.registering = True |
---|
386 | self.bee.log("New account, starting registration") |
---|
387 | from yowsup.registration import WACodeRequest |
---|
388 | cr = WACodeRequest(str(self.setting("cc")), self.number, |
---|
389 | "000", "000", "000", "000", |
---|
390 | self.setting("reg_mode")) |
---|
391 | res = cr.send() |
---|
392 | res = {k: v for k, v in res.iteritems() if v is not None} |
---|
393 | if res.get("status", "") != "sent": |
---|
394 | self.bee.error("Failed to start registration: %r" % res) |
---|
395 | self.bee.logout(False) |
---|
396 | return |
---|
397 | |
---|
398 | text = ("Registration request sent. You will receive a SMS or " |
---|
399 | "call with a confirmation code. Please respond to this " |
---|
400 | "message with that code.") |
---|
401 | sender = "wa_%s" % self.number |
---|
402 | self.bee.add_buddy(sender, "") |
---|
403 | self.bee.buddy_msg(sender, text, 0, 0) |
---|
404 | |
---|
405 | def _register_confirm(self, code): |
---|
406 | from yowsup.registration import WARegRequest |
---|
407 | code = code.strip().replace("-", "") |
---|
408 | rr = WARegRequest(str(self.setting("cc")), self.number, code) |
---|
409 | res = rr.send() |
---|
410 | res = {k: v for k, v in res.iteritems() if v is not None} |
---|
411 | if (res.get("status", "") != "ok") or (not self.get("pw", "")): |
---|
412 | self.bee.error("Failed to finish registration: %r" % res) |
---|
413 | self.bee.logout(False) |
---|
414 | return |
---|
415 | self.bee.log("Registration finished, attempting login") |
---|
416 | self.bee.set_setstr("password", res["pw"]) |
---|
417 | self.account["pass"] = res["pw"] |
---|
418 | self.login(self.account) |
---|
419 | |
---|
420 | def buddy_msg(self, to, text, flags): |
---|
421 | if self.registering: |
---|
422 | return self._register_confirm(text) |
---|
423 | msg = TextMessageProtocolEntity(text, to=to) |
---|
424 | self.yow.Ship(msg) |
---|
425 | |
---|
426 | def add_buddy(self, handle, _group): |
---|
427 | self.yow.Ship(GetSyncIqProtocolEntity( |
---|
428 | ["+" + handle.split("@")[0]], mode=GetSyncIqProtocolEntity.MODE_DELTA)) |
---|
429 | |
---|
430 | def remove_buddy(self, handle, _group): |
---|
431 | self.yow.Ship(UnsubscribePresenceProtocolEntity(handle)) |
---|
432 | |
---|
433 | def set_away(self, state, status): |
---|
434 | print "Trying to set status to %r, %r" % (state, status) |
---|
435 | if state: |
---|
436 | # Only one option offered so None = available, not None = away. |
---|
437 | self.yow.Ship(AvailablePresenceProtocolEntity()) |
---|
438 | else: |
---|
439 | self.yow.Ship(UnavailablePresenceProtocolEntity()) |
---|
440 | if status: |
---|
441 | self.yow.Ship(SetStatusIqProtocolEntity(status)) |
---|
442 | |
---|
443 | def set_set_name(self, _key, value): |
---|
444 | #self.yow.Ship(PresenceProtocolEntity(name=value)) |
---|
445 | pass |
---|
446 | |
---|
447 | def chat_join(self, id, name, _nick, _password, settings): |
---|
448 | print "New chat created with id: %d" % id |
---|
449 | group = self.groups[name] |
---|
450 | group.update({"id": id, "name": name}) |
---|
451 | self.groups_by_id[id] = group |
---|
452 | |
---|
453 | gi = group.get("topic", None) |
---|
454 | if gi: |
---|
455 | self.bee.chat_topic(id, gi.getSubjectOwner(), |
---|
456 | gi.getSubject(), gi.getSubjectTimestamp()) |
---|
457 | |
---|
458 | # WA doesn't really have a concept of joined or not, just |
---|
459 | # long-term membership. Let's just sync state (we have |
---|
460 | # basic info but not yet a member list) and ACK the join |
---|
461 | # once that's done. |
---|
462 | # Well except that WA/YS killed this one. \o/ |
---|
463 | #self.yow.Ship(ParticipantsGroupsIqProtocolEntity(name)) |
---|
464 | |
---|
465 | # So for now do without a participant list.. |
---|
466 | self.chat_join_participants(group) |
---|
467 | self.chat_send_backlog(group) |
---|
468 | |
---|
469 | def chat_join_participants(self, group): |
---|
470 | for p in group.get("participants", []): |
---|
471 | if p != self.account["user"]: |
---|
472 | self.bee.chat_add_buddy(group["id"], p) |
---|
473 | |
---|
474 | def chat_send_backlog(self, group): |
---|
475 | # Add the user themselves last to avoid a visible join flood. |
---|
476 | self.bee.chat_add_buddy(group["id"], self.account["user"]) |
---|
477 | for msg in group.setdefault("queue", []): |
---|
478 | self.show_message(msg) |
---|
479 | del group["queue"] |
---|
480 | |
---|
481 | def chat_msg(self, id, text, flags): |
---|
482 | msg = TextMessageProtocolEntity(text, to=self.groups_by_id[id]["name"]) |
---|
483 | self.yow.Ship(msg) |
---|
484 | |
---|
485 | def chat_leave(self, id): |
---|
486 | # WA never really let us leave, so just disconnect id and jid. |
---|
487 | group = self.groups_by_id[id] |
---|
488 | del self.groups_by_id[id] |
---|
489 | del group["id"] |
---|
490 | |
---|
491 | def _build_stack(self): |
---|
492 | creds = (self.number, self.account["pass"]) |
---|
493 | |
---|
494 | stack = (YowStackBuilder() |
---|
495 | .pushDefaultLayers(True) |
---|
496 | .push(BitlBeeLayer) |
---|
497 | .build()) |
---|
498 | stack.setProp(YowAuthenticationProtocolLayer.PROP_CREDENTIALS, creds) |
---|
499 | stack.setProp(YowNetworkLayer.PROP_ENDPOINT, YowConstants.ENDPOINTS[0]) |
---|
500 | stack.setProp(YowCoderLayer.PROP_DOMAIN, YowConstants.DOMAIN) |
---|
501 | stack.setProp(YowCoderLayer.PROP_RESOURCE, env.CURRENT_ENV.getResource()) |
---|
502 | try: |
---|
503 | stack.setProp(YowIqProtocolLayer.PROP_PING_INTERVAL, 0) |
---|
504 | except AttributeError: |
---|
505 | # Ping setting only exists since May 2015. |
---|
506 | from yowsup.layers.protocol_iq.layer import YowPingThread |
---|
507 | YowPingThread.start = lambda x: None |
---|
508 | |
---|
509 | stack.setProp("org.bitlbee.Bijtje", self) |
---|
510 | |
---|
511 | stack.broadcastEvent(YowLayerEvent(YowNetworkLayer.EVENT_STATE_CONNECT)) |
---|
512 | |
---|
513 | return stack |
---|
514 | |
---|
515 | |
---|
516 | # Not RPCs from here on. |
---|
517 | def show_message(self, msg): |
---|
518 | if hasattr(msg, "getBody"): |
---|
519 | text = msg.getBody() |
---|
520 | elif hasattr(msg, "getCaption") and hasattr(msg, "getMediaUrl"): |
---|
521 | lines = [] |
---|
522 | if msg.getMediaUrl(): |
---|
523 | lines.append(msg.getMediaUrl()) |
---|
524 | else: |
---|
525 | lines.append("<Broken link>") |
---|
526 | if msg.getCaption(): |
---|
527 | lines.append(msg.getCaption()) |
---|
528 | text = "\n".join(lines) |
---|
529 | else: |
---|
530 | text = "Message of unknown type %r" % type(msg) |
---|
531 | |
---|
532 | if msg.getParticipant(): |
---|
533 | group = self.groups[msg.getFrom()] |
---|
534 | if "id" in group: |
---|
535 | self.bee.chat_add_buddy(group["id"], msg.getParticipant()) |
---|
536 | self.bee.chat_msg(group["id"], msg.getParticipant(), text, 0, msg.getTimestamp()) |
---|
537 | else: |
---|
538 | self.bee.log("Warning: Activity in room %s" % msg.getFrom()) |
---|
539 | self.groups[msg.getFrom()].setdefault("queue", []).append(msg) |
---|
540 | else: |
---|
541 | self.bee.buddy_msg(msg.getFrom(), text, 0, msg.getTimestamp()) |
---|
542 | |
---|
543 | |
---|
544 | implugin.RunPlugin(YowsupIMPlugin, debug=True) |
---|