-
Notifications
You must be signed in to change notification settings - Fork 2
/
jabrssng.py
2281 lines (1834 loc) · 82.5 KB
/
jabrssng.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
# Copyright (C) 2001-2011, Christof Meerwald
# http://jabrss.cmeerw.org
# 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; version 2 dated June, 1991.
#
# 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, write to the Free Software
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307
# USA
from __future__ import with_statement
import base64, bisect, codecs, getopt, logging, os, ssl, socket
import sqlite3, sys, threading, time, traceback
from getpass import getpass
from xmpplify import tobytes, Element, JID, Stanza, XmppStream
from parserss import RSS_Resource, RSS_Resource_id2url, RSS_Resource_simplify
from parserss import RSS_Resource_db, RSS_Resource_Cursor
from parserss import UrlError
from parserss import init_parserss
if not hasattr(__builtins__, 'raw_input'):
raw_input = input
logger = logging.getLogger('JabRSS')
def log_message(*msg):
if sys.version_info[0] == 2:
data = map(lambda x: unicode(x), msg)
else:
data = msg
logger.info(b' '.decode('ascii').join(data))
init_parserss(db_fname='jabrss_res.db', dbsync_obj=threading.Lock())
TEXT_WELCOME = '''\
Welcome to JabRSS. Please note that the current privacy policy is quite simple: all your data are belong to me and might be sold to your favorite spammer. :-) For more information, please visit the JabRSS Web site at http://jabrss.cmeerw.org
BTW, if you like this service, you can help keeping it running by making a donation, see http://cmeerw.org/donate.html'''
TEXT_NEWUSER = '''
Now there is only one more thing to do before you can use JabRSS: you have to authorize the presence subscription request from JabRSS. This is necessary so that JabRSS knows your presence status and only sends you RSS headlines when you are online.'''
TEXT_HELP = '''\
Supported commands:
subscribe http://host.domain/path/feed.rss
unsubscribe http://host.domain/path/feed.rss
info http://host.domain/path/feed.rss
list
set ( plaintext | chat | headline )
set also_deliver [ Away ] [ XA ] [ DND ]
set header [ Title ] [ URL ]
set subject [ Title ] [ URL ]
set size_limit <num>
set store_messages <num>
configuration
show statistics
show usage
Please refer to the JabRSS command reference at http://dev.cmeerw.org/jabrss/Documentation for more information.
And of course, if you like this service you might also consider a donation, see http://cmeerw.org/donate.html'''
JABRSS_JID = None
JABRSS_HOST = None
JABRSS_PASSWORD = None
MAX_MESSAGE_SIZE = 20000
opts, args = getopt.getopt(sys.argv[1:], 'f:h:p:j:',
['password-file=', 'password=',
'jid=', 'connect-host='])
for optname, optval in opts:
if optname in ('-f', '--password-file'):
fd = open(optval, 'r')
JABRSS_PASSWORD = fd.readline().strip()
fd.close()
elif optname in ('-h', '--connect-host'):
JABRSS_HOST = optval
elif optname in ('-p', '--password'):
JABRSS_PASSWORD = optval
elif optname in ('-j', '--jid'):
JABRSS_JID = JID(optval)
if JABRSS_JID == None:
JABRSS_JID = JID(raw_input('JabRSS JID: '))
if JABRSS_HOST == None:
JABRSS_HOST = raw_input('Host: ')
if JABRSS_PASSWORD == None:
JABRSS_PASSWORD = getpass('Password: ')
http_proxy = os.getenv('http_proxy')
if http_proxy and (http_proxy[:7] == 'http://'):
http_proxy = http_proxy[7:]
if http_proxy[-1] == '/':
http_proxy = http_proxy[:-1]
else:
http_proxy = None
https_proxy = os.getenv('https_proxy')
if https_proxy and (https_proxy[:7] == 'http://'):
https_proxy = https_proxy[7:]
if https_proxy[-1] == '/':
https_proxy = https_proxy[:-1]
else:
https_proxy = None
RSS_Resource.http_proxy = http_proxy
if hasattr(sqlite3, 'enable_shared_cache'):
# non-standard, but useful
sqlite3.enable_shared_cache(True)
def get_db():
db = sqlite3.Connection('jabrss.db', 60000)
db.isolation_level = None
db.cursor().execute('PRAGMA synchronous=NORMAL')
return db
class FlexibleLocker:
def __init__(self, lock, active = True):
self._lock, self._active = lock, active
self._locked = False
def __enter__(self):
self.lock()
return self
def __exit__(self, exc_type, exc_value, traceback):
self.unlock()
def locked(self):
if not self._locked and self._active and self._lock != None:
self._locked = True
def lock(self):
if not self._locked and self._active and self._lock != None:
self._lock.acquire()
self._locked = True
def unlock(self):
if self._locked and self._active and self._lock != None:
self._lock.release()
self._locked = False
def replace(self, lock):
self.unlock()
self._lock = lock
self.lock()
class Cursor:
def __init__(self, dbconn, parent = None):
self._txn, self._locked = False, False
self._parent = parent
if self._parent == None:
if not hasattr(dbconn, 'cursor'):
self._cursor = dbconn().cursor()
else:
self._cursor = dbconn.cursor()
else:
self._cursor = None
def __enter__(self):
if self._parent == None:
return self
else:
return self._parent
def __exit__(self, exc_type, exc_value, traceback):
if self._parent == None:
self.commit()
def begin(self):
if not self._locked:
db_sync.acquire()
self._locked = True
if not self._txn:
self._cursor.execute('BEGIN')
self._txn = True
def commit(self):
try:
if self._txn:
self._cursor.execute('COMMIT')
self._txn = False
finally:
if self._locked:
db_sync.release()
self._locked = False
def execute(self, stmt, bindings=None):
self.begin()
if bindings == None:
return self._cursor.execute(stmt)
else:
return self._cursor.execute(stmt, bindings)
def fetchone(self):
return self._cursor.fetchone()
def __getattr__(self, name):
if name == 'lastrowid':
return self._cursor.lastrowid
elif name == 'rowcount':
return self._cursor.rowcount
raise AttributeError('object has no attribute \'%s\'' % (name,))
db = get_db()
db_sync = threading.Lock()
main_res_db = RSS_Resource_db()
class DataStorage:
def __init__(self):
self._users = {}
self._users_sync = threading.Lock()
self._resources = {}
self._res_uids = {}
self._resources_sync = threading.Lock()
self._redirect_db = None
def _redirect_cb(self, redirect_url, db, redirect_count,
generate_id, connect_timeout, timeout):
redirect_resource = self.get_resource(redirect_url, db)
# prevent resource from being evicted until redirect is processed
with Cursor(self._redirect_db) as cursor:
try:
dummy_user.add_resource(redirect_resource, None, cursor)
except ValueError:
pass
redirect_resource.unlock()
new_items, next_item_id, redirect_target, redirect_seq, redirects = redirect_resource.update(db, redirect_count, redirect_cb = storage._redirect_cb)
if len(new_items) > 0:
redirect_resource.unlock()
redirects.insert(0, (redirect_resource, new_items, next_item_id))
elif (redirect_target != None) or (redirect_resource._invalid_since):
with redirect_resource.sync():
with Cursor(self._redirect_db) as cursor:
try:
dummy_user.remove_resource(redirect_resource, cursor)
except ValueError:
pass
if redirect_target != None:
redirect_resource = redirect_target
return redirect_resource, redirects
def users_sync(self):
return self._users_sync
def resources_sync(self):
return self._resources_sync
# get resource (by URL) from cache, database or create new object
# @param res_cursor db cursor for resource database
# @return resource (already locked, must be unlocked)
def get_resource(self, url, res_db=None, lock=True, follow_redirect=True):
resource_url = RSS_Resource_simplify(url)
with FlexibleLocker(self.resources_sync(), lock) as resources_locker:
while resource_url != None:
cached_resource = True
try:
resource = self._resources[resource_url]
resources_locker.unlock()
if lock:
resource.lock()
resources_locker.lock()
except KeyError:
resources_locker.unlock()
resource = RSS_Resource(resource_url, res_db)
if lock:
resource.lock()
resources_locker.lock()
cached_resource = False
if follow_redirect:
resource_url, redirect_seq = resource.redirect_info(res_db)
else:
resource_url, redirect_seq = None, None
if resource_url != None and lock:
resource.unlock()
if not cached_resource:
self._resources[resource.url()] = resource
self._resources[resource.id()] = resource
RSS_Resource.schedule_update(resource)
return resource
# @throws KeyError
def get_cached_resource(self, url):
resource_url = RSS_Resource_simplify(url)
with self.resources_sync():
return self._resources[resource_url]
def get_resource_by_id(self, res_id, res_db=None, follow_redirect=False):
with self.resources_sync():
try:
return self._resources[res_id]
except KeyError:
resource_url = RSS_Resource_id2url(res_id)
return self.get_resource(resource_url, res_db, False,
follow_redirect)
def evict_resource(self, resource):
with self.resources_sync():
try:
del self._resources[resource.url()]
except KeyError:
pass
try:
del self._resources[resource.id()]
except KeyError:
pass
try:
del self._res_uids[resource.id()]
except KeyError:
pass
# @precondition self.resources_sync()
def get_resource_uids(self, resource, db_cursor=None):
res_id = resource.id()
try:
res_uids = self._res_uids[res_id]
except KeyError:
res_uids = []
with Cursor(db, db_cursor) as cursor:
result = cursor.execute('SELECT uid FROM user_resource WHERE rid=?',
(res_id,))
for row in result:
res_uids.append(row[0])
self._res_uids[res_id] = res_uids
return res_uids
# @throws KeyError
def get_user(self, jid):
key = jid.bare().tostring().lower()
jid_resource = jid.resource()
if jid_resource == None:
jid_resource = ''
return self._users[key], jid_resource
# @throws KeyError
def get_user_by_id(self, uid):
return self._users[uid]
def load_user(self, jid, presence_show, create=False):
key = jid.bare().tostring().lower()
jid_resource = jid.resource()
if presence_show == None:
jid_resource = None
elif jid_resource == None:
jid_resource = ''
try:
user = self._users[key]
user.set_presence(jid_resource, presence_show)
return user, jid_resource
except KeyError:
try:
user = JabberUser(key, jid_resource, presence_show, create)
except KeyError:
return None, None
with self.users_sync():
self._users[key] = user
self._users[user.uid()] = user
for res_id in user._res_ids:
try:
storage.get_resource_by_id(res_id, main_res_db)
except:
log_message('caught exception loading resource', str(res_id), 'for new user')
traceback.print_exc(file=sys.stdout)
return user, jid_resource
def evict_user(self, user):
with self.users_sync():
try:
del self._users[user.jid()]
except KeyError:
pass
try:
del self._users[user.uid()]
except KeyError:
pass
def evict_all_users(self):
with self.users_sync():
self._users = {}
def remove_user(self, user):
with Cursor(db) as cursor:
cursor.execute('DELETE FROM user WHERE uid=?',
(user.uid(),))
log_message('user %s (id %d) deleted' % (user._jid, user._uid))
self.evict_user(user)
storage = DataStorage()
def strip_resource(jid):
pos = jid.find('/')
if pos != -1:
jid = jid[:pos]
return jid.lower()
def get_week_nr():
t = int(time.time())
gmtime = time.gmtime(t)
# converting old entries:
# 1775 + x/7; 1827 + x/7
week_nr = t - ((gmtime[3]*60 + gmtime[4])*60 + gmtime[5])
week_nr -= gmtime[6]*24*60*60
week_nr += 84*60*60
week_nr //= 7*24*60*60
return week_nr
class JabberUser:
##
# self._jid
# self._uid
# self._uid_str
# self._res_ids
# self._configuration & 0x0003 .. message type
# (0 = plain text, 1 = headline messages, 2 = chat message, 3 = reserved)
# self._configuration & 0x001c .. deliver when away
# (4 = away, 8 = xa, 16 = dnd)
# self._configuration & 0x0020 .. migration flag
# self._configuration & 0x00c0 .. feed title/URL in message subject
# (0x40 .. title, 0x80 .. URL)
# self._configuration & 0x0300 .. feed title/URL in message text
# (0x100 .. title, 0x200 .. URL)
# self._store_messages .. number of messages that should be stored
# self._size_limit .. limit the size of descriptions
# self._stat_start .. first week corresponding to _nr_headlines[-1]
# self._nr_headlines[8] .. number of headlines delivered (per week)
# self._size_headlines[8] .. size of headlines delivered (per week)
#
# self._unknown_msgs .. number of unknown messages received
##
def __init__(self, jid, jid_resource, show=None, create=False):
self._jid = jid
if jid_resource != None:
self._jid_resources = {jid_resource : show}
else:
self._jid_resources = {}
self._update_presence()
self._configuration = 0
self._store_messages = 16
self._size_limit = None
with Cursor(db) as cursor:
cursor.execute('SELECT uid, conf, store_messages, size_limit FROM user WHERE jid=?',
(self._jid,))
row = cursor.fetchone()
if row != None:
self._uid, self._configuration, self._store_messages, self._size_limit = row
elif create:
cursor.execute('INSERT INTO user (jid, conf, store_messages, size_limit, since) VALUES (?, ?, ?, ?, ?)',
(self._jid, self._configuration, self._store_messages, self._size_limit, get_week_nr()))
self._uid = cursor.lastrowid
else:
raise KeyError(jid)
if self._size_limit == None:
self._size_limit = 0
else:
self._size_limit *= 16
self._res_ids = []
result = cursor.execute('SELECT rid FROM user_resource WHERE uid=?',
(self._uid,))
for row in result:
self._res_ids.append(row[0])
self._stat_start = 0
self._nr_headlines = []
self._size_headlines = []
self._unknown_msgs = 0
result = cursor.execute('SELECT start, nr_msgs0, nr_msgs1, nr_msgs2, nr_msgs3, nr_msgs4, nr_msgs5, nr_msgs6, nr_msgs7, size_msgs0, size_msgs1, size_msgs2, size_msgs3, size_msgs4, size_msgs5, size_msgs6, size_msgs7 FROM user_stat WHERE uid=?',
(self._uid,))
for row in result:
self._stat_start = row[0]
self._nr_headlines = list(row[1:9])
self._size_headlines = list(row[9:17])
self._adjust_statistics()
def _adjust_statistics(self):
new_stat_start = get_week_nr()
shift = new_stat_start - self._stat_start
self._nr_headlines = self._nr_headlines[shift:]
self._size_headlines = self._size_headlines[shift:]
self._stat_start = new_stat_start
if len(self._nr_headlines) < 8:
self._nr_headlines += (8 - len(self._nr_headlines)) * [0]
if len(self._size_headlines) < 8:
self._size_headlines += (8 - len(self._size_headlines)) * [0]
def _commit_statistics(self, db_cursor=None):
with Cursor(db, db_cursor) as cursor:
cursor.execute('INSERT INTO user_stat (uid, start, nr_msgs0, nr_msgs1, nr_msgs2, nr_msgs3, nr_msgs4, nr_msgs5, nr_msgs6, nr_msgs7, size_msgs0, size_msgs1, size_msgs2, size_msgs3, size_msgs4, size_msgs5, size_msgs6, size_msgs7) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)',
tuple([self._uid, self._stat_start] + self._nr_headlines + self._size_headlines))
def uid(self):
return self._uid
def jid(self):
return self._jid
# @return (day of year, [nr_headlines])
def get_statistics(self):
return (self._stat_start, self._nr_headlines, self._size_headlines)
def set_message_type(self, message_type):
self._configuration = (self._configuration & ~0x0003) | (message_type & 0x0003)
self._update_configuration()
def get_message_type(self):
return self._configuration & 0x0003
def set_subject_format(self, format):
self._configuration = (self._configuration & ~0x00c0) | (((format ^ 0x1) & 0x0003) << 6)
self._update_configuration()
def get_subject_format(self):
return ((self._configuration & 0x00c0) >> 6) ^ 0x1
def set_header_format(self, format):
self._configuration = (self._configuration & ~0x0300) | ((format & 0x0003) << 8)
self._update_configuration()
def get_header_format(self):
return (self._configuration & 0x0300) >> 8
def set_size_limit(self, size_limit):
if size_limit > 0:
self._size_limit = min(size_limit, 3072)
else:
self._size_limit = 0
self._update_configuration()
def get_size_limit(self):
if self._size_limit > 0:
return min(self._size_limit, 3072)
else:
return 1024
def set_store_messages(self, store_messages):
self._store_messages = min(64, max(0, store_messages))
self._update_configuration()
def get_store_messages(self):
return self._store_messages
def get_deliver_when_away(self):
return self._configuration & 0x4
def get_deliver_when_xa(self):
return self._configuration & 0x8
def get_deliver_when_dnd(self):
return self._configuration & 0x10
def set_delivery_state(self, state):
self._configuration = (self._configuration & ~0x001c) | ((state & 7) << 2)
self._update_configuration()
def _update_configuration(self):
with Cursor(db) as cursor:
cursor.execute('UPDATE user SET conf=?, store_messages=?, size_limit=? WHERE uid=?',
(self._configuration, self._store_messages, self._size_limit // 16, self._uid))
def set_configuration(self, conf, store_messages, size_limit):
self._configuration = conf
self._store_messages = store_messages
self._size_limit = size_limit
self._update_configuration()
def get_configuration(self):
return (self._configuration, self._store_messages, self._size_limit)
def _update_presence(self):
new_show = -1
for show in self._jid_resources.values():
if (show >= 0) and ((show < new_show) or (new_show < 0)):
new_show = show
self._show = new_show
def set_presence(self, jid_resource, show):
if show == None:
return
if show >= 0:
self._jid_resources[jid_resource] = show
else:
try:
del self._jid_resources[jid_resource]
except KeyError:
pass
if jid_resource == '':
for res in list(self._jid_resources.keys()):
try:
del self._jid_resources[res]
except KeyError:
pass
self._update_presence()
# @throws KeyError
def presence(self, jid_resource=None):
if jid_resource == None:
return self._show
else:
return self._jid_resources[jid_resource]
def get_delivery_state(self, presence=None):
if presence == None:
presence = self.presence()
# self._configuration & 0x001c .. deliver when away
# (4 = away, 8 = xa, 16 = dnd)
return (presence in (0, 1)) or \
((presence == 2) and (self._configuration & 0x4)) or \
((presence == 3) and (self._configuration & 0x8)) or \
((presence == 4) and (self._configuration & 0x10))
def resources(self):
return self._res_ids
# @precondition resource.locked()
# @throws ValueError
def add_resource(self, resource, seq_nr=None, db_cursor=None):
res_id = resource.id()
if res_id not in self._res_ids:
self._res_ids.append(res_id)
# also update storage res->uid mapping
with storage.resources_sync():
res_uids = storage.get_resource_uids(resource, db_cursor)
res_uids.append(self.uid())
with Cursor(db, db_cursor) as cursor:
cursor.execute('INSERT INTO user_resource (uid, rid, seq_nr) VALUES (?, ?, ?)',
(self._uid, res_id, seq_nr))
else:
raise ValueError(res_id)
# @precondition resource.locked()
# @throws ValueError
def remove_resource(self, resource, db_cursor=None):
res_id = resource.id()
self._res_ids.remove(res_id)
# also update storage res->uid mapping
with storage.resources_sync():
res_uids = storage.get_resource_uids(resource, db_cursor)
try:
res_uids.remove(self.uid())
except ValueError:
pass
if len(res_uids) == 0:
storage.evict_resource(resource)
with Cursor(db, db_cursor) as cursor:
cursor.execute('DELETE FROM user_resource WHERE uid=? AND rid=?',
(self._uid, res_id))
def headline_id(self, resource, db_cursor=None):
with Cursor(db, db_cursor) as cursor:
result = cursor.execute('SELECT seq_nr FROM user_resource WHERE uid=? AND rid=?',
(self._uid, resource.id()))
headline_id = None
for row in result:
headline_id = row[0]
if headline_id == None:
headline_id = 0
return headline_id
def update_headline(self, resource, headline_id, new_items=[],
db_cursor=None):
with Cursor(db, db_cursor) as cursor:
cursor.execute('UPDATE user_resource SET seq_nr=? WHERE uid=? AND rid=?',
(headline_id, self._uid, resource.id()))
if new_items:
self._adjust_statistics()
self._nr_headlines[-1] += len(new_items)
items_size = 0
for item in new_items:
items_size += len(item.title) + len(item.link)
if item.descr_plain != None:
items_size += len(item.descr_plain)
self._size_headlines[-1] += items_size
self._commit_statistics(cursor)
class DummyJabberUser(JabberUser):
def __init__(self):
self._jid = None
self._show = 'xa'
self._jid_resources = {None: self._show}
self._configuration = 0x20
self._store_messages = 0
self._size_limit = 0
self._uid = -1
self._res_ids = []
self._stat_start = 0
self._nr_headlines = []
self._size_headlines = []
def _commit_statistics(self, db_cursor=None):
pass
def _update_configuration(self):
pass
def _update_presence(self):
pass
def get_delivery_state(self, presence=None):
return False
# @precondition resource.locked()
# @throws ValueError
def add_resource(self, resource, seq_nr=None, db_cursor=None):
res_id = resource.id()
log_message('dummy adding res', str(res_id), str(len(self._res_ids)))
if res_id not in self._res_ids:
self._res_ids.append(res_id)
# also update storage res->uid mapping
with storage.resources_sync():
res_uids = storage.get_resource_uids(resource, db_cursor)
res_uids.append(self.uid())
else:
raise ValueError(res_id)
# @precondition resource.locked()
# @throws ValueError
def remove_resource(self, resource, db_cursor=None):
res_id = resource.id()
log_message('dummy removing res', str(res_id), str(len(self._res_ids)))
if len(self._res_ids) == 0:
return
self._res_ids.remove(res_id)
# also update storage res->uid mapping
with storage.resources_sync():
res_uids = storage.get_resource_uids(resource, db_cursor)
try:
res_uids.remove(self.uid())
except ValueError:
pass
if len(res_uids) == 0:
storage.evict_resource(resource)
def headline_id(self, resource, db_cursor=None):
return 0
def update_headline(self, resource, headline_id, new_items=[],
db_cursor=None):
pass
dummy_user = DummyJabberUser()
class JabRSSStream(XmppStream):
def __init__(self, jid, host, password, port=5222):
self.jid, self._host, self._port = jid, host, port
self._update_queue = []
self._update_queue_cond = threading.Condition()
RSS_Resource.schedule_update = self.schedule_update
self._io_sync = threading.Lock()
self._roster_id, self._sock, self._encoding = 0, None, 'utf-8'
self._online = False
self._term, self._term_flag = threading.Event(), False
handlers = {
('iq', 'get', '{http://jabber.org/protocol/disco#info}query') : self.iq_get_disco,
('iq', 'get', '{jabber:iq:last}query') : self.iq_get_last,
('iq', 'get', '{urn:xmpp:ping}ping') : self.iq_get_ping,
('iq', 'get', '{jabber:iq:time}query') : self.iq_get_time_jabber,
('iq', 'get', '{urn:xmpp:time}time') : self.iq_get_time,
('iq', 'get', '{jabber:iq:version}query') : self.iq_get_version,
('iq', 'get') : self.iq_get,
('iq', 'set', '{jabber:iq:roster}query') : self.iq_set_roster,
('iq', 'set') : self.iq_set,
('message', 'normal') : self.message,
('message', 'chat') : self.message,
('message', 'headline') : self.message_headline,
('presence', None) : self.presence_available,
('presence', 'unavailable') : self.presence_unavailable,
('presence', 'error') : self.presence_unavailable,
('presence', 'subscribe') : self.presence_subscribe,
('presence', 'subscribed') : self.presence_subscribed,
('presence', 'unsubscribe') : self.presence_unsubscribe,
('presence', 'unsubscribed') : self.presence_unsubscribed,
}
XmppStream.__init__(self, self.jid, handlers,
encoding=self._encoding,
password=password)
def _stream_closed(self):
storage.evict_all_users()
sock = self._sock
self._sock, self._online = None, False
return sock
def connect(self):
# resolve addresses manually for compatibility with Python 2.5
# which doesn't support create_connection
exc = socket.gaierror(-2, 'Name or service not known')
for ai in socket.getaddrinfo(self._host, self._port, socket.AF_UNSPEC, socket.SOCK_STREAM):
try:
exc = None
self._sock = socket.socket(ai[0], ai[1], ai[2])
self._sock.settimeout(30)
self._sock.connect(ai[4])
break
except socket.error as e:
exc = e
if exc != None:
raise exc
log_message('connected to', str(self._sock.getpeername()))
self._sock.settimeout(600)
XmppStream.connect(self)
def sock(self):
self._io_sync.acquire()
try:
return self._sock
finally:
self._io_sync.release()
def send(self, data):
self._io_sync.acquire()
try:
if self._sock != None:
logger.debug('>>> ' + repr(data))
try:
self._sock.sendall(data)
except socket.error:
self._stream_closed()
raise
finally:
self._io_sync.release()
def closed(self):
log_message('stream closed')
self._io_sync.acquire()
try:
self._stream_closed()
finally:
self._io_sync.release()
def shutdown(self):
log_message('stream shutdown')
self._io_sync.acquire()
try:
sock = self._stream_closed()
if sock != None:
try:
sock.shutdown(socket.SHUT_WR)
except socket.error:
pass
finally:
self._io_sync.release()
def terminate(self):
self._term_flag = True
self._update_queue_cond.acquire()
self._update_queue_cond.notifyAll()
self._update_queue_cond.release()
self._term.wait()
def terminated(self):
return self._term_flag
def stream_start(self, elem):
log_message('stream start')
def stream_features(self, elem):
log_message('stream features')
def stream_error(self, elem):
log_message('stream error')
storage.evict_all_users()
def stream_end(self, elem):
storage.evict_all_users()
def starttls_proceed(self, elem):