This repository has been archived by the owner on Sep 13, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 12
/
Copy pathkernel.py
1980 lines (1809 loc) · 79.9 KB
/
kernel.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
# -*- coding: utf-8 -*-
# --------------------------------------------------------------------------- #
# #
# iSida Jabber Bot #
# Copyright (C) diSabler <[email protected]> #
# #
# This program is free software: you can redistribute it and/or modify #
# it under the terms of the GNU General Public License as published by #
# the Free Software Foundation, either version 3 of the License, or #
# (at your option) any later version. #
# #
# This program is distributed in the hope that it will be useful, #
# but WITHOUT ANY WARRANTY; without even the implied warranty of #
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the #
# GNU General Public License for more details. #
# #
# You should have received a copy of the GNU General Public License #
# along with this program. If not, see <http://www.gnu.org/licenses/>. #
# #
# --------------------------------------------------------------------------- #
from __future__ import with_statement
import calendar
import crontab
import datetime
import gc
import json
import hashlib
import htmlentitydefs
import httplib
import logging
import operator
import os
import math
import random
import re
import socket
import string
import sys
import time
import urllib
import urllib2
import chardet
import xmpp
global execute, prefix, comms, hashlib, trace
def sqlite3_split_part(txt, spltr, cnt):
if txt: return (txt.split(spltr) + [''] * (cnt-1))[cnt-1]
else: return txt
sqlite3_row_number_last_x = 0
def sqlite3_row_number():
global sqlite3_row_number_last_x
sqlite3_row_number_last_x += 1
return sqlite3_row_number_last_x
def cur_execute_sqlite3(*params):
conn = sqlite3.connect(sqlite_base)
if 'split_part' in list(params)[0]: conn.create_function('split_part', 3, sqlite3_split_part)
if 'row_number' in list(params)[0]:
global sqlite3_row_number_last_x
sqlite3_row_number_last_x = 0
conn.create_function('row_number', 0, sqlite3_row_number)
cur = conn.cursor()
par = True
try:
params = list(params)
params[0] = params[0].replace('%s','?').replace(' ilike ',' like ').replace(' update ',' `update` ').replace(' repeat ',' `repeat` ').replace(' option ',' `option` ').replace(' count ',' `count` ').replace(' match ',' `match` ')
params = tuple(params)
cur.execute(*params)
prm = params[0].split()[0].lower()
if prm in ['update','insert','delete','create','drop','alter']: conn.commit()
except Exception, par:
par = None
conn.rollback()
if halt_on_exception: raise
conn.commit()
conn.close()
return par
def cur_execute_mysql(*params):
conn = mysqldb.connect(database=base_name, user=base_user, host=base_host, password=base_pass, port=base_port)
cur = conn.cursor()
par = True
try:
params = list(params)
params[0] = params[0].replace(' ilike ',' like ').replace(' update ',' `update` ').replace(' repeat ',' `repeat` ').replace(' option ',' `option` ').replace(' count ',' `count` ').replace(' match ',' `match` ').replace('split_part(','substring_index(')
params = tuple(params)
cur.execute(*params)
prm = params[0].split()[0].lower()
if prm in ['update','insert','delete','create','drop','alter']: conn.commit()
except Exception, par:
par = None
conn.rollback()
if halt_on_exception: raise
conn.commit()
conn.close()
return par
def cur_execute(*params):
if base_type == 'sqlite3': return cur_execute_sqlite3(*params)
elif base_type == 'mysql': return cur_execute_mysql(*params)
global conn
cur = conn.cursor()
if base_type == 'pgsql': psycopg2.extensions.register_type(psycopg2.extensions.UNICODE, cur)
par = True
try:
cur.execute(*params)
prm = params[0].split()[0].lower()
if prm in ['update','insert','delete','create','drop','alter']: conn.commit()
except Exception, par:
if database_debug:
try: par = str(par)
except: par = unicode(par)
pprint(par,'red')
else: par = None
conn.rollback()
if halt_on_exception: raise
cur.close()
return par
def cur_execute_fetchone_sqlite3(*params):
conn = sqlite3.connect(sqlite_base)
if 'split_part' in list(params)[0]: conn.create_function('split_part', 3, sqlite3_split_part)
if 'row_number' in list(params)[0]:
global sqlite3_row_number_last_x
sqlite3_row_number_last_x = 0
conn.create_function('row_number', 0, sqlite3_row_number)
try: cur = conn.cursor()
except: return None
par = None
try:
params = list(params)
params[0] = params[0].replace('%s','?').replace(' ilike ',' like ').replace(' update ',' `update` ').replace(' repeat ',' `repeat` ').replace(' option ',' `option` ').replace(' count ',' `count` ').replace(' match ',' `match` ')
params = tuple(params)
cur.execute(*params)
try: par = cur.fetchone()
except Exception, par:
par = None
if halt_on_exception: raise
except Exception, par:
par = None
conn.rollback()
conn.close()
return par
def cur_execute_fetchone_mysql(*params):
conn = mysqldb.connect(database=base_name, user=base_user, host=base_host, password=base_pass, port=base_port)
try: cur = conn.cursor()
except: return None
par = None
try:
params = list(params)
params[0] = params[0].replace(' ilike ',' like ').replace(' update ',' `update` ').replace(' repeat ',' `repeat` ').replace(' option ',' `option` ').replace(' count ',' `count` ').replace(' match ',' `match` ').replace('split_part(','substring_index(')
params = tuple(params)
cur.execute(*params)
try: par = cur.fetchone()
except Exception, par:
par = None
if halt_on_exception: raise
except Exception, par:
par = None
conn.rollback()
conn.close()
return par
def cur_execute_fetchone(*params):
if base_type == 'sqlite3': return cur_execute_fetchone_sqlite3(*params)
elif base_type == 'mysql': return cur_execute_fetchone_mysql(*params)
global conn
try: cur = conn.cursor()
except: return None
if base_type == 'pgsql': psycopg2.extensions.register_type(psycopg2.extensions.UNICODE, cur)
par = None
try:
cur.execute(*params)
try: par = cur.fetchone()
except Exception, par:
if database_debug:
try: par = str(par)
except: par = unicode(par)
else: par = None
if halt_on_exception: raise
except Exception, par:
if database_debug:
try: par = str(par)
except: par = unicode(par)
pprint(par,'red')
if halt_on_exception: raise
else: par = None
conn.rollback()
cur.close()
return par
def cur_execute_fetchall_sqlite3(*params):
conn = sqlite3.connect(sqlite_base)
if 'split_part' in list(params)[0]: conn.create_function('split_part', 3, sqlite3_split_part)
if 'row_number' in list(params)[0]:
global sqlite3_row_number_last_x
sqlite3_row_number_last_x = 0
conn.create_function('row_number', 0, sqlite3_row_number)
try: cur = conn.cursor()
except: return None
par = None
try:
params = list(params)
params[0] = params[0].replace('%s','?').replace(' ilike ',' like ').replace(' update ',' `update` ').replace(' repeat ',' `repeat` ').replace(' option ',' `option` ').replace(' count ',' `count` ').replace(' match ',' `match` ')
params = tuple(params)
cur.execute(*params)
try: par = cur.fetchall()
except Exception, par:
par = None
if halt_on_exception: raise
except Exception, par:
par = None
conn.rollback()
if halt_on_exception: raise
conn.close()
return par
def cur_execute_fetchall_mysql(*params):
conn = mysqldb.connect(database=base_name, user=base_user, host=base_host, password=base_pass, port=base_port)
try: cur = conn.cursor()
except: return None
par = None
try:
params = list(params)
params[0] = params[0].replace(' ilike ',' like ').replace(' update ',' `update` ').replace(' repeat ',' `repeat` ').replace(' option ',' `option` ').replace(' count ',' `count` ').replace(' match ',' `match` ').replace('split_part(','substring_index(')
params = tuple(params)
cur.execute(*params)
try: par = cur.fetchall()
except Exception, par:
par = None
if halt_on_exception: raise
except Exception, par:
par = None
conn.rollback()
if halt_on_exception: raise
conn.close()
return par
def cur_execute_fetchall(*params):
if base_type == 'sqlite3': return cur_execute_fetchall_sqlite3(*params)
elif base_type == 'mysql': return cur_execute_fetchall_mysql(*params)
global conn
try: cur = conn.cursor()
except: return None
if base_type == 'pgsql': psycopg2.extensions.register_type(psycopg2.extensions.UNICODE, cur)
par = None
try:
cur.execute(*params)
try: par = cur.fetchall()
except Exception, par:
if database_debug:
try: par = str(par)
except: par = unicode(par)
else: par = None
if halt_on_exception: raise
except Exception, par:
if database_debug:
try: par = str(par)
except: par = unicode(par)
pprint(par,'red')
else: par = None
conn.rollback()
if halt_on_exception: raise
cur.close()
return par
def get_color(c):
color = os.environ.has_key('TERM')
colors = {'clear':'[0m','blue':'[34m','red':'[31m','magenta':'[35m','green':'[32m','cyan':'[36m','brown':'[33m','light_gray':'[37m','black':'[30m','bright_blue':'[34;1m','bright_red':'[31;1m','purple':'[35;1m','bright_green':'[32;1m','bright_cyan':'[36;1m','yellow':'[33;1m','dark_gray':'[30;1m','white':'[37;1m'}
return ['','\x1b%s' % colors[c]][color]
def get_color_win32(c):
colors = {'clear':7,'blue':1,'red':4,'magenta':5,'green':2,'cyan':3,'brown':6,'light_gray':7,'black':0,'bright_blue':9,'bright_red':12,'purple':13,'bright_green':10,'bright_cyan':11,'yellow':14,'dark_gray':8,'white':15}
return colors[c]
def thr(func,param,name):
global th_cnt, thread_error_count, sema
th_cnt += 1
try:
if thread_type:
with sema:
tmp_th = KThread(group=None,target=log_execute,name='%s_%s' % (th_cnt,name),args=(func,param))
tmp_th.start()
else: thread.start_new_thread(log_execute,(func,param))
except SystemExit: pass
except Exception, SM:
try: SM = str(SM)
except: SM = unicode(SM)
if 'thread' in SM.lower(): thread_error_count += 1
else: logging.exception(' [%s] %s' % (timeadd(tuple(time.localtime())),unicode(func)))
if thread_type:
try: tmp_th.kill()
except: pass
if halt_on_exception: raise
def log_execute(proc, params):
try: proc(*params)
except SystemExit: pass
except: logging.exception(' [%s] %s' % (timeadd(tuple(time.localtime())),unicode(proc)))
def sender(item):
global message_out, presence_out, iq_out, unknown_out, last_stanza, messages_log
last_stanza = unicode(item)
if last_stanza[:2] == '<m':
message_out += 1
id = get_id()
item.setAttr('id',id)
messages_log[id] = item
elif last_stanza[:2] == '<p': presence_out += 1
elif last_stanza[:2] == '<i': iq_out += 1
else: unknown_out += 1
if time_nolimit: time.sleep(time_nolimit)
try: cl.send(item)
except Exception,SM:
pprint(last_stanza,'red')
pprint(SM,'red')
if halt_on_exception: raise
def readfile(filename):
fp = file(filename)
data = fp.read()
fp.close()
return data
def writefile(filename, data):
fp = file(filename, 'w')
fp.write(data)
fp.close()
def getFile(filename,default):
if os.path.isfile(filename):
try: filebody = eval(readfile(filename))
except:
if os.path.isfile(back_file % filename.split('/')[-1]):
while True:
try:
filebody = eval(readfile(back_file % filename.split('/')[-1]))
break
except: pass
else:
filebody = default
writefile(filename,str(default))
else:
filebody = default
writefile(filename,str(default))
writefile(back_file % filename.split('/')[-1],str(filebody))
return filebody
def get_config(room,item):
setup = cur_execute_fetchone('select value from config_conf where room=%s and option = %s',(room,item))
try:
if setup[0] in ['True','true']: return True
elif setup[0] in ['False','false','None','none']: return False
else: return setup[0]
except:
try: return config_prefs[item][3]
except: return None
def get_config_int(room,item):
setup = cur_execute_fetchone('select value from config_conf where room=%s and option = %s',(room,item))
try: return int(setup[0])
except: return int(config_prefs[item][3])
def put_config(room,item,value):
if value in [True,False,None]: value = str(value)
setup = cur_execute_fetchone('select value from config_conf where room=%s and option = %s',(room,item))
if setup: cur_execute('update config_conf set value=%s where room=%s and option = %s', (value,room,item))
else: cur_execute('insert into config_conf values (%s,%s,%s)', (room,item,value))
def GT(item):
try:
gt_result = cur_execute_fetchone('select value from config_owner where option = %s;',(item,))[0]
if gt_result in ['true','false','none']: gt_result = gt_result.capitalize()
except:
try: gt_result = owner_prefs[item][2]
except: gt_result = None
try: return eval(gt_result)
except: return gt_result
def PT(item,value):
if value in [True,False,None] or isinstance(value,type([])): value = str(value)
setup = cur_execute_fetchone('select value from config_owner where option = %s;',(item,))
if setup: cur_execute('update config_owner set value=%s where option = %s', (value,item))
else: cur_execute('insert into config_owner values (%s,%s)', (item,value))
def get_subtag(body,tag):
T = re.findall('%s=\"(.*?)\"' % tag,body,re.S)
if T: return T[0]
else: return ''
def get_tag(body,tag):
T = re.findall('<%s.*?>(.*?)</%s>' % (tag,tag),body,re.S)
if T: return T[0]
else: return ''
def get_tag_full(body,tag):
T = re.findall('(<%s[^>]*?>|</%s>)' % (tag,tag),body,re.S)
if T and len(T)==1: return T[0]
elif len(T) >= 2 and T[0][1:len(tag)+1] == T[1][-len(tag)-1:-1]:
T1 = re.findall('(%s.*?%s)' % (re.escape(T[0]),re.escape(T[1])),body,re.S)
if T1: return T1[0]
else: return ''
elif len(T): return T[0]
else: return ''
def get_tag_item(body,tag,item):
body = get_tag_full(body,tag)
return get_subtag(body,item)
def parser(t):
try: return ''.join([['?',l][l<='~'] for l in unicode(t)])
except:
fp = file(slog_folder % 'critical_exception_%s.txt' % int(time.time()), 'wb')
fp.write(t)
fp.close()
def remove_sub_space(t): return ''.join([['?',l][l>=' ' or l in '\t\r\n'] for l in unicode(t)])
def smart_encode(text,enc):
tx,splitter = '','|'
while splitter in text: splitter += '|'
ttext = text.replace('</','<%s/' % splitter).split(splitter)
for tmp in ttext:
try: tx += unicode(tmp,enc)
except: pass
return tx
def timeadd(lt): return '%02d.%02d.%02d %02d:%02d:%02d' % (lt[2],lt[1],lt[0],lt[3],lt[4],lt[5])
def onlytimeadd(lt): return '%02d:%02d:%02d' % (lt[3],lt[4],lt[5])
def pprint(*text):
global last_logs_store
c,wc,win_color = '','',''
if len(text) > 1:
if is_win32: win_color = get_color_win32(text[1])
else: c,wc = get_color(text[1]),get_color('clear')
elif is_win32: win_color = get_color_win32('clear')
text = text[0]
lt = tuple(time.localtime())
zz = '%s[%s]%s %s%s' % (wc,onlytimeadd(lt),c,text,wc)
last_logs_store = ['[%s] %s' % (onlytimeadd(lt),text)] + last_logs_store[:last_logs_size]
if debug_console:
if is_win32 and win_color:
ctypes.windll.Kernel32.SetConsoleTextAttribute(win_console_color, get_color_win32('clear'))
print zz.split(' ',1)[0],
ctypes.windll.Kernel32.SetConsoleTextAttribute(win_console_color, win_color)
try: print zz.split(' ',1)[1]
except: print parser(zz.split(' ',1)[1])
ctypes.windll.Kernel32.SetConsoleTextAttribute(win_console_color, get_color_win32('clear'))
else:
try: print zz
except: print parser(zz)
if CommandsLog:
fname = slog_folder % '%02d%02d%02d.txt' % (lt[0],lt[1],lt[2])
fbody = '%s|%s\n' % (onlytimeadd(lt),text.replace('\n','\r'))
fl = open(fname, 'a')
fl.write(fbody.encode('utf-8'))
fl.close()
def send_presence_all(sm):
pr=xmpp.Presence(typ='unavailable')
pr.setStatus(sm)
sender(pr)
time.sleep(2)
def errorHandler(text):
draw_warning(text)
sys.exit('exit')
def get_joke(text):
def joke_blond(text):
def blond_text(text):
b = ''
cnt = random.randint(0,1)
for tmp in text:
if cnt: b += tmp.upper()
else: b += tmp.lower()
cnt = not cnt
return b
text = text.split(' ')
new_text = []
for t in text:
if t == '/me' or [True for s in ['http://','https://','ftp://','svn://','xmpp:','git://'] if t.startswith(s)]: new_text.append(t)
else: new_text.append(blond_text(t))
return ' '.join(new_text)
def joke_upyachka(text):
upch = [u'пыщь!!!111адын',u'ололололо!!11',u'ГОЛАКТЕКО ОПАСНОСТЕ!!11',u'ТЕЛОИД!!',u'ЖАЖА1!',u'ОНОТОЛЕЙ!!!!!',u'ПОТС ЗОХВАЧЕН11!!!',
u'ПыЩЩЩЩЩЩЩЩЩь!!!!!!!1111',u'ПыЩЩЩЩЩЩЩЩЩь11111адинадин1адин']
return '%s %s' % (text.strip(),random.choice(upch))
def no_joke(text): return text
jokes = [joke_blond,no_joke,joke_upyachka]
return random.choice(jokes)(text)
def msg_validator(t): return ''.join([[l,'?'][l<' ' and l not in '\n\t\r' or l>u'\uff00'] for l in unicode(t)])
def message_exclude_update():
global messages_excl
excl = GT('exclude_messages').replace('\r','').replace('\t','').split('\n')
messages_excl = []
for c in excl:
if '#' not in c and len(c): messages_excl.append(c)
def message_validate(item):
if messages_excl:
for c in messages_excl:
cn = re.findall(c,' %s ' % item,re.S|re.I|re.U)
for tmp in cn: item = item.replace(tmp,[GT('censor_text')*len(tmp),GT('censor_text')][len(GT('censor_text'))>1])
return item
def send_msg(mtype, mjid, mnick, mmessage):
global between_msg_last,time_limit
if mmessage:
mmessage = message_validate(mmessage)
mnick = message_validate(mnick)
# 1st april joke :)
if time.localtime()[1:3] == (4,1) and GT('1st_april_joke'): mmessage = get_joke(mmessage)
no_send = True
if len(mmessage) > msg_limit:
cnt = 0
maxcnt = int(len(mmessage)/msg_limit) + 1
mmsg = mmessage
while len(mmsg) > msg_limit and not game_over:
tmsg = u'[%s/%s] %s[…]' % (cnt+1,maxcnt,mmsg[:msg_limit])
cnt += 1
sender(xmpp.Message('%s/%s' % (mjid,mnick), tmsg, 'chat'))
mmsg = mmsg[msg_limit:]
time.sleep(time_limit)
tmsg = '[%s/%s] %s' % (cnt+1,maxcnt,mmsg)
sender(xmpp.Message('%s/%s' % (mjid,mnick), tmsg, 'chat'))
if mtype == 'chat': no_send = None
else: mmessage = mmessage[:msg_limit] + u'[…]'
if no_send:
if mtype == 'groupchat' and mnick != '': mmessage = '%s: %s' % (mnick,mmessage)
else: mjid += '/' + mnick
while mmessage[-1:] in ['\n','\t','\r',' ']: mmessage = mmessage[:-1]
mmessage = msg_validator(mmessage)
if len(mmessage): sender(xmpp.Message(mjid, mmessage, mtype))
def os_version_disco():
iSys = sys.platform
iOs = os.name
isidaPyVer = sys.version.split()[0]
if iOs == 'posix':
osInfo = os.uname()
isidaOs = osInfo[0]
isidaOsVer = '%s-%s/PYv%s' % (osInfo[2].split('-',1)[0],osInfo[4],isidaPyVer)
elif iSys == 'win32':
def get_registry_value(key, subkey, value):
import _winreg
key = getattr(_winreg, key)
handle = _winreg.OpenKey(key, subkey)
(value, type) = _winreg.QueryValueEx(handle, value)
return value
def get(key): return get_registry_value("HKEY_LOCAL_MACHINE", "SOFTWARE\\Microsoft\\Windows NT\\CurrentVersion",key)
osInfo = get("ProductName")
buildInfo = get("CurrentBuildNumber")
try:
spInfo = get("CSDVersion")
isidaOs = osInfo
isidaOsVer = 'SP:%s/BLD:%s/PYv%s' % (spInfo,buildInfo,isidaPyVer)
except:
isidaOs = 'Windows'
isidaOsVer = '%s/BLD:%s/PYv%s' % (osInfo.replace('Windows','').strip(),buildInfo,isidaPyVer)
else: isidaOs = isidaOsVer = 'unknown'
return isidaOs, isidaOsVer
def os_version():
iSys = sys.platform
iOs = os.name
isidaPyVer = '%s [%s]' % (sys.version.split(' (')[0],sys.version.split(')')[0].split(', ')[1])
if iOs == 'posix':
osInfo = os.uname()
isidaOs = '%s %s-%s / Python %s' % (osInfo[0],osInfo[2],osInfo[4],isidaPyVer)
elif iSys == 'win32':
def get_registry_value(key, subkey, value):
import _winreg
key = getattr(_winreg, key)
handle = _winreg.OpenKey(key, subkey)
(value, type) = _winreg.QueryValueEx(handle, value)
return value
def get(key): return get_registry_value("HKEY_LOCAL_MACHINE", "SOFTWARE\\Microsoft\\Windows NT\\CurrentVersion",key)
osInfo = ' '.join(get("ProductName").split()[:3])
buildInfo = get("CurrentBuildNumber")
try:
spInfo = get("CSDVersion")
isidaOs = '%s %s [%s] / Python %s' % (osInfo,spInfo,buildInfo,isidaPyVer)
except: isidaOs = '%s [%s] / Python %s' % (osInfo,buildInfo,isidaPyVer)
else: isidaOs = 'unknown'
return isidaOs
def caps_and_send(tmp):
tmp.setTag('x', namespace=xmpp.NS_VCARD_UPDATE)
tmp.getTag('x', namespace=xmpp.NS_VCARD_UPDATE).setTagData('photo',photo_hash)
tmp.setTag('c', namespace=xmpp.NS_CAPS, attrs={'node':capsNode,'ver':capsHash,'hash':'sha-1'})
sender(tmp)
def join(conference,passwd):
global pres_answer,cycles_used,cycles_unused,current_join
id = get_id()
current_join[conference] = id
if Settings['status'] == 'online': j = xmpp.Node('presence', {'id': id, 'to': conference}, payload = [xmpp.Node('status', {},[Settings['message']]),\
xmpp.Node('priority', {},[Settings['priority']])])
else: j = xmpp.Node('presence', {'id': id, 'to': conference}, payload = [xmpp.Node('show', {},[Settings['status']]),\
xmpp.Node('status', {},[Settings['message']]),\
xmpp.Node('priority', {},[Settings['priority']])])
j.setTag('x', namespace=xmpp.NS_MUC).addChild('history', {'maxchars':'0', 'maxstanzas':'0'})
j.getTag('x').setTagData('password', passwd)
caps_and_send(j)
answered, Error, join_timeout = None, None, 3
if is_start: join_timeout_delay = 0.3
else: join_timeout_delay = 1
while not answered and join_timeout >= 0 and not game_over:
if is_start:
cyc = cl.Process(1)
if str(cyc) == 'None': cycles_unused += 1
elif int(str(cyc)): cycles_used += 1
else: cycles_unused += 1
else: time.sleep(join_timeout_delay)
join_timeout -= join_timeout_delay
for tmp in pres_answer:
if tmp[0]==id:
Error = tmp[1]
pres_answer.remove(tmp)
answered = True
break
if current_join.has_key(conference) and current_join[conference] != id: break
if current_join.has_key(conference):
if current_join[conference] != id: Error = {'CAPTCHA':current_join[conference],'ID':id}
current_join.pop(conference)
return Error
def leave(conference, sm):
j = xmpp.Presence(conference, 'unavailable', status=sm)
sender(j)
def muc_filter_action(act,jid,room,reason):
if act in ['visitor','kick']:
nick = get_nick_by_jid(room,getRoom(jid))
if nick and act=='visitor': sender(xmpp.Node('iq',{'id': get_id(), 'type': 'set', 'to':room},payload = [xmpp.Node('query', {'xmlns': xmpp.NS_MUC_ADMIN},[xmpp.Node('item',{'role':'visitor', 'nick':nick},[xmpp.Node('reason',{},reason)])])]))
elif nick and act=='kick': sender(xmpp.Node('iq',{'id': get_id(), 'type': 'set', 'to':room},payload = [xmpp.Node('query', {'xmlns': xmpp.NS_MUC_ADMIN},[xmpp.Node('item',{'role':'none', 'nick':nick},[xmpp.Node('reason',{},reason)])])]))
elif not nick and act=='visitor': sender(xmpp.Node('iq',{'id': get_id(), 'type': 'set', 'to':room},payload = [xmpp.Node('query', {'xmlns': xmpp.NS_MUC_ADMIN},[xmpp.Node('item',{'role':'visitor', 'jid':jid},[xmpp.Node('reason',{},reason)])])]))
elif not nick and act=='kick': sender(xmpp.Node('iq',{'id': get_id(), 'type': 'set', 'to':room},payload = [xmpp.Node('query', {'xmlns': xmpp.NS_MUC_ADMIN},[xmpp.Node('item',{'role':'none', 'jid':jid},[xmpp.Node('reason',{},reason)])])]))
elif act=='ban': sender(xmpp.Node('iq',{'id': get_id(), 'type': 'set', 'to':room},payload = [xmpp.Node('query', {'xmlns': xmpp.NS_MUC_ADMIN},[xmpp.Node('item',{'affiliation':'outcast', 'jid':jid},[xmpp.Node('reason',{},reason)])])]))
return None
def paste_text(text,room,jid):
return paste_text_raw(text,room,jid,True)
def paste_text_muc(text,room,jid):
return paste_text_raw(text,room,jid,False)
def paste_text_raw(text,room,jid,need_replace):
nick = get_nick_by_jid_res(room,jid)
_html_paste = GT('html_paste_enable')
if _html_paste:
if need_replace: text = html_escape(text).replace(' ',' ')
else: text = html_escape(text)
nick = html_escape(nick)
paste_header = ['','<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"><html xmlns="http://www.w3.org/1999/xhtml" xml:lang="ru" lang="ru"><head><meta http-equiv="Content-Type" content="text/html; charset=utf-8" /><link href="%s" rel="stylesheet" type="text/css" /><title>\n' % paste_css_path][_html_paste]
url = '%s%s' % (str(hex(int(time.time()*100)))[2:-1],['.txt','.html'][_html_paste])
lt = tuple(time.localtime())
ott = onlytimeadd(tuple(time.localtime()))
paste_body = ['%s','<p><span class="paste">%s</span></p>\n'][_html_paste] % (text)
lht = '%s [%s] - %02d/%02d/%02d %02d:%02d:%02d' % (nick,room,lt[0],lt[1],lt[2],lt[3],lt[4],lt[5])
paste_he = ['%s\t\thttp://isida.dsy.name\n\n' % lht,'%s%s</title></head><body><div class="main"><div class="top"><div class="heart"><a href="http://isida.dsy.name">http://isida.dsy.name</a></div><div class="conference">%s</div></div><div class="container">\n' % (paste_header,lht,lht)][_html_paste]
fl = open(pastepath+url, 'a')
fl.write(paste_he.encode('utf-8'))
fl.write(paste_body.encode('utf-8'))
paste_ender = ['','</div></div></body></html>'][_html_paste]
fl.write(paste_ender.encode('utf-8'))
fl.close()
return pasteurl+url
def disp_time(*t):
if len(t) == 2: rn = t[1]
else: rn = ''
t = t[0]
lt=tuple(time.localtime(t))
return '%02d:%02d:%02d, %02d.%s\'%s, %s' % (lt[3],lt[4],lt[5],lt[2],L(wmonth[lt[1]-1],rn).replace('_',''),lt[0],L(wday[lt[6]],rn))
def nice_time(*ttim):
if len(ttim) == 2: rn = ttim[1]
else: rn = ''
ttim = ttim[0]
gt=tuple(time.gmtime(ttim))
lt=tuple(time.localtime(ttim))
timeofset = (datetime.datetime(*lt[:6])-datetime.datetime(*gt[:6])).seconds / 3600.0
if timeofset < 0: t_gmt = 'GMT%s' % int(timeofset)
else: t_gmt = 'GMT+%s' % int(timeofset)
if timeofset%1: t_gmt += ':%02d' % int((timeofset%1*60/100) * 100)
t_utc='%s%02d%02dT%02d:%02d:%02d' % gt[:6]
t_display = '%02d:%02d:%02d, %02d.%s\'%s, %s, ' % (lt[3],lt[4],lt[5],lt[2],L(wmonth[lt[1]-1],rn).replace('_',''),lt[0],L(wday[lt[6]],rn))
#t_tz = time.tzname[time.localtime()[8]]
#enc = chardet.detect(t_tz)['encoding']
#if t_tz == None: body = ''
#if enc == None or enc == '' or enc.lower() == 'unicode': enc = 'utf-8'
#t_tz = unicode(t_tz,enc)
#t_display += '%s, %s' % (t_tz,t_gmt)
#return t_utc,t_tz,t_display
t_display += t_gmt
return t_utc,t_gmt,t_display
def get_eval_item(mess,string):
try:
result = eval('mess.%s' % string)
if result: return result.encode('utf-8')
except: pass
return ''
def match_for_raw(original,regexp,gr):
orig_drop = orig_reg = re.findall(regexp, original.replace('\n',' '), re.S|re.I|re.U)
while '' in orig_drop: orig_drop.remove('')
orig_join = ''.join(orig_reg)
if orig_join:
#orig_split = original.split()
#match_percent = 100.0 / len(original) * len(orig_join)
#match_percent = 100.0 / len(orig_drop) * len(orig_split)
match_percent = 100.0 / len(orig_drop) * sum([len(tmp) <= 2 for tmp in orig_drop])
raw_percent = get_config(gr,'muc_filter_raw_percent')
if raw_percent.isdigit(): raw_percent = int(raw_percent)
else: raw_percent = int(config_prefs['muc_filter_raw_percent'][3])
return ['',orig_join][match_percent >= raw_percent]
else: return ''
def caps_matcher(c_caps,c_list):
result = False
for t in c_list:
r = int(t[0] == '*')*2+int(t[-1] == '*')
if r == 3 and t[1:-1].lower() in c_caps.lower(): return True
elif r == 2 and c_caps.endswith(t[1:]): return True
elif r == 1 and c_caps.startswith(t[:-1]): return True
elif c_caps == t: return True
return result
def iqCB(sess,iq):
global timeofset, iq_in, iq_request, last_msg_base, last_msg_time_base, ddos_ignore, ddos_iq, user_hash, server_hash, server_hash_list
global disco_excl, message_excl, users_locale
iq_in += 1
id = iq.getID()
if id == None: return None
room = unicode(iq.getFrom())
if cur_execute_fetchone('select * from bot_owner where jid=%s',(getRoom(room),)): towh = selfjid
else: towh = '%s/%s' % (getRoom(room),get_nick_by_jid_res(getRoom(room), selfjid))
query = iq.getTag('query')
was_request = id in iq_request
al,tjid = get_level(getRoom(room),getResourse(room))
acclvl = al >= 7 and GT('iq_disco_enable')
nnj,tjid = False,getRoom(tjid)
if room == selfjid: nnj = True
else:
for tmp in megabase:
if '%s/%s' % tuple(tmp[0:2]) == room:
nnj = True
break
c_lang = iq.getAttr('xml:lang')
if c_lang: users_locale[room] = c_lang[:2].replace('uk','ua')
if getServer(Settings['jid']) == room: nnj = True
if iq.getType()=='error' and was_request:
try: er_name = get_tag(unicode(iq),'error').replace('<','').split()[0]
except: er_name = 'Unknown error!'
iq_async(id,time.time(),er_name,'error')
elif iq.getType()=='result' and was_request:
try: nspace = query.getNamespace()
except: nspace = 'None'
if nspace == xmpp.NS_MUC_ADMIN: iq_async(id,nspace,time.time(),iq)
elif nspace == xmpp.NS_MUC_OWNER: iq_async(id,nspace,time.time(),iq)
elif nspace == xmpp.NS_VERSION:
ver_client = unicode(query.getTagData(tag='name'))
ver_version = unicode(query.getTagData(tag='version'))
ver_os = unicode(query.getTagData(tag='os'))
t = cur_execute_fetchone('select jid from versions where room=%s and jid=%s and client=%s and version=%s and os=%s',(getRoom(room),tjid,ver_client,ver_version,ver_os))
if not t: cur_execute('insert into versions values (%s,%s,%s,%s,%s,%s)',(getRoom(room),tjid,ver_client,ver_version,ver_os,int(time.time())))
iq_async(id,nspace,time.time(),'%s %s // %s' % (ver_client,ver_version,ver_os))
elif nspace == xmpp.NS_TIME: iq_async(id,nspace,time.time(),query.getTagData(tag='display'),query.getTagData(tag='utc'),query.getTagData(tag='tz'))
elif iq.getTag('time',namespace=xmpp.NS_URN_TIME): iq_async(id,xmpp.NS_URN_TIME,time.time(),iq.getTag('time').getTagData(tag='utc'),iq.getTag('time').getTagData(tag='tzo'))
elif iq.getTag('vCard',namespace=xmpp.NS_VCARD): iq_async(id,xmpp.NS_VCARD,time.time(),unicode(iq),iq)
else: iq_async(id,nspace,time.time(),unicode(iq),iq)
elif iq.getType()=='get' and nnj and not ddos_ignore.has_key(tjid):
iq_ddos_requests,iq_ddos_limit = GT('ddos_iq_requests'),GT('ddos_iq_limit')
nick = getResourse(room)
qry = unicode(iq.getTag(name='query'))
if ddos_iq.has_key(tjid): time_tuple = [time.time()] + ddos_iq[tjid][:iq_ddos_requests-1]
else: time_tuple = [time.time()]
ddos_iq[tjid] = time_tuple
if len(time_tuple) == iq_ddos_requests and (time_tuple[0]-time_tuple[-1]) < iq_ddos_limit:
ddos_ignore[tjid] = [getRoom(room),nick,time.time()+GT('ddos_limit')[al]]
pprint('!!! IQ-DDOS Detect: %s %s [%s] %s' % (al, room, tjid, qry),'bright_red')
return
for t in [tmp[2] for tmp in giq_hook if tmp[1] == 'get']:
to_send = t(iq,id,room,acclvl,query,towh,al)
if to_send:
if to_send != True: sender(to_send)
raise xmpp.NodeProcessed
elif iq.getType()=='set':
for t in [tmp[2] for tmp in giq_hook if tmp[1] == 'set']:
to_send = t(iq,id,room,acclvl,query,towh,al)
if to_send:
if to_send != True: sender(to_send)
raise xmpp.NodeProcessed
def iq_async_clean():
global iq_reques
while not game_over:
to = GT('timeout')
while to > 0 and not game_over:
to -= 1
time.sleep(1)
if len(iq_request):
for tmp in iq_request.keys():
if iq_request[tmp][0] + GT('timeout') < time.time(): iq_request.pop(tmp)
break
def presence_async_clean():
global pres_answer
while not game_over:
to = GT('timeout')
while to > 0 and not game_over:
to -= 1
time.sleep(1)
if len(pres_answer):
tm = []
for tmp in pres_answer:
if tmp[2] + GT('timeout') > time.time(): tm.append(tmp)
pres_answer = tm
def iq_async(*answ):
global iq_request
req = iq_request.pop(answ[0])
try: er_code = answ[3]
except: er_code = None
if er_code == 'error': is_answ = (answ[1]-req[0],(answ[2],'error'))
elif req[3] == xmpp.NS_URN_PING or req[3] == answ[1]: is_answ = (answ[2]-req[0],answ[3:])
elif req[3] == xmpp.NS_VCARD and answ[1] == 'None':
answ[4].setTag('vCard',namespace=xmpp.NS_VCARD)
is_answ = (answ[2]-req[0],answ[3:])
else:
pprint('!!! Got a fake iq answer. Request: %s. Answer: %s. Raw: %s' % (req[3],answ[1],answ[3]),'red')
is_answ = (answ[2]-req[0],('%s %s' % (L('Error!'),L('Got a fake iq answer!')),))
req[2].append(is_answ)
thr(req[1],(tuple(req[2])),'iq_async_%s' % answ[0])
def remove_ignore():
global ddos_ignore
while not game_over:
if len(ddos_ignore):
tt = time.time()
for tmp in ddos_ignore.keys():
if tt > ddos_ignore[tmp][2]:
try:
ddos_ignore.pop(tmp)
pprint('!!! DDOS: Jid %s is removed from ignore!' % tmp,'red')
except: pprint('!!! DDOS: Unable find jid %s in ignore list. Perhaps it\'s removed by bot\'s owner!' % tmp,'red')
time.sleep(10)
def com_parser(access_mode, nowname, type, room, nick, text, jid):
global last_command, ddos_ignore
jjid = getRoom(jid)
if ddos_ignore.has_key(jjid): return
if last_command[1:7] == [nowname, type, room, nick, text, jid] and time.time() < last_command[7]+GT('ddos_diff')[access_mode]:
ddos_ignore[jjid] = [room,nick,time.time()+GT('ddos_limit')[access_mode]]
pprint('!!! DDOS Detect: %s %s/%s %s %s' % (access_mode, room, nick, jid, text),'bright_red')
send_msg(type, room, nick, L('Warning! Exceeded the limit of sending the same commands. You to ignore for %s.','%s/%s'%(room,nick)) % un_unix(GT('ddos_limit')[access_mode],'%s/%s'%(room,nick)))
return None
no_comm = True
cof = cur_execute_fetchall('select * from commonoff;')#!!!
for parse in comms:
if access_mode >= parse[0] and nick != nowname:
not_offed = True
if access_mode != 9 or ignore_owner:
for co in cof:
if co[0]==room and co[1]==text.lower()[:len(co[1])]:
not_offed = None
break
p1l = parse[1].lower()
if not_offed and (text.lower() == p1l or text[:len(parse[1])+1].lower() in ['%s '%p1l,'%s\n'%p1l]):
pprint('%s %s/%s [%s] %s' % (jid,room,nick,access_mode,text),'bright_cyan')
no_comm = None
if not parse[3]: thr(parse[2],(type, room, nick, parse[4:]),parse[1])
elif parse[3] == 1: thr(parse[2],(type, room, nick),parse[1])
elif parse[3] == 2: thr(parse[2],(type, room, nick, text[len(parse[1])+1:]),parse[1])
last_command = [access_mode, nowname, type, room, nick, text, jid, time.time()]
break
return no_comm
def messageCB(sess,mess):
global lfrom, lto, lastserver, lastnick, comms, message_in, no_comm, last_hash, current_join
message_in += 1
type=unicode(mess.getType())
room=unicode(mess.getFrom().getStripped())
allow_execute = True
if getRoom(Settings['jid']) == getRoom(room):
allow_execute = False
msg = 'Warning! Self-message detected!'
pprint('!!! %s Stanza:\n%s' % (msg,unicode(mess)))
own = cur_execute_fetchall('select * from bot_owner;')
if own:
for ajid in own: send_msg('chat', ajid[0], '', msg)
text=unicode(mess.getBody())
id = mess.getID()
try: was_send = messages_log.pop(id)
except: was_send = None
if was_send and type == 'error' and mess.getTag('error',attrs={'code':'500','type':'wait'}):
time.sleep(time_limit)
sender(was_send)
return
if current_join and room in [getRoom(t) for t in current_join.keys()]:
try:
tt = {}
for t in mess.getTag('captcha',attrs={'xmlns':'urn:xmpp:captcha'}).getTag('x',attrs={'xmlns':'jabber:x:data'}).getTags('field'):
tt[t.getAttrs()['var']] = t.getTagData('value')
if current_join[tt['from']] == tt['sid']:
pprint('*** Captcha: %s' % text)
current_join[tt['from']] = text
else: current_join.pop(tt['from'])
except:
for t in current_join.keys():
if room == getRoom(t):
current_join.pop(t)
break
try:
code = mess.getTag('x',namespace=xmpp.NS_MUC_USER).getTagAttr('status','code')
if code in msg_status_codes:
append_message_to_log(room,'','',type,msg_status_codes[code])
return
except: pass
if (text == 'None' or text == '') and not mess.getSubject(): return
if mess.getTimestamp() != None: return
nick=mess.getFrom().getResource()
if nick != None: nick = unicode(nick)
towh=unicode(mess.getTo().getStripped())
lprefix = get_local_prefix(room)
ft = back_text = text
rn = '%s/%s' % (room,nick)
access_mode,jid = get_level(room,nick)
if not allow_execute: access_mode = -1
nowname = get_xnick(room)
if '@' not in jid and (jid == 'None' or jid.startswith('j2j.')) and is_owner(room): access_mode = 9
if type == 'groupchat' and nick != '' and access_mode >= 0 and jid not in ['None',Settings['jid']]: talk_count(room,jid,nick,text)
if nick != '' and nick != None and nick != nowname and len(text)>1 and text != 'None' and text != to_censore(text,room) and access_mode >= 0 and get_config(getRoom(room),'censor'):
cens_text = L('Censored!',rn)
lvl = get_level(room,nick)[0]
if lvl >= 5 and get_config(getRoom(room),'censor_warning'): send_msg(type,room,nick,cens_text)
elif lvl == 4 and get_config(getRoom(room),'censor_action_member') != 'off':
act = get_config(getRoom(room),'censor_action_member')
muc_filter_action(act,jid,room,cens_text)
elif lvl < 4 and get_config(getRoom(room),'censor_action_non_member') != 'off':
act = get_config(getRoom(room),'censor_action_non_member')
muc_filter_action(act,jid,room,cens_text)
no_comm = True
if text != 'None' and text and access_mode >= 0 and not mess.getSubject():
no_comm = True
is_par = False
if text.startswith('%s: ' % nowname) or text.startswith('%s, ' % nowname):
text = text[len(nowname)+2:]
is_par = True
btext = text
if text.startswith(lprefix):
text = text[len(lprefix):]
is_par = True
if type == 'chat': is_par = True
if is_par: no_comm = com_parser(access_mode, nowname, type, room, nick, text, jid)
if no_comm:
btl = btext.lower()
if base_type == 'mysql': alias = cur_execute_fetchone("select match ,cmd from alias where (room=%s or room=%s) and ( match =%s or %s like concat( match ,' %%')) order by room desc",(room,'*',btl,btl))
else: alias = cur_execute_fetchone("select match ,cmd from alias where (room=%s or room=%s) and ( match =%s or %s ilike match ||' %%') order by room desc",(room,'*',btl,btl))
if alias:
pprint('%s %s/%s [%s|alias] %s' % (jid,room,nick,access_mode,text),'bright_cyan')
argz = btext[len(alias[0])+1:]
if not argz:
ppr = alias[1].replace('%*', '').replace('%{reduce}*', '').replace('%{reduceall}*', '').replace('%{unused}*', '')
ppr = re.sub('\%\{nick2jid\}[0-9\*]','',ppr,flags=re.S|re.I|re.U)
cpar = re.findall('%([0-9]+)', ppr, re.S)
if len(cpar):
for tmp in cpar:
try: ppr = ppr.replace('%'+tmp,'')
except: pass
else:
if '%' not in alias[1]: ppr = '%s %%*' % alias[1]