-
Notifications
You must be signed in to change notification settings - Fork 1
/
yahoo.py
executable file
·1380 lines (1315 loc) · 69.5 KB
/
yahoo.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/python
import os
try:
version = 'git ' + open(os.path.join(os.path.dirname(__file__), '.git/refs/heads/master')).read().strip()
except:
version = 'unknown'
#
# Yahoo! Transport
# June 2004 Copyright (c) Mike Albon
# 2007 Copyright (c) Norman Rasmussen
#
# This program is free software licensed with the GNU Public License Version 2.
# For a full copy of the license please go here http://www.gnu.org/licenses/licenses.html#GPL
import base64, ConfigParser, os, platform, random, re, select, sha, shelve, signal, socket, sys, time, traceback
import xmpp.client
from curphoo import cpformat
from xmpp.protocol import *
from xmpp.browser import *
from xmpp.jep0106 import *
import config, roomlist, xmlconfig, ylib
from adhoc import AdHocCommands
from toolbox import *
VERSTR = 'Yahoo! Transport'
rdsocketlist = {}
wrsocketlist = {}
# key is a tuple of 3 values, (frequency in seconds, function, arguments), value is time of next call
timerlist = {}
NODE_AVATAR='jabber:x:avatar x'
NODE_VCARDUPDATE='vcard-temp:x:update x'
NODE_ADMIN='admin'
NODE_ADMIN_REGISTERED_USERS='registered-users'
NODE_ADMIN_ONLINE_USERS='online-users'
NODE_ROSTER='roster'
def YIDEncode(yid):
return yid.replace('@','%')
def YIDDecode(yid):
return yid.replace('%','@')
roomenccodere = re.compile('([^-]?)([A-Z-])')
def RoomEncode(yid):
return JIDEncode(roomenccodere.sub('\\1-\\2', yid))
roomdeccodere = re.compile('-([a-zA-Z-])')
def RoomDecode(yid):
def decode(m):
return m.group(1).upper()
return roomdeccodere.sub(decode, JIDDecode(yid))
class Transport:
# This class is the main collection of where all the handlers for both the Yahoo and Jabber
#Global structures
userlist = {}
discoresults = {}
online = 1
restart = 0
offlinemsg = ''
def __init__(self,jabber):
self.jabber = jabber
self.chatcat = {0:(0,{})}
self.catlist = {}
def jabberqueue(self,packet):
if not wrsocketlist.has_key(self.jabber.Connection._sock):
wrsocketlist[self.jabber.Connection._sock]=[]
wrsocketlist[self.jabber.Connection._sock].append(packet)
def yahooqueue(self,fromjid,packet):
s = self.userlist[fromjid].sock
if not wrsocketlist.has_key(s):
wrsocketlist[s]=[]
wrsocketlist[s].append(packet)
def findbadconn(self):
#print rdsocketlist
for each in self.userlist:
if config.dumpProtocol: print each, self.userlist[each].sock.fileno()
if self.userlist[each].sock.fileno() == -1:
#print each, self.userlist[each].sock.fileno()
self.y_closed(self.userlist[each])
else:
try:
a,b,c = select.select([self.userlist[each].sock],[self.userlist[each].sock],[self.userlist[each].sock],0)
except:
self.y_closed(self.userlist[each])
badlist = []
for each in wrsocketlist.keys():
try:
if each.fileno() == -1:
badlist.append(each)
except:
badlist.append(each)
for each in badlist:
del wrsocketlist[each]
return
def register_handlers(self):
self.jabber.RegisterHandler('message',self.xmpp_message)
self.jabber.RegisterHandler('presence',self.xmpp_presence)
self.jabber.RegisterHandler('iq',self.xmpp_iq_discoinfo_results,typ = 'result', ns=NS_DISCO_INFO)
self.jabber.RegisterHandler('iq',self.xmpp_iq_version,typ = 'get', ns=NS_VERSION)
self.jabber.RegisterHandler('iq',self.xmpp_iq_register_get, typ = 'get', ns=NS_REGISTER)
self.jabber.RegisterHandler('iq',self.xmpp_iq_register_set, typ = 'set', ns=NS_REGISTER)
self.jabber.RegisterHandler('iq',self.xmpp_iq_avatar, typ = 'get', ns=NS_AVATAR)
self.jabber.RegisterHandler('iq',self.xmpp_iq_gateway_get, typ = 'get', ns=NS_GATEWAY)
self.jabber.RegisterHandler('iq',self.xmpp_iq_gateway_set, typ = 'set', ns=NS_GATEWAY)
self.jabber.RegisterHandler('iq',self.xmpp_iq_vcard, typ = 'get', ns=NS_VCARD)
#self.jabber.RegisterHandler('iq',self.xmpp_iq_notimplemented)
#self.jabber.RegisterHandler('iq',self.xmpp_iq_mucadmin_set,typ = 'set', ns=NS_MUC_ADMIN)
#self.jabber.RegisterHandler('iq',self.xmpp_iq_mucadmin_get,typ = 'get', ns=NS_MUC_ADMIN)
self.disco = Browser()
self.disco.PlugIn(self.jabber)
self.adhoccommands = AdHocCommands(userfile)
self.adhoccommands.PlugIn(self)
self.disco.setDiscoHandler(self.xmpp_base_disco,node='',jid=config.jid)
self.disco.setDiscoHandler(self.xmpp_base_disco,node='',jid=config.confjid)
self.disco.setDiscoHandler(self.xmpp_base_disco,node='',jid='')
def register_ymsg_handlers(self, con):
con.handlers['online']= self.y_online
con.handlers['offline']= self.y_offline
con.handlers['chatonline']= self.y_chatonline
con.handlers['chatoffline']= self.y_chatoffline
con.handlers['login'] = self.y_login
con.handlers['loginfail'] = self.y_loginfail
con.handlers['subscribe'] = self.y_subscribe
con.handlers['message'] = self.y_message
con.handlers['messagefail'] = self.y_messagefail
con.handlers['chatmessage'] = self.y_chatmessage
con.handlers['notify'] = self.y_notify
con.handlers['ping'] = self.y_ping
con.handlers['calendar'] = self.y_calendar
con.handlers['email'] = self.y_email
con.handlers['closed'] = self.y_closed
con.handlers['avatar'] = self.y_avatar
#chatroom handlers
con.handlers['reqroom'] = self.y_chat_login
con.handlers['roominfo'] = self.y_chat_roominfo
con.handlers['chatjoin'] = self.y_chat_join
con.handlers['chatleave'] = self.y_chat_leave
con.handlers['roommessage'] = self.y_roommessage
#con.handlers['roommessagefail'] = self.y_roommessagefail
def xmpp_message(self, con, event):
resource = 'messenger'
fromjid = event.getFrom()
if fromjid == None:
return
fromstripped = fromjid.getStripped().encode('utf8')
if event.getTo().getNode() != None:
if self.userlist.has_key(fromstripped):
yobj=self.userlist[fromstripped]
if event.getTo().getDomain() == config.jid:
yid = YIDDecode(event.getTo().getNode())
yidenc = yid.encode('utf-8')
if event.getBody() == None:
state = '0'
if event.getTag('composing',namespace=NS_CHATSTATES):
state = '1'
self.yahooqueue(fromstripped,yobj.ymsg_send_notify(yidenc,state))
return
resource = 'messenger'
# normal non-groupchat or conference cases
if resource == 'messenger':
if event.getType() == None or event.getType() =='normal':
# normal message case
#print 'got message'
self.yahooqueue(fromstripped,yobj.ymsg_send_message(yidenc,event.getBody().encode('utf-8')))
elif event.getType() == 'chat':
# normal chat case
#print 'got message'
self.yahooqueue(fromstripped,yobj.ymsg_send_message(yidenc,event.getBody().encode('utf-8')))
else:
#print 'type error'
self.jabberqueue(Error(event,ERR_BAD_REQUEST))
elif resource == 'chat':
if event.getType() == None or event.getType() =='normal':
# normal message case
#print 'got message'
self.yahooqueue(fromstripped,yobj.ymsg_send_chatmessage(yidenc,event.getBody().encode('utf-8')))
elif event.getType() == 'chat':
# normal chat case
#print 'got message'
self.yahooqueue(fromstripped,yobj.ymsg_send_chatmessage(yidenc,event.getBody().encode('utf-8')))
else:
#print 'type error'
self.jabberqueue(Error(event,ERR_BAD_REQUEST))
else:
#print 'resource error'
self.jabberqueue(Error(event,ERR_BAD_REQUEST))
elif config.enableChatrooms and event.getTo().getDomain() == config.confjid:
if event.getBody() == None:
return
yid = RoomDecode(event.getTo().getNode())
# Must add resource matching here, ie only connected resource can send to room.
if event.getSubject():
self.jabberqueue(Error(event,ERR_NOT_IMPLEMENTED))
return
if event.getTo().getResource() == None or event.getTo().getResource() == '':
#print yobj.roomlist, yobj.roomnames
if yobj.roomnames.has_key(yid.lower()):
room = yobj.roomnames[yid.lower()].encode('utf-8')
else:
room = None
if config.dumpProtocol: print "groupchat room: ",room
if room != None:
if event.getBody()[0:3] == '/me':
type = 2
body = event.getBody()[4:].encode('utf-8')
else:
type = 1
body = event.getBody().encode('utf-8')
self.yahooqueue(fromstripped,yobj.ymsg_send_roommsg(room,body,type))
to = '%s/%s'%(event.getTo(),yobj.username)
self.jabberqueue(Message(to=event.getFrom(), frm= to, typ='groupchat',body=event.getBody()))
else:
self.jabberqueue(Error(event,ERR_BAD_REQUEST))
else:
self.jabberqueue(Error(event,ERR_BAD_REQUEST))
else:
if config.dumpProtocol: print 'no item error'
self.jabberqueue(Error(event,ERR_REGISTRATION_REQUIRED))
else:
self.jabberqueue(Error(event,ERR_BAD_REQUEST))
def xmpp_presence(self, con, event):
yobj = None
yrost = None
fromjid = event.getFrom()
fromstripped = fromjid.getStripped().encode('utf8')
if userfile.has_key(fromstripped):
if event.getTo().getDomain() == config.jid:
yid = YIDDecode(event.getTo().getNode())
yidenc = yid.encode('utf-8')
if event.getType() == 'subscribed':
if self.userlist.has_key(fromstripped):
yobj=self.userlist[fromstripped]
if event.getTo() == config.jid:
conf = userfile[fromstripped]
conf['subscribed']=True
userfile[fromstripped]=conf
userfile.sync()
#For each new user check if rosterx is adversited then do the rosterx message, else send a truckload of subscribes.
#Part 1, parse the features out of the disco result
features = []
if self.discoresults.has_key(event.getFrom().getStripped().encode('utf8')):
discoresult = self.discoresults[event.getFrom().getStripped().encode('utf8')]
#for i in discoresult.getQueryPayload():
if discoresult.getTag('query').getTag('feature'): features.append(discoresult.getTag('query').getAttr('var'))
#Part 2, make the rosterX message
if NS_ROSTERX in features:
m = Message(to = fromjid, frm = config.jid, subject= 'Yahoo Roster Items', body = 'Items from Yahoo Roster')
p=None
p= m.setTag('x',namespace = NS_ROSTERX)
yrost = yobj.buddylist
if config.dumpProtocol: print yrost
for each in yrost.keys():
for yid in yrost[each]:
p.addChild(name='item', attrs={'jid':'%s@%s'%(YIDEncode(yid),config.jid),'name':yid, 'action':'add'},payload=[Node('group',payload=each)])
self.jabberqueue(m)
if config.dumpProtocol: print m
else:
for each in yobj.buddylist.keys():
for yid in yobj.buddylist[each]:
self.jabberqueue(Presence(frm='%s@%s'%(YIDEncode(yid),config.jid),to = fromjid, typ='subscribe', status='Yahoo messenger contact'))
m = Presence(to = fromjid, frm = config.jid)
self.jabberqueue(m)
self.y_send_online(fromstripped)
self.register_ymsg_handlers(yobj)
else:
self.jabberqueue(Error(event,ERR_NOT_ACCEPTABLE))
elif event.getType() == 'subscribe':
if self.userlist.has_key(fromstripped):
yobj=self.userlist[fromstripped]
if event.getTo() == config.jid:
conf = userfile[fromstripped]
conf['usubscribed']=True
userfile[fromstripped]=conf
userfile.sync()
m = Presence(to = fromjid, frm = config.jid, typ = 'subscribed')
self.jabberqueue(m)
elif yobj.roster.has_key(yidenc):
m = Presence(to = fromjid, frm = event.getTo(), typ = 'subscribed')
self.jabberqueue(m)
else:
#add new user case.
if event.getStatus() != None:
if config.dumpProtocol: print event.getStatus().encode('utf-8')
status = event.getStatus().encode('utf-8')
else:
status = ''
self.yahooqueue(fromstripped,yobj.ymsg_send_addbuddy(yidenc, status))
self.jabberqueue(Presence(frm=event.getTo(), to = event.getFrom(), typ = 'subscribed'))
else:
self.jabberqueue(Error(event,ERR_NOT_ACCEPTABLE))
elif event.getType() == 'unsubscribe':
if self.userlist.has_key(fromstripped):
yobj=self.userlist[fromstripped]
if yobj.roster.has_key(yid):
if event.getStatus() != None:
msg = event.getStatus().encode('utf-8')
else:
msg = ''
self.yahooqueue(fromstripped,yobj.ymsg_send_delbuddy(yidenc, msg))
self.jabberqueue(Presence(frm=event.getTo(), to = event.getFrom(), typ = 'unsubscribed'))
else:
self.jabberqueue(Error(event,ERR_NOT_ACCEPTABLE))
elif event.getType() == 'unsubscribed':
# should do something more elegant here
pass
elif event.getType() == None or event.getType() == 'available' or event.getType() == 'invisible':
# code to add yahoo connection goes here
if yid != '':
return
if self.userlist.has_key(fromstripped):
yobj=self.userlist[fromstripped]
# update status case and additional resource case
# update status case
if yobj.xresources.has_key(event.getFrom().getResource()):
#update resource record
yobj.xresources[event.getFrom().getResource()]=(event.getShow(),event.getPriority(),event.getStatus(),yobj.xresources[event.getFrom().getResource()][3])
if config.dumpProtocol: print "Update resource login: %s" % yobj.xresources
else:
#new resource login
yobj.xresources[event.getFrom().getResource()]=(event.getShow(),event.getPriority(),event.getStatus(),time.time())
if config.dumpProtocol: print "New resource login: %s" % yobj.xresources
#send roster as is
self.y_send_online(fromstripped,event.getFrom().getResource())
#print fromstripped, event.getShow().encode('utf-8'), event.getStatus().encode('utf-8')
self.xmpp_presence_do_update(event,fromstripped)
else:
# open connection case
try:
conf = userfile[fromstripped]
except:
self.jabberqueue(Message(to=fromstripped,subject='Transport Configuration Error',body='The transport has found that your configuration could not be loaded. Please re-register with the transport'))
del userfile[fromstripped]
userfile.sync()
return
yobj = ylib.YahooCon(conf['username'].encode('utf-8'),conf['password'].encode('utf-8'), fromstripped,config.host,config.dumpProtocol)
s = yobj.connect()
if s != None:
rdsocketlist[s]=yobj
self.userlist[fromstripped]=yobj
self.register_ymsg_handlers(yobj)
self.yahooqueue(fromstripped,yobj.ymsg_send_init())
yobj.event = event
if event.getShow() == 'xa' or event.getShow() == 'away':
yobj.away = 'away'
elif event.getShow() == 'dnd':
yobj.away = 'dnd'
elif event.getShow() == 'invisible':
yobj.away = 'invisible'
else:
yobj.away = None
yobj.showstatus = event.getStatus()
#Add line into currently matched resources
yobj.xresources[event.getFrom().getResource()]=(event.getShow(),event.getPriority(),event.getStatus(),time.time())
else:
self.jabberqueue(Error(event,ERR_REMOTE_SERVER_TIMEOUT))
elif event.getType() == 'unavailable':
# Match resources and remove the newly unavailable one
if self.userlist.has_key(fromstripped):
yobj=self.userlist[fromstripped]
#print 'Resource: ', event.getFrom().getResource(), "To Node: ",yid
if yid =='':
self.y_send_offline(fromstripped,event.getFrom().getResource())
if yobj.xresources.has_key(event.getFrom().getResource()):
del yobj.xresources[event.getFrom().getResource()]
self.xmpp_presence_do_update(event,fromstripped)
#Single resource case
#print yobj.xresources
if yobj.xresources == {}:
if config.dumpProtocol: print 'No more resource logins'
if timerlist.has_key(yobj.pripingobj):
del timerlist[yobj.pripingobj]
if timerlist.has_key(yobj.secpingobj):
del timerlist[yobj.secpingobj]
del self.userlist[yobj.fromjid]
if rdsocketlist.has_key(yobj.sock):
del rdsocketlist[yobj.sock]
if wrsocketlist.has_key(yobj.sock):
del wrsocketlist[yobj.sock]
yobj.sock.close()
del yobj
else:
self.jabberqueue(Presence(to=fromjid,frm = config.jid, typ='unavailable'))
elif config.enableChatrooms and event.getTo().getDomain() == config.confjid:
yid = RoomDecode(event.getTo().getNode())
yidenc = yid.encode('utf-8')
#Need to move Chatpings into this section for Yahoo rooms.
if self.userlist.has_key(fromstripped):
yobj=self.userlist[fromstripped]
if yobj.connok:
if config.dumpProtocol: print "chat presence"
yobj.roomnames[yid.lower()] = yid
if event.getType() == 'available' or event.getType() == None or event.getType() == '':
nick = event.getTo().getResource()
yobj.nick = nick
if not yobj.chatlogin:
self.yahooqueue(fromstripped,yobj.ymsg_send_conflogon())
self.yahooqueue(fromstripped,yobj.ymsg_send_chatlogin(None))
yobj.chatresource = event.getFrom().getResource()
#Add secondary ping object code
freq = 5 * 60 #Secondary ping frequency from Zinc
nextrun = int(time.time()) + random.randrange(freq)
yobj.confpingobj=(freq,self.y_sendping,(yobj, yobj.ymsg_send_confping))
timerlist[yobj.confpingobj]=nextrun
yobj.roomtojoin = yidenc
else:
self.yahooqueue(fromstripped,yobj.ymsg_send_chatjoin(yidenc))
elif event.getType() == 'unavailable':
# Must add code to compare from resources here
self.yahooqueue(fromstripped,yobj.ymsg_send_chatleave(yidenc))
self.yahooqueue(fromstripped,yobj.ymsg_send_chatlogout())
self.yahooqueue(fromstripped,yobj.ymsg_send_conflogoff())
if 'confpingobj' in dir(yobj) and timerlist.has_key(yobj.confpingobj):
del timerlist[yobj.confpingobj]
else:
self.jabberqueue(Error(event,ERR_FEATURE_NOT_IMPLEMENTED))
else:
self.jabberqueue(Error(event,ERR_BAD_REQUEST))
else:
self.jabberqueue(Error(event,ERR_BAD_REQUEST))
else:
self.jabberqueue(Error(event,ERR_BAD_REQUEST))
else:
# Need to add auto-unsubscribe on probe events here.
if event.getType() == 'probe':
self.jabberqueue(Presence(to=event.getFrom(), frm=event.getTo(), typ='unsubscribe'))
self.jabberqueue(Presence(to=event.getFrom(), frm=event.getTo(), typ='unsubscribed'))
elif event.getType() == 'unsubscribed':
pass
elif event.getType() == 'unsubscribe':
self.jabberqueue(Presence(frm=event.getTo(),to=event.getFrom(),typ='unsubscribed'))
else:
self.jabberqueue(Error(event,ERR_REGISTRATION_REQUIRED))
def xmpp_presence_do_update(self,event,fromstripped):
age =None
priority = None
resource = None
yobj=self.userlist[fromstripped]
for each in yobj.xresources.keys():
#print each,yobj.xresources
if yobj.xresources[each][1]>priority:
#if priority is higher then take the highest
age = yobj.xresources[each][3]
priority = yobj.xresources[each][1]
resource = each
elif yobj.xresources[each][1]==priority:
#if priority is the same then take the oldest
if yobj.xresources[each][3]<age:
age = yobj.xresources[each][3]
priority = yobj.xresources[each][1]
resource = each
if resource == event.getFrom().getResource():
#only update shown status if resource is current datasource
if event.getShow() == None:
if event.getStatus() != None:
self.yahooqueue(fromstripped,yobj.ymsg_send_away(None,event.getStatus()))
else:
self.yahooqueue(fromstripped,yobj.ymsg_send_back())
yobj.away = None
elif event.getShow() == 'xa' or event.getShow() == 'away':
self.yahooqueue(fromstripped, yobj.ymsg_send_away('away',event.getStatus()))
yobj.away = 'away'
elif event.getShow() == 'dnd':
self.yahooqueue(fromstripped, yobj.ymsg_send_away('dnd',event.getStatus()))
yobj.away= 'dnd'
elif event.getType() == 'invisible':
self.yahooqueue(fromstripped, yobj.ymsg_send_away('invisible',None))
yobj.away= 'invisible'
def xmpp_iq_notimplemented(self, con, event):
self.jabberqueue(Error(event,ERR_FEATURE_NOT_IMPLEMENTED))
# New Disco Handlers
def xmpp_base_disco(self, con, event, type):
fromjid = event.getFrom().getStripped().__str__()
fromstripped = event.getFrom().getStripped().encode('utf8')
to = event.getTo()
node = event.getQuerynode();
if to == config.jid:
if node == None:
if type == 'info':
features = [NS_VERSION,NS_COMMANDS,NS_AVATAR,NS_CHATSTATES]
if config.allowRegister or userfile.has_key(fromjid):
features = [NS_REGISTER] + features
return {
'ids':[
{'category':'gateway','type':'yahoo','name':VERSTR}],
'features':features}
if type == 'items':
list = [
{'node':NODE_ROSTER,'name':config.discoName + ' Roster','jid':config.jid}]
if config.enableChatrooms:
list.append({'jid':config.confjid,'name':config.discoName + ' Chatrooms'})
if fromjid in config.admins:
list.append({'node':NODE_ADMIN,'name':config.discoName + ' Admin','jid':config.jid})
return list
elif node == NODE_ADMIN:
if type == 'info':
return {'ids':[],'features':[]}
if type == 'items':
if not fromjid in config.admins:
return []
return [
{'node':NS_COMMANDS,'name':config.discoName + ' Commands','jid':config.jid},
{'node':NODE_ADMIN_REGISTERED_USERS,'name':config.discoName + ' Registered Users','jid':config.jid},
{'node':NODE_ADMIN_ONLINE_USERS,'name':config.discoName + ' Online Users','jid':config.jid}]
elif node == NODE_ROSTER:
if type == 'info':
return {'ids':[],'features':[]}
if type == 'items':
list = []
if self.userlist.has_key(fromstripped):
for yid in self.userlist[fromstripped].roster.keys():
list.append({'jid':'%s@%s' %(YIDEncode(yid),config.jid),'name':yid})
return list
elif node.startswith(NODE_ADMIN_REGISTERED_USERS):
if type == 'info':
return {'ids':[],'features':[]}
if type == 'items':
if not fromjid in config.admins:
return []
nodeinfo = node.split('/')
list = []
if len(nodeinfo) == 1:
for each in userfile.keys():
#list.append({'node':'/'.join([NODE_ADMIN_REGISTERED_USERS, each]),'name':each,'jid':config.jid})
list.append({'name':each,'jid':each})
#elif len(nodeinfo) == 2:
#fromjid = nodeinfo[1]
#list = [
#{'name':fromjid + ' JID','jid':fromjid}]
return list
elif node.startswith(NODE_ADMIN_ONLINE_USERS):
if type == 'info':
return {'ids':[],'features':[]}
if type == 'items':
if not fromjid in config.admins:
return []
nodeinfo = node.split('/')
list = []
if len(nodeinfo) == 1:
for each in self.userlist.keys():
#list.append({'node':'/'.join([NODE_ADMIN_ONLINE_USERS, each]),'name':each,'jid':config.jid})
list.append({'name':each,'jid':each})
#elif len(nodeinfo) == 2:
#fromjid = nodeinfo[1]
#list = [
#{'name':fromjid + ' JID','jid':fromjid}]
return list
else:
self.jabber.send(Error(event,ERR_ITEM_NOT_FOUND))
raise NodeProcessed
elif to.getDomain() == config.jid:
if self.userlist.has_key(fromstripped):
yid = YIDDecode(event.getTo().getNode())
if type == 'info':
if self.userlist[fromstripped].roster.has_key(yid):
features = [NS_VCARD,NS_VERSION,NS_CHATSTATES]
if userfile[fromstripped.encode('utf-8')].has_key('avatar'):
if userfile[fromstripped.encode('utf-8')]['avatar'].has_key(yid):
features.append(NS_AVATAR)
return {
'ids':[
{'category':'client','type':'yahoo','name':yid}],
'features':features}
else:
self.jabberqueue(Error(event,ERR_NOT_ACCEPTABLE))
if type == 'items':
if self.userlist[fromstripped].roster.has_key(yid):
return []
else:
self.jabberqueue(Error(event,ERR_NOT_ACCEPTABLE))
elif config.enableChatrooms and to == config.confjid:
if node == None:
if type == 'info':
#if we return disco info for our subnodes when the server asks, then we get added to the server's item list
if fromstripped == config.mainServerJID:
raise NodeProcessed
return {
'ids':[
{'category':'conference','type':'yahoo','name':VERSTR + ' Chatrooms'}],
'features':[NS_MUC,NS_VERSION]}
if type == 'items':
if self.chatcat[0][0] < (time.time() - (5*60)):
t = roomlist.getcata(0)
if t != None:
for each in t.keys():
self.chatcat[each] = (time.time(),t[each])
list = []
for each in self.chatcat[0][1]:
list.append({'jid':to,'node':each,'name':self.chatcat[0][1][each]})
return list
else:
if type == 'info':
if self.chatcat[0][1].has_key(node):
return {
'ids':[
{'name':self.chatcat[0][1][node]}],
'features':[]}
if type == 'items':
# Do get room item
if not self.catlist.has_key(node):
t = roomlist.getrooms(node)
if t != None:
self.catlist[node] = (time.time(),t)
else:
if self.catlist[node][0] < (time.time() - 5*60):
t = roomlist.getrooms(node)
if t != None:
self.catlist[node] = (time.time(),t)
# Do get more categories
if not self.chatcat.has_key(node):
t = roomlist.getcata(node)
if t != None:
self.chatcat[node] = (time.time(),t)
else:
if self.chatcat[node][0] < (time.time() - 5*60):
t = roomlist.getcata(node)
if t != None:
self.chatcat[node] = (time.time(),t)
list = []
if len(node.split('/')) == 1:
#add catagories first
if self.chatcat.has_key(node):
for each in self.chatcat[node][1].keys():
if each != 0 and 0 in self.chatcat[node][1].keys():
list.append({'jid':to,'node':each,'name':self.chatcat[node][1][0][each]})
# First level of nodes
for z in self.catlist[node][1].keys():
each = self.catlist[node][1][z]
if each.has_key('type'):
if each['type'] == 'yahoo':
if each.has_key('rooms'):
for c in each['rooms'].keys():
n = RoomEncode('%s:%s' % (each['name'],c))
list.append({'jid':'%s@%s'%(n,config.confjid),'name':'%s:%s'%(each['name'],c)})
return list
elif config.enableChatrooms and to.getDomain() == config.confjid:
if type == 'info':
yid = RoomDecode(event.getTo().getNode())
lobby,room = yid.split(':')
result = {
'ids':[
{'category':'conference','type':'yahoo','name':yid}],
'features':[NS_MUC]}
for node in self.catlist.keys():
if self.catlist[node][1].has_key(lobby):
t = self.catlist[node][1][lobby]
if t['rooms'].has_key(room):
data = {'muc#roominfo_description':t['name'],'muc#roominfo_subject':t['topic'],'muc#roominfo_occupants':t['rooms'][room]['users']}
info = DataForm(typ = 'result', data= data)
field = info.setField('FORM_TYPE')
field.setType('hidden')
field.setValue('http://jabber.org/protocol/muc#roominfo')
result['xdata'] = info
return result
if type == 'items':
return []
def xmpp_iq_discoinfo_results(self, con, event):
self.discoresults[event.getFrom().getStripped().encode('utf8')]=event
raise NodeProcessed
def xmpp_iq_register_get(self, con, event):
if event.getTo() == config.jid:
username = []
password = []
fromjid = event.getFrom().getStripped().encode('utf8')
queryPayload = [Node('instructions', payload = 'Please provide your Yahoo! username and password')]
if userfile.has_key(fromjid):
try:
username = userfile[fromjid]['username']
password = userfile[fromjid]['password']
except:
pass
queryPayload += [
Node('username',payload=username),
Node('password',payload=password),
Node('registered')]
else:
if not config.allowRegister:
return
queryPayload += [
Node('username'),
Node('password')]
m = event.buildReply('result')
m.setQueryNS(NS_REGISTER)
m.setQueryPayload(queryPayload)
self.jabberqueue(m)
#Add disco#info check to client requesting for rosterx support
i= Iq(to=event.getFrom(), frm=config.jid, typ='get',queryNS=NS_DISCO_INFO)
self.jabberqueue(i)
else:
self.jabberqueue(Error(event,ERR_BAD_REQUEST))
raise NodeProcessed
def xmpp_iq_register_set(self, con, event):
if event.getTo() == config.jid:
remove = False
username = False
password = False
fromjid = event.getFrom().getStripped().encode('utf8')
#for each in event.getQueryPayload():
# if each.getName() == 'username':
# username = each.getData()
# print "Have username ", username
# elif each.getName() == 'password':
# password = each.getData()
# print "Have password ", password
# elif each.getName() == 'remove':
# remove = True
query = event.getTag('query')
if query.getTag('username'):
username = query.getTagData('username')
if query.getTag('password'):
password = query.getTagData('password')
if query.getTag('remove'):
remove = True
if not remove and username and password:
if userfile.has_key(fromjid):
conf = userfile[fromjid]
else:
if not config.allowRegister:
return
conf = {}
conf['username']=username
conf['password']=password
userfile[fromjid]=conf
userfile.sync()
m=event.buildReply('result')
self.jabberqueue(m)
if self.userlist.has_key(fromjid):
self.y_closed(self.userlist[fromjid])
if not self.userlist.has_key(fromjid):
yobj = ylib.YahooCon(username.encode('utf-8'),password.encode('utf-8'), fromjid,config.host,config.dumpProtocol)
self.userlist[fromjid]=yobj
if config.dumpProtocol: print "try connect"
s = yobj.connect()
if s != None:
if config.dumpProtocol: print "conect made"
rdsocketlist[s]=yobj
self.yahooqueue(fromjid,yobj.ymsg_send_challenge())
yobj.handlers['login']=self.y_reg_login
yobj.handlers['loginfail']=self.y_loginfail
yobj.handlers['closed']=self.y_loginfail
yobj.handlers['ping']=self.y_ping
yobj.event = event
yobj.showstatus = None
yobj.away = None
elif remove and not username and not password:
if self.userlist.has_key(fromjid):
self.y_closed(self.userlist[fromjid])
if userfile.has_key(fromjid):
del userfile[fromjid]
userfile.sync()
m = event.buildReply('result')
self.jabberqueue(m)
m = Presence(to = event.getFrom(), frm = config.jid, typ = 'unsubscribe')
self.jabberqueue(m)
m = Presence(to = event.getFrom(), frm = config.jid, typ = 'unsubscribed')
self.jabberqueue(m)
else:
self.jabberqueue(Error(event,ERR_BAD_REQUEST))
else:
self.jabberqueue(Error(event,ERR_BAD_REQUEST))
else:
self.jabberqueue(Error(event,ERR_BAD_REQUEST))
raise NodeProcessed
def xmpp_iq_avatar(self, con, event):
fromjid = event.getFrom()
fromstripped = fromjid.getStripped().encode('utf-8')
if userfile.has_key(fromstripped):
if event.getTo().getDomain() == config.jid:
yid = YIDDecode(event.getTo().getNode())
elif config.enableChatrooms and event.getTo().getDomain() == config.confjid:
yid = YIDDecode(event.getTo().getResource())
else:
self.jabberqueue(Error(event,ERR_ITEM_NOT_FOUND))
raise NodeProcessed
if userfile[fromstripped].has_key('avatar'):
if userfile[fromstripped]['avatar'].has_key(yid):
m = Iq(to = event.getFrom(), frm=event.getTo(), typ = 'result', queryNS=NS_AVATAR, payload=[Node('data',attrs={'mimetype':'image/png'},payload=base64.encodestring(userfile[fromstripped]['avatar'][yid][1]))])
m.setID(event.getID())
self.jabberqueue(m)
else:
self.jabberqueue(Error(event,ERR_ITEM_NOT_FOUND))
else:
self.jabberqueue(Error(event,ERR_ITEM_NOT_FOUND))
else:
self.jabberqueue(Error(event,ERR_ITEM_NOT_FOUND))
raise NodeProcessed
def xmpp_iq_gateway_get(self, con, event):
if event.getTo() == config.jid:
m = Iq(to = event.getFrom(), frm=event.getTo(), typ = 'result', queryNS=NS_GATEWAY, payload=[
Node('desc',payload='Please enter the Yahoo! ID of the person you would like to contact.'),
Node('prompt',payload='Yahoo! ID')])
m.setID(event.getID())
self.jabberqueue(m)
raise NodeProcessed
def xmpp_iq_gateway_set(self, con, event):
if event.getTo() == config.jid:
query = event.getTag('query')
jid = query.getTagData('prompt')
m = Iq(to = event.getFrom(), frm=event.getTo(), typ = 'result', queryNS=NS_GATEWAY, payload=[
Node('jid',payload='%s@%s'%(YIDEncode(jid),config.jid)), # JEP-0100 says use jid,
Node('prompt',payload='%s@%s'%(YIDEncode(jid),config.jid))]) # but Psi uses prompt
m.setID(event.getID())
self.jabberqueue(m)
raise NodeProcessed
def xmpp_iq_vcard(self, con, event):
fromjid = event.getFrom()
fromstripped = fromjid.getStripped().encode('utf-8')
if userfile.has_key(fromstripped):
if event.getTo().getDomain() == config.jid:
yid = YIDDecode(event.getTo().getNode())
elif config.enableChatrooms and event.getTo().getDomain() == config.confjid:
yid = YIDDecode(event.getTo().getResource())
else:
self.jabberqueue(Error(event,ERR_ITEM_NOT_FOUND))
raise NodeProcessed
m = Iq(to = event.getFrom(), frm=event.getTo(), typ = 'result')
m.setID(event.getID())
v = m.addChild(name='vCard', namespace=NS_VCARD)
v.setTagData(tag='NICKNAME', val=yid)
if userfile[fromstripped].has_key('avatar') and \
userfile[fromstripped]['avatar'].has_key(yid):
p = v.addChild(name='PHOTO')
p.setTagData(tag='TYPE', val='image/png')
p.setTagData(tag='BINVAL', val=base64.encodestring(userfile[fromstripped]['avatar'][yid][1]))
self.jabberqueue(m)
else:
self.jabberqueue(Error(event,ERR_ITEM_NOT_FOUND))
raise NodeProcessed
def y_avatar(self,yobj,yid,avatar):
hex = None
conf = userfile[yobj.fromjid]
if not conf.has_key('avatar'):
conf['avatar']={}
if avatar != None:
a = sha.new(avatar)
hex = a.hexdigest()
conf['avatar'][yid]=(hex,avatar)
elif conf['avatar'].has_key(yid):
hex = ''
del conf['avatar'][yid]
userfile[yobj.fromjid] = conf
userfile.sync()
if hex != None:
if config.dumpProtocol: print "avatar:",hex
self.y_online(yobj,yid,forceavatar=1)
def y_closed(self, yobj):
if self.userlist.has_key(yobj.fromjid):
if not yobj.connok:
if config.dumpProtocol: print "got closed, on not connok"
if yobj.moreservers():
if rdsocketlist.has_key(yobj.sock):
del rdsocketlist[yobj.sock]
if wrsocketlist.has_key(yobj.sock):
del wrsocketlist[yobj.sock]
yobj.sock.close()
s= yobj.connect()
if s != None:
rdsocketlist[s]=yobj
self.userlist[yobj.fromjid]=yobj
self.yahooqueue(yobj.fromjid,yobj.ymsg_send_challenge())
return # this method terminates here - all change please
else:
self.y_loginfail(yobj)
self.y_send_offline(yobj.fromjid)
self.jabberqueue(Error(Presence(frm = yobj.fromjid, to = config.jid),ERR_REMOTE_SERVER_TIMEOUT))
if timerlist.has_key(yobj.pripingobj):
del timerlist[yobj.pripingobj]
if timerlist.has_key(yobj.secpingobj):
del timerlist[yobj.secpingobj]
if 'confpingobj' in dir(yobj) and timerlist.has_key(yobj.confpingobj):
del timerlist[yobj.confpingobj]
if self.userlist.has_key(yobj.fromjid):
del self.userlist[yobj.fromjid]
if rdsocketlist.has_key(yobj.sock):
del rdsocketlist[yobj.sock]
if wrsocketlist.has_key(yobj.sock):
del wrsocketlist[yobj.sock]
if yobj.sock:
yobj.sock.close()
del yobj
def y_sendping(self, yobj, pingfunc):
data = pingfunc()
if data:
if config.dumpProtocol: print "sending ping"
self.yahooqueue(yobj.fromjid, data)
else:
if config.dumpProtocol: print "not sending ping"
def y_ping(self, yobj):
if config.dumpProtocol: print "got ping!"
if yobj.pripingfreq:
freq = yobj.pripingfreq*60
nextrun = int(time.time()) + random.randrange(freq)
yobj.pripingobj=(freq,self.y_sendping,(yobj, yobj.ymsg_send_priping))
timerlist[yobj.pripingobj] = nextrun
if yobj.secpingfreq:
freq = yobj.secpingfreq*60
nextrun = int(time.time()) + random.randrange(freq)
yobj.secpingobj=(freq,self.y_sendping,(yobj, yobj.ymsg_send_secping))
timerlist[yobj.secpingobj] = nextrun
for each in yobj.xresources.keys():
mjid = JID(yobj.fromjid)
mjid.setResource(each)
self.jabberqueue(Presence(to = mjid, frm = config.jid))
yobj.handlers['loginfail']= self.y_loginfail
yobj.handlers['login']= self.y_closed
yobj.connok = True
self.yahooqueue(yobj.fromjid,yobj.ymsg_send_online(yobj.away, yobj.showstatus))
if userfile[yobj.fromjid]['username'] != yobj.username:
conf = userfile[yobj.fromjid]
conf['username']=yobj.username
userfile[yobj.fromjid]=conf
self.jabberqueue(Message(to=yobj.fromjid,frm=config.jid,subject='Yahoo! login name',body='Your Yahoo! username was specified incorrectly in the configuration. This may be because of an upgrade from a previous version, the configuration has been updated'))
def y_login(self,yobj):
if config.dumpProtocol: print "got login"
def y_loginfail(self,yobj, reason = None):
if config.dumpProtocol: print "got login fail: ",reason
if config.dumpProtocol: print yobj.conncount, yobj.moreservers()
if yobj.moreservers() and reason == None:
if rdsocketlist.has_key(yobj.sock):
del rdsocketlist[yobj.sock]
if wrsocketlist.has_key(yobj.sock):
del wrsocketlist[yobj.sock]
yobj.sock.close()
s = yobj.connect()
if s != None:
rdsocketlist[s]=yobj
self.userlist[yobj.fromjid]=yobj
self.yahooqueue(yobj.fromjid,yobj.ymsg_send_challenge())
return # this method terminates here - all change please
else:
# This is the no more servers or definite error case.
if reason == 'badpassword':
self.jabberqueue(Message(to=yobj.event.getFrom(),frm=config.jid,subject='Login Failure',body='Login Failed to Yahoo! service. The Yahoo! Service returned a bad password error Please use the registration function to check your password is correct.'))
elif reason == 'locked':
self.jabberqueue(Message(to=yobj.event.getFrom(),frm=config.jid,subject='Login Failure',body='Login Failed to Yahoo! service. Your account has been locked by Yahoo!.'))
elif reason == 'imageverify':
self.jabberqueue(Message(to=yobj.event.getFrom(),frm=config.jid,subject='Login Failure',body='Login Failed to Yahoo! service. Your account needs to be verified, unfortuantely this can not be done using the transport at this time.'))
elif reason == 'badusername':
if userfile[yobj.fromjid]['username'] == yobj.username:
# If the userdetails has a blah@foo style username try taking the domain off first, then connect again
if userfile[yobj.fromjid]['username'].count('@'):
yobj.username = yobj.username.split('@')[0]
if yobj.moreservers():
if rdsocketlist.has_key(yobj.sock):
del rdsocketlist[yobj.sock]
if wrsocketlist.has_key(yobj.sock):
del wrsocketlist[yobj.sock]
yobj.sock.close()
s = yobj.connect()
if s != None:
rdsocketlist[s]=yobj
self.userlist[yobj.fromjid]=yobj
self.yahooqueue(yobj.fromjid,yobj.ymsg_send_challenge())
self.jabberqueue(Message(to=yobj.event.getFrom(),frm=config.jid,subject='Login Failure',body='Login Failed to Yahoo! service. Please check registration details by re-registering in your client. You have an @ in your username, login will be attempted without the domain component.'))
return
else:
self.jabberqueue(Message(to=yobj.event.getFrom(),frm=config.jid,subject='Login Failure',body='Login Failed to Yahoo! service. Your username is not recognised by the Yahoo! service.'))
else:
self.jabberqueue(Message(to=yobj.event.getFrom(),frm=config.jid,subject='Login Failure',body='Login Failed to Yahoo! service. Your username is not recognised by the Yahoo! service'))
else:
self.jabberqueue(Message(to=yobj.event.getFrom(),frm=config.jid,subject='Login Failure',body='Login Failed to Yahoo! service. Please check registration details by re-registering in your client'))
self.jabberqueue(Error(yobj.event,ERR_NOT_AUTHORIZED))
del self.userlist[yobj.fromjid]
if rdsocketlist.has_key(yobj.sock):
del rdsocketlist[yobj.sock]
if wrsocketlist.has_key(yobj.sock):
del wrsocketlist[yobj.sock]
yobj.sock.close()
del yobj
def y_online(self,yobj,yid,forceavatar=0):
hex = None