forked from ncoevoet/ChanTracker
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathplugin.py
3398 lines (3210 loc) · 121 KB
/
plugin.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
###
# Copyright (c) 2013, Nicolas Coevoet
# Copyright (c) 2010, Daniel Folkinshteyn - taken some ideas about threading database ( MessageParser )
# Copyright (c) 2004, Jeremiah Fincher - taken duration parser from plugin Time
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#
# * Redistributions of source code must retain the above copyright notice,
# this list of conditions, and the following disclaimer.
# * Redistributions in binary form must reproduce the above copyright notice,
# this list of conditions, and the following disclaimer in the
# documentation and/or other materials provided with the distribution.
# * Neither the name of the author of this software nor the name of
# contributors to this software may be used to endorse or promote products
# derived from this software without specific prior written consent.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
# ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
# LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
# CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
# SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
# INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
# CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
# ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
# POSSIBILITY OF SUCH DAMAGE.
###
import os
import time
import supybot.utils as utils
from supybot.commands import *
import supybot.commands as commands
import supybot.plugins as plugins
import supybot.ircutils as ircutils
import supybot.ircmsgs as ircmsgs
import supybot.callbacks as callbacks
import supybot.ircdb as ircdb
import supybot.log as log
import supybot.schedule as schedule
import supybot.registry as registry
import supybot.conf as conf
import socket
import re
import sqlite3
import collections
from operator import itemgetter
#due to more kind of pattern checked, increase size
ircutils._hostmaskPatternEqualCache = utils.structures.CacheDict(4000)
cache = utils.structures.CacheDict(4000)
def applymodes(channel, args=(), prefix='', msg=None):
"""Returns a MODE that applies changes on channel."""
modes = args
if msg and not prefix:
prefix = msg.prefix
return ircmsgs.IrcMsg(prefix=prefix, command='MODE', args=[channel] + ircutils.joinModes(modes), msg=msg)
def matchHostmask (pattern,n):
# return the machted pattern for Nick
if n.prefix == None or not ircutils.isUserHostmask(n.prefix):
return None
(nick,ident,host) = ircutils.splitHostmask(n.prefix)
if host.find('/') != -1:
# cloaks
if host.startswith('gateway/web/freenode/ip.') or host.startswith('gateway/web/cgi-irc/kiwiirc.com/ip.'):
n.ip = cache[host] = host.split('ip.')[1]
else:
# trying to get ip
if host in cache:
n.ip = cache[host]
else:
n.setIp(host)
if n.ip != None:
cache[host] = n.ip
else:
try:
r = socket.getaddrinfo(host,None)
if r != None:
u = {}
L = []
for item in r:
if not item[4][0] in u:
u[item[4][0]] = item[4][0]
L.append(item[4][0])
if len(L) == 1:
cache[host] = L[0]
n.setIp(L[0])
else:
cache[host] = None
except:
cache[host] = None
if n.ip != None and ircutils.hostmaskPatternEqual(pattern,'%s!%s@%s' % (nick,ident,n.ip)):
return '%s!%s@%s' % (nick,ident,n.ip)
if ircutils.hostmaskPatternEqual(pattern,n.prefix):
return n.prefix
return None
def matchAccount (pattern,pat,negate,n,extprefix):
# for $a, $~a, $a: extended pattern
result = None
if negate:
if not len(pat) and n.account == None:
result = n.prefix
else:
if len(pat):
if n.account != None and ircutils.hostmaskPatternEqual('*!*@%s' % pat, '*!*@%s' % n.account):
result = '%sa:%s' % (extprefix,n.account)
else:
if n.account != None:
result = '%sa:%s' % (extprefix,n.account)
return result
def matchRealname (pattern,pat,negate,n,extprefix):
# for $~r $r: extended pattern
if n.realname == None:
return None
if negate:
if len(pat):
if not ircutils.hostmaskPatternEqual('*!*@%s' % pat, '*!*@%s' % n.realname):
return '%sr:%s' % (extprefix,n.realname.replace(' ','?'))
else:
if len(pat):
if ircutils.hostmaskPatternEqual('*!*@%s' % pat, '*!*@%s' % n.realname):
return '%sr:%s' % (extprefix,n.realname.replace(' ','?'))
return None
def matchGecos (pattern,pat,negate,n,extprefix):
# for $~x, $x: extended pattern
if n.realname == None:
return None
tests = []
(nick,ident,host) = ircutils.splitHostmask(n.prefix)
tests.append(n.prefix)
if n.ip != None:
tests.append('%s!%s@%s' % (nick,ident,n.ip))
for test in tests:
test = '%s#%s' % (test,n.realname.replace(' ','?'))
if negate:
if not ircutils.hostmaskPatternEqual(pat,test):
return test
else:
if ircutils.hostmaskPatternEqual(pat,test):
return test
return None
def match (pattern,n,irc):
if not pattern:
return None
if not n.prefix:
return None
# check if given pattern match an Nick
key = pattern + ' :: ' + str(n)
if key in cache:
return cache[key]
cache[key] = None
extprefix = ''
extmodes = ''
if 'extban' in irc.state.supported:
ext = irc.state.supported['extban']
extprefix = ext.split(',')[0]
extmodes = ext.split(',')[1]
if pattern.startswith(extprefix):
p = pattern[1:]
negate = extmodes.find(p[0]) == -1
if negate:
p = p[1:]
t = p[0]
p = p[1:]
if len(p):
# remove ':'
p = p[1:]
if p.find(extprefix) != -1 and not p.endswith(extprefix):
# forward
p = p[(p.rfind(extprefix)+1):]
if t == 'a':
cache[key] = matchAccount (pattern,p,negate,n,extprefix)
elif t == 'r':
cache[key] = matchRealname (pattern,p,negate,n,extprefix)
elif t == 'x':
cache[key] = matchGecos (pattern,p,negate,n,extprefix)
else:
# bug if ipv6 used ..
k = pattern[(pattern.rfind(':')+1):]
cache[key] = matchHostmask(k,n)
else:
p = pattern
if p.find(extprefix) != -1:
p = p.split(extprefix)[0]
if ircutils.isUserHostmask(p):
cache[key] = matchHostmask(p,n)
else:
log.error('%s pattern is not supported' % pattern)
return cache[key]
def getBestPattern (n,irc):
# return best pattern for a given Nick
match(n.prefix,n,irc)
results = []
if not n.prefix or not ircutils.isUserHostmask(n.prefix):
return []
(nick,ident,host) = ircutils.splitHostmask(n.prefix)
if ident.startswith('~'):
ident = '*'
else:
if host.startswith('gateway/web/freenode/ip.') or host.startswith('gateway/web/cgi-irc/kiwiirc.com/ip.') or host.startswith('gateway/tor-sasl/') or host.startswith('unaffiliated/'):
ident = '*'
if n.ip != None:
if len(n.ip.split(':')) > 4:
# large ipv6
a = n.ip.split(':')
m = a[0]+':'+a[1]+':'+a[2]+':'+a[3]+':*'
results.append('*!%s@%s' % (ident,m))
else:
results.append('*!%s@*%s' % (ident,n.ip))
if host.find('/') != -1:
# cloaks
if host.startswith('gateway/'):
h = host.split('/')
# gateway/type/(domain|account) [?/random]
p = ''
if len(h) > 3:
p = '/*'
h = h[:3]
host = '%s%s' % ('/'.join(h),p)
elif host.startswith('nat/'):
h = host.replace('nat/','')
if h.find('/') != -1:
host = 'nat/%s/*' % h.split('/')[0]
if not ircutils.userFromHostmask(n.prefix).startswith('~') and not host.startswith('unaffiliated/'):
ident = ircutils.userFromHostmask(n.prefix)
if host.find('gateway/') != -1 and host.find('/x-') != -1:
host = '%s/*' % host.split('/x-')[0]
k = '*!%s@%s' % (ident,host)
if not k in results:
results.append(k)
extprefix = ''
extmodes = ''
if 'extban' in irc.state.supported:
ext = irc.state.supported['extban']
extprefix = ext.split(',')[0]
extmodes = ext.split(',')[1]
if n.account:
results.append('%sa:%s' % (extprefix,n.account))
if n.realname:
results.append('%sr:%s' % (extprefix,n.realname.replace(' ','?')))
return results
def clearExtendedBanPattern (pattern,irc):
# a little method to cleanup extended pattern
extprefix = ''
extmodes = ''
if 'extban' in irc.state.supported:
ext = irc.state.supported['extban']
extprefix = ext.split(',')[0]
extmodes = ext.split(',')[1]
if pattern.startswith(extprefix):
pattern = pattern[1:]
if pattern.startswith('~'):
pattern = pattern[1:]
pattern = pattern[1:]
if pattern.startswith(':'):
pattern = pattern[1:]
return pattern
def floatToGMT (t):
f = None
try:
f = float(t)
except:
return None
return time.strftime('%Y-%m-%d %H:%M:%S GMT',time.gmtime(f))
class Ircd (object):
# define an ircd, keeps Chan and Nick items
def __init__(self,irc,logsSize):
object.__init__(self)
self.irc = irc
self.name = irc.network
self.channels = ircutils.IrcDict()
self.nicks = ircutils.IrcDict()
self.caps = ircutils.IrcDict()
# contains IrcMsg, kicks, modes, etc
self.queue = utils.structures.smallqueue()
# contains less important IrcMsgs ( sync, logChannel )
self.lowQueue = utils.structures.smallqueue()
self.logsSize = logsSize
self.askedItems = {}
def getChan (self,irc,channel):
if not channel or not irc:
return None
self.irc = irc
if not channel in self.channels:
self.channels[channel] = Chan (self,channel)
return self.channels[channel]
def getNick (self,irc,nick):
if not nick or not irc:
return None
self.irc = irc
if not nick in self.nicks:
self.nicks[nick] = Nick(self.logsSize)
return self.nicks[nick]
def getItem (self,irc,uid):
# return active item
if not irc or not uid:
return None
for channel in list(self.channels.keys()):
chan = self.getChan(irc,channel)
items = chan.getItems()
for type in list(items.keys()):
for value in items[type]:
item = items[type][value]
if item.uid == uid:
return item
# TODO maybe uid under modes that needs op to be shown ?
return None
def info (self,irc,uid,prefix,db):
# return mode changes summary
if not uid or not prefix:
return []
c = db.cursor()
c.execute("""SELECT channel,oper,kind,mask,begin_at,end_at,removed_at,removed_by FROM bans WHERE id=? LIMIT 1""",(uid,))
L = c.fetchall()
if not len(L):
c.close()
return []
(channel,oper,kind,mask,begin_at,end_at,removed_at,removed_by) = L[0]
if not ircdb.checkCapability(prefix, '%s,op' % channel):
c.close()
return []
results = []
current = time.time()
results.append('[%s] [%s] %s sets +%s %s' % (channel,floatToGMT(begin_at),oper,kind,mask))
if not removed_at:
if begin_at == end_at:
results.append('set forever')
else:
s = 'set for %s' % utils.timeElapsed(end_at-begin_at)
s = s + ' with %s more' % utils.timeElapsed(end_at-current)
s = s + ' and ends at [%s]' % floatToGMT(end_at)
results.append(s)
else:
s = 'was active %s and ended on [%s]' % (utils.timeElapsed(removed_at-begin_at),floatToGMT(removed_at))
if end_at != begin_at:
s = s + ' ,initialy for %s' % utils.timeElapsed(end_at-begin_at)
s = s + ', removed by %s' % removed_by
results.append(s)
c.execute("""SELECT oper, comment FROM comments WHERE ban_id=? ORDER BY at DESC""",(uid,))
L = c.fetchall()
if len(L):
for com in L:
(oper,comment) = com
results.append('"%s" by %s' % (comment,oper))
c.execute("""SELECT full,log FROM nicks WHERE ban_id=?""",(uid,))
L = c.fetchall()
if len(L) == 1:
for affected in L:
(full,log) = affected
message = ""
for line in log.split('\n'):
message = '%s' % line
break
results.append(message)
elif len(L) > 1:
results.append('affects %s users' % len(L))
#if len(L):
#for affected in L:
#(full,log) = affected
#message = full
#for line in log.split('\n'):
#message = '[%s]' % line
#break
#results.append(message)
c.close()
return results
def pending(self,irc,channel,mode,prefix,pattern,db,never,ids,duration):
# returns active items for a channel mode
if not channel or not mode or not prefix:
return []
if not ircdb.checkCapability(prefix, '%s,op' % channel):
return []
chan = self.getChan(irc,channel)
results = []
r = []
c = db.cursor()
t = time.time()
for m in mode:
items = chan.getItemsFor(m)
if len(items):
for item in items:
item = items[item]
if never:
if item.when == item.expire or not item.expire:
r.append([item.uid,item.mode,item.value,item.by,item.when,item.expire])
else:
if duration > 0:
log.debug('%s -> %s : %s' % (duration,item.when,(t-item.when)))
if (t - item.when) > duration:
r.append([item.uid,item.mode,item.value,item.by,item.when,item.expire])
else:
r.append([item.uid,item.mode,item.value,item.by,item.when,item.expire])
r.sort(reverse=True)
if len(r):
for item in r:
(uid,mode,value,by,when,expire) = item
if pattern != None and not ircutils.hostmaskPatternEqual(pattern,by):
continue
c.execute("""SELECT oper, comment FROM comments WHERE ban_id=? ORDER BY at DESC LIMIT 1""",(uid,))
L = c.fetchall()
if len(L):
(oper,comment) = L[0]
message = ' "%s"' % comment
else:
message = ''
if ids:
results.append('%s' % uid)
elif expire and expire != when:
results.append('[#%s +%s %s by %s expires at %s]%s' % (uid,mode,value,by,floatToGMT(expire),message))
else:
results.append('[#%s +%s %s by %s on %s]%s' % (uid,mode,value,by,floatToGMT(when),message))
c.close()
return results
def against (self,irc,channel,n,prefix,db):
# returns active items which matchs n
if not channel or not n or not db:
return []
if not ircdb.checkCapability(prefix, '%s,op' % channel):
return []
chan = self.getChan(irc,channel)
results = []
r = []
c = db.cursor()
for k in list(chan.getItems()):
items = chan.getItemsFor(k)
if len(items):
for item in items:
item = items[item]
if match(item.value,n,irc):
r.append([item.uid,item.mode,item.value,item.by,item.when,item.expire])
r.sort(reverse=True)
if len(r):
for item in r:
(uid,mode,value,by,when,expire) = item
c.execute("""SELECT oper, comment FROM comments WHERE ban_id=? ORDER BY at DESC LIMIT 1""",(uid,))
L = c.fetchall()
if len(L):
(oper,comment) = L[0]
message = ' "%s"' % comment
else:
message = ''
if expire and expire != when:
results.append('[#%s +%s %s by %s expires at %s]%s' % (uid,mode,value,by,floatToGMT(expire),message))
else:
results.append('[#%s +%s %s by %s on %s]%s' % (uid,mode,value,by,floatToGMT(when),message))
c.close()
return results
def log (self,irc,uid,prefix,db):
# return log of affected users by a mode change
if not uid or not prefix:
return []
c = db.cursor()
c.execute("""SELECT channel,oper,kind,mask,begin_at,end_at,removed_at,removed_by FROM bans WHERE id=?""",(uid,))
L = c.fetchall()
if not len(L):
c.close()
return []
(channel,oper,kind,mask,begin_at,end_at,removed_at,removed_by) = L[0]
if not ircdb.checkCapability(prefix, '%s,op' % channel):
c.close()
return []
results = []
#c.execute("""SELECT oper, comment, at FROM comments WHERE ban_id=? ORDER BY at DESC""",(uid,))
#L = c.fetchall()
#if len(L):
#for com in L:
#(oper,comment,at) = com
#results.append('"%s" by %s on %s' % (comment,oper,floatToGMT(at)))
c.execute("""SELECT full,log FROM nicks WHERE ban_id=?""",(uid,))
L = c.fetchall()
if len(L):
for item in L:
(full,log) = item
results.append('For [%s]' % full)
for line in log.split('\n'):
results.append(line)
else:
results.append('no log found')
c.close()
return results
def search (self,irc,pattern,prefix,db,deep,active,never,channel,ids):
# deep search inside database,
# results filtered depending prefix capability
c = db.cursor()
bans = {}
results = []
isOwner = ircdb.checkCapability(prefix, 'owner') or prefix == irc.prefix
glob = '*%s*' % pattern
like = '%'+pattern+'%'
if pattern.startswith('$'):
pattern = clearExtendedBanPattern(pattern,irc)
glob = '*%s*' % pattern
like = '%'+pattern+'%'
elif ircutils.isUserHostmask(pattern):
(n,i,h) = ircutils.splitHostmask(pattern)
if n == '*':
n = None
if i == '*':
i = None
if h == '*':
h = None
items = [n,i,h]
subpattern = ''
for item in items:
if item:
subpattern = subpattern + '*' + item
glob = '*%s*' % subpattern
like = '%'+subpattern+'%'
c.execute("""SELECT id, mask FROM bans ORDER BY id DESC""")
items = c.fetchall()
if len(items):
for item in items:
(uid,mask) = item
if ircutils.hostmaskPatternEqual(pattern,mask):
bans[uid] = uid
c.execute("""SELECT ban_id, full FROM nicks ORDER BY ban_id DESC""")
items = c.fetchall()
if len(items):
for item in items:
(uid,full) = item
if ircutils.hostmaskPatternEqual(pattern,full):
bans[uid] = uid
if deep:
c.execute("""SELECT ban_id, full FROM nicks WHERE full GLOB ? OR full LIKE ? OR log GLOB ? OR log LIKE ? ORDER BY ban_id DESC""",(glob,like,glob,like))
else:
c.execute("""SELECT ban_id, full FROM nicks WHERE full GLOB ? OR full LIKE ? ORDER BY ban_id DESC""",(glob,like))
items = c.fetchall()
if len(items):
for item in items:
(uid,full) = item
bans[uid] = uid
c.execute("""SELECT id, mask FROM bans WHERE mask GLOB ? OR mask LIKE ? ORDER BY id DESC""",(glob,like))
items = c.fetchall()
if len(items):
for item in items:
(uid,full) = item
bans[uid] = uid
c.execute("""SELECT ban_id, comment FROM comments WHERE comment GLOB ? OR comment LIKE ? ORDER BY ban_id DESC""",(glob,like))
items = c.fetchall()
if len(items):
for item in items:
(uid,full) = item
bans[uid] = uid
if len(bans):
for uid in bans:
c.execute("""SELECT id, mask, kind, channel, begin_at, end_at, removed_at FROM bans WHERE id=? ORDER BY id DESC LIMIT 1""",(uid,))
items = c.fetchall()
for item in items:
(uid,mask,kind,chan,begin_at,end_at,removed_at) = item
if isOwner or ircdb.checkCapability(prefix, '%s,op' % chan):
if never or active:
if removed_at:
continue
if never:
if begin_at != end_at:
continue
if channel and len(channel):
if chan != channel:
continue
results.append([uid,mask,kind,chan])
if len(results):
results.sort(reverse=True)
i = 0
msgs = []
while i < len(results):
(uid,mask,kind,chan) = results[i]
if ids:
msgs.append('%s' % uid)
elif channel and len(channel):
msgs.append('[#%s +%s %s]' % (uid,kind,mask))
else:
msgs.append('[#%s +%s %s in %s]' % (uid,kind,mask,chan))
i = i+1
c.close()
return msgs
c.close()
return []
def affect (self,irc,uid,prefix,db):
# return affected users by a mode change
if not uid or not prefix:
return []
c = db.cursor()
c.execute("""SELECT channel,oper,kind,mask,begin_at,end_at,removed_at,removed_by FROM bans WHERE id=?""",(uid,))
L = c.fetchall()
if not len(L):
c.close()
return []
(channel,oper,kind,mask,begin_at,end_at,removed_at,removed_by) = L[0]
if not ircdb.checkCapability(prefix, '%s,op' % channel):
c.close()
return []
results = []
c.execute("""SELECT full,log FROM nicks WHERE ban_id=?""",(uid,))
L = c.fetchall()
if len(L):
for item in L:
(full,log) = item
message = full
for line in log.split('\n'):
message = '[%s]' % line
break
results.append(message)
else:
results.append('nobody affected')
c.close()
return results
def markremoved (self,irc,uid,message,prefix,db,ct):
# won't use channel,mode,value, because Item may be removed already
# it's a duplicate of mark, only used to compute logChannel on a removed item
if not prefix or not message:
return False
c = db.cursor()
c.execute("""SELECT id,channel,kind,mask FROM bans WHERE id=?""",(uid,))
L = c.fetchall()
b = False
if len(L):
(uid,channel,kind,mask) = L[0]
if not ircdb.checkCapability(prefix,'%s,op' % channel):
if prefix != irc.prefix:
c.close()
return False
current = time.time()
c.execute("""INSERT INTO comments VALUES (?, ?, ?, ?)""",(uid,prefix,current,message))
db.commit()
f = None
if prefix != irc.prefix and ct.registryValue('announceMark',channel=channel):
f = ct._logChan
elif prefix == irc.prefix and ct.registryValue('announceBotMark',channel=channel):
f = ct._logChan
if f:
if ct.registryValue('useColorForAnnounces',channel=channel):
f(irc,channel,'[%s] [#%s %s %s] marked by %s: %s' % (ircutils.bold(channel),ircutils.mircColor(uid,'yellow','black'),ircutils.bold(ircutils.mircColor('+%s' % kind,'red')),ircutils.mircColor(mask,'light blue'),prefix.split('!')[0],message))
else:
f(irc,channel,'[%s] [#%s +%s %s] marked by %s: %s' % (channel,uid,kind,mask,prefix.split('!')[0],message))
b = True
c.close()
return b
def mark (self,irc,uid,message,prefix,db,logFunction,ct):
# won't use channel,mode,value, because Item may be removed already
if not prefix or not message:
return False
c = db.cursor()
c.execute("""SELECT id,channel,kind,mask FROM bans WHERE id=?""",(uid,))
L = c.fetchall()
b = False
if len(L):
(uid,channel,kind,mask) = L[0]
if not ircdb.checkCapability(prefix,'%s,op' % channel):
if prefix != irc.prefix:
c.close()
return False
current = time.time()
c.execute("""INSERT INTO comments VALUES (?, ?, ?, ?)""",(uid,prefix,current,message))
db.commit()
if logFunction:
if ct.registryValue('useColorForAnnounces',channel=channel):
logFunction(irc,channel,'[%s] [#%s %s %s] marked by %s: %s' % (ircutils.bold(channel),ircutils.mircColor(uid,'yellow','black'),ircutils.bold(ircutils.mircColor('+%s' % kind,'red')),ircutils.mircColor(mask,'light blue'),prefix.split('!')[0],message))
else:
logFunction(irc,channel,'[%s] [#%s +%s %s] marked by %s: %s' % (channel,uid,kind,mask,prefix.split('!')[0],message))
b = True
c.close()
return b
def submark (self,irc,channel,mode,value,message,prefix,db,logFunction,ct):
# add mark to an item which is not already in lists
if not channel or not mode or not value or not prefix:
return False
if not ircdb.checkCapability(prefix,'%s,op' % channel):
if prefix != irc.prefix:
return False
c = db.cursor()
c.execute("""SELECT id,oper FROM bans WHERE channel=? AND kind=? AND mask=? AND removed_at is NULL ORDER BY id LIMIT 1""",(channel,mode,value))
L = c.fetchall()
if len(L):
# item exists
(uid,oper) = L[0]
c.close()
# must not be occurs, but ..
return self.mark(irc,uid,message,prefix,db,logFunction,ct)
else:
c.close()
if channel in self.channels:
chan = self.getChan(irc,channel)
item = chan.getItem(mode,value)
if not item:
hash = '%s%s' % (mode,value)
# prepare item update after being set ( we don't have id yet )
chan.mark[hash] = [mode,value,message,prefix]
return True
return False
def add (self,irc,channel,mode,value,seconds,prefix,db):
# add new eIqb item
if not ircdb.checkCapability(prefix,'%s,op' % channel):
if prefix != irc.prefix:
return False
if not channel or not mode or not value or not prefix:
return False
c = db.cursor()
c.execute("""SELECT id,oper FROM bans WHERE channel=? AND kind=? AND mask=? AND removed_at is NULL ORDER BY id LIMIT 1""",(channel,mode,value))
L = c.fetchall()
if len(L):
(id,oper) = L[0]
c.close()
if channel in self.channels:
chan = self.getChan(irc,channel)
hash = '%s%s' % (mode,value)
chan.update[hash] = [mode,value,seconds,prefix]
return True
return False
else:
c.close()
if channel in self.channels:
chan = self.getChan(irc,channel)
hash = '%s%s' % (mode,value)
# prepare item update after being set ( we don't have id yet )
chan.update[hash] = [mode,value,seconds,prefix]
# enqueue mode changes
chan.queue.enqueue(('+%s' % mode,value))
return True
return False
def edit (self,irc,channel,mode,value,seconds,prefix,db,scheduleFunction,logFunction,ct):
# edit eIqb duration
if not channel or not mode or not value or not prefix:
return False
if not ircdb.checkCapability(prefix,'%s,op' % channel):
if prefix != irc.prefix:
return False
c = db.cursor()
c.execute("""SELECT id,channel,kind,mask,begin_at,end_at FROM bans WHERE channel=? AND kind=? AND mask=? AND removed_at is NULL ORDER BY id LIMIT 1""",(channel,mode,value))
L = c.fetchall()
b = False
if len(L):
(uid,channel,kind,mask,begin_at,end_at) = L[0]
chan = self.getChan(irc,channel)
current = float(time.time())
if begin_at == end_at:
text = 'was forever'
else:
text = 'ended [%s] for %s' % (floatToGMT(end_at),utils.timeElapsed(end_at-begin_at))
if seconds < 0:
newEnd = begin_at
reason = 'never expires'
elif seconds == 0:
newEnd = current # force expires for next tickle
reason = 'expires at [%s], for %s in total' % (floatToGMT(newEnd),utils.timeElapsed(newEnd-begin_at))
else:
newEnd = current+seconds
reason = 'expires at [%s], for %s in total' % (floatToGMT(newEnd),utils.timeElapsed(newEnd-begin_at))
text = '%s, now %s' % (text,reason)
c.execute("""INSERT INTO comments VALUES (?, ?, ?, ?)""",(uid,prefix,current,text))
c.execute("""UPDATE bans SET end_at=? WHERE id=?""", (newEnd,int(uid)))
db.commit()
i = chan.getItem(kind,mask)
if i:
if newEnd == begin_at:
i.expire = None
else:
i.expire = newEnd
if scheduleFunction and newEnd != current:
scheduleFunction(irc,newEnd)
if logFunction:
if ct.registryValue('useColorForAnnounces',channel=channel):
logFunction(irc,channel,'[%s] [#%s %s %s] edited by %s: %s' % (ircutils.bold(channel),ircutils.mircColor(str(uid),'yellow','black'),ircutils.bold(ircutils.mircColor('+%s' % kind,'red')),ircutils.mircColor(mask,'light blue'),prefix.split('!')[0],reason))
else:
logFunction(irc,channel,'[%s] [#%s +%s %s] edited by %s: %s' % (channel,uid,kind,mask,prefix.split('!')[0],reason))
b = True
c.close()
return b
def resync (self,irc,channel,mode,db,logFunction,ct):
# here sync mode lists, if items were removed when bot was offline, mark records as removed
c = db.cursor()
c.execute("""SELECT id,channel,mask FROM bans WHERE channel=? AND kind=?AND removed_at is NULL ORDER BY id""",(channel,mode))
L = c.fetchall()
current = time.time()
commits = 0
msgs = []
if len(L):
current = time.time()
if channel in irc.state.channels:
chan = self.getChan(irc,channel)
if mode in chan.dones:
for record in L:
(uid,channel,mask) = record
item = chan.getItem(mode,mask)
if not item:
c.execute("""UPDATE bans SET removed_at=?, removed_by=? WHERE id=?""", (current,'offline!offline@offline',int(uid)))
commits = commits + 1
if ct.registryValue('useColorForAnnounces',channel=channel):
msgs.append('[#%s %s]' % (ircutils.mircColor(uid,'yellow','black'),ircutils.mircColor(mask,'light blue')))
else:
msgs.append('[#%s %s]' % (uid,mask))
if commits > 0:
db.commit()
if logFunction:
if ct.registryValue('useColorForAnnounces',channel=channel):
logFunction(irc,channel,'[%s] [%s] %s removed: %s' % (ircutils.bold(channel),ircutils.mircColor(mode,'green'),commits, ' '.join(msgs)))
else:
logFunction(irc,channel,'[%s] [%s] %s removed: %s' % (channel,mode,commits, ' '.join(msgs)))
c.close()
class Chan (object):
# in memory and in database stores +eIqb list -ov
# no user action from here, only ircd messages
def __init__(self,ircd,name):
object.__init__(self)
self.ircd = ircd
self.name = name
self._lists = ircutils.IrcDict()
# queue contains (mode,valueOrNone) - ircutils.joinModes
self.queue = utils.structures.smallqueue()
# contains [modevalue] = [mode,value,seconds,prefix]
self.update = ircutils.IrcDict()
# contains [modevalue] = [mode,value,message,prefix]
self.mark = ircutils.IrcDict()
# contains IrcMsg ( mostly kick / fpart )
self.action = utils.structures.smallqueue()
# looking for eqIb list ends
self.dones = []
self.syn = False
self.opAsked = False
self.deopAsked = False
self.deopPending = False
# now stuff here is related to protection
self.spam = ircutils.IrcDict()
self.repeatLogs = ircutils.IrcDict()
self.nicks = ircutils.IrcDict()
self.netsplit = False
self.attacked = False
def isWrong (self,pattern):
if 'bad' in self.spam and pattern in self.spam['bad']:
if len(self.spam['bad'][pattern]) > 0:
return True
return False
def getItems (self):
# [X][Item.value] is Item
return self._lists
def getItemsFor (self,mode):
if not mode in self._lists:
self._lists[mode] = ircutils.IrcDict()
return self._lists[mode]
def summary (self,db):
r = []
c = db.cursor()
c.execute("""SELECT id,oper,kind,removed_at FROM bans WHERE channel=?""",(self.name,))
L = c.fetchall()
total = {}
opers = {}
if len(L):
for item in L:
(id,oper,kind,removed_at) = item
if not kind in total:
total[kind] = {}
total[kind]['active'] = 0
total[kind]['removed'] = 0
if not removed_at:
total[kind]['active'] = total[kind]['active'] + 1
else:
total[kind]['removed'] = total[kind]['removed'] + 1
if not oper in opers:
opers[oper] = {}
if not kind in opers[oper]:
opers[oper][kind] = {}
opers[oper][kind]['active'] = 0
opers[oper][kind]['removed'] = 0
if not removed_at:
opers[oper][kind]['active'] = opers[oper][kind]['active'] + 1
else:
opers[oper][kind]['removed'] = opers[oper][kind]['removed'] + 1
for kind in total:
r.append('+%s: %s/%s (active/total)' % (kind,total[kind]['active'],total[kind]['active']+total[kind]['removed']))
for oper in opers:
r.append('%s:' % oper)
for kind in opers[oper]:
r.append('+%s: %s/%s (active/total)' % (kind,opers[oper][kind]['active'],opers[oper][kind]['active']+opers[oper][kind]['removed']))
c.close()
return r
def addItem (self,mode,value,by,when,db,checkUser=True):
# eqIb(+*) (-ov) pattern prefix when
# mode : eqIb -ov + ?
l = self.getItemsFor(mode)
if not self.syn:
checkUser = False
if not value in l:
i = Item()
i.channel = self.name
i.mode = mode
i.value = value
uid = None
expire = when
c = db.cursor()
c.execute("""SELECT id,oper,begin_at,end_at FROM bans WHERE channel=? AND kind=? AND mask=? AND removed_at is NULL ORDER BY id LIMIT 1""",(self.name,mode,value))
L = c.fetchall()
if len(L):
# restoring stored informations, due to netsplit server's values may be wrong
(uid,by,when,expire) = L[0]
c.execute("""SELECT ban_id,full FROM nicks WHERE ban_id=?""",(uid,))
L = c.fetchall()
i.isNew = False
if len(L):
for item in L:
(uid,full) = item
i.affects.append(full)
else:
# if begin_at == end_at --> that means forever
c.execute("""INSERT INTO bans VALUES (NULL, ?, ?, ?, ?, ?, ?,NULL, NULL)""", (self.name,by,mode,value,when,when))
i.isNew = True
uid = c.lastrowid
# leave channel's users list management to supybot
ns = []
if self.name in self.ircd.irc.state.channels and checkUser:
L = []
for nick in list(self.ircd.irc.state.channels[self.name].users):
L.append(nick)
for nick in L:
n = self.ircd.getNick(self.ircd.irc,nick)
m = match(value,n,self.ircd.irc)
if m:
i.affects.append(n.prefix)
# insert logs
index = 0
logs = []
logs.append('%s' % n)
for line in n.logs:
(ts,target,message) = n.logs[index]
index += 1
if target == self.name or target == 'ALL':
logs.append('[%s] <%s> %s' % (floatToGMT(ts),nick,message))
c.execute("""INSERT INTO nicks VALUES (?, ?, ?, ?)""",(uid,value,n.prefix,'\n'.join(logs)))
ns.append([n,m])
db.commit()
c.close()
i.uid = uid
i.by = by
i.when = float(when)
i.expire = float(expire)
l[value] = i
else:
l[value].isNew = False
return l[value]
def getItem (self,mode,value):
if mode in self._lists:
if value in self._lists[mode]:
return self._lists[mode][value]
return None
def removeItem (self,mode,value,by,c):
# flag item as removed in database, we use a cursor as argument because otherwise database tends to be locked
removed_at = float(time.time())
i = self.getItem(mode,value)
created = False
if not i:
c.execute("""SELECT id,oper,begin_at,end_at FROM bans WHERE channel=? AND kind=? AND mask=? AND removed_at is NULL ORDER BY id LIMIT 1""",(self.name,mode,value))
L = c.fetchall()
if len(L):
(uid,by,when,expire) = L[0]
i = Item()
i.uid = uid
i.mode = mode
i.value = value
i.channel = self.named
i.by = oper
i.when = float(when)
i.expire = float(expire)
if i: