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