-
Notifications
You must be signed in to change notification settings - Fork 0
/
mica.py
executable file
·6391 lines (5290 loc) · 286 KB
/
mica.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/env python
# coding: utf-8
from pwd import getpwuid
from sys import path
from time import sleep
from threading import Thread, Lock, current_thread, Timer, local as threading_local
from datetime import datetime as datetime_datetime
import threading
from copy import deepcopy
from cStringIO import StringIO
from traceback import format_exc, print_stack
from os import path as os_path, getuid as os_getuid, urandom as os_urandom, remove as os_remove, makedirs as os_makedirs
from re import compile as re_compile, IGNORECASE as re_IGNORECASE, sub as re_sub
from shutil import rmtree as shutil_rmtree
from urllib2 import quote as urllib2_quote, Request as urllib2_Request, urlopen as urllib2_urlopen, URLError as urllib2_URLError, HTTPError as urllib2_HTTPError
from urllib import urlencode
from codecs import open as codecs_open
from uuid import uuid4 as uuid_uuid4
from hashlib import md5 as hashlib_md5
from json import loads as json_loads, dumps as json_dumps
from base64 import b64encode as base64_b64encode
from socket import timeout as socket_timeout
from string import ascii_lowercase as string_ascii_lowercase, ascii_uppercase as string_ascii_uppercase
from binascii import hexlify as binascii_hexlify
from sys import settrace as sys_settrace
from pyratemp import TemplateSyntaxError
import requests
import couch_adapter
import processors
from processors import *
from common import *
from serializable import *
from translator import *
from templates import *
from prebind import BOSHClient
uploads_enabled = True
dbtag = "MICA"
if not mobile :
import stripe
try :
from gcm import *
from gcm.gcm import GCMNotRegisteredException
except ImportError, e :
mdebug("Cannot find GCM. Will not be able to send android push notifications.")
from apns import APNs, Frame, Payload
from crypticle import *
from oauthlib.common import to_unicode
from oauthlib.oauth2.rfc6749.errors import MissingTokenError, InvalidGrantError, InvalidClientIdError
from requests_oauthlib import OAuth2Session
from requests_oauthlib.compliance_fixes import facebook_compliance_fix
from requests.exceptions import ConnectionError as requests_ConnectionError
try :
import PythonMagick
except ImportError, e :
# TODO: not using this boolean anywhere yet....
uploads_enabled = False
mdebug("Cannot find PythonMagick: uploads will be disabled on this server.")
mverbose("Initial imports complete")
cwd = re_compile(".*\/").search(os_path.realpath(__file__)).group(0)
import sys
if mobile :
sys.path = [cwd, cwd + "mica/", cwd + "urllib3/"] + sys.path
else :
sys.path = [cwd, cwd + "mica/"] + sys.path
#Non-python-core
from zope.interface import Interface, Attribute, implements
from twisted.python.components import registerAdapter
from twisted.web.wsgi import WSGIResource
from twisted.web.static import File
from twisted.web.resource import Resource
from twisted.web import proxy, server
from twisted.python import log, failure
from twisted.python.logfile import DailyLogFile
from twisted.internet.error import AlreadyCalled, CannotListenError
from twisted.internet import reactor, defer, main as tmain
import sys
reactor = sys.modules['twisted.internet.reactor']
from twisted.web.server import Session, Site
from webob import Request, Response, exc
'''
import httplib
import logging
httplib.HTTPConnection.debuglevel = 3
httplib.HTTPSConnection.debuglevel = 3
requests_log = logging.getLogger("requests.packages.urllib3")
requests_log.setLevel(DEBUG)
requests_log.propagate = False
'''
if not mobile :
try :
from pdfminer.pdfinterp import PDFResourceManager, PDFPageInterpreter
from pdfminer.converter import PDFPageAggregator
from pdfminer.layout import LAParams, LTPage, LTTextBox, LTText, LTContainer, LTTextLine, LTImage, LTRect, LTCurve
from pdfminer.pdfpage import PDFPage
except ImportError, e :
mdebug("Could not import pdfminer. Full translation will not work.")
pass
mverbose("Imports complete.")
pdf_punct = ",卜「,\,,\\,,【,\],\[,>,<,】,〈,@,;,&,*,\|,/,-,_,—,,,,,.,。,?,?,:,:,\:,\:,:,\:,\、,\“,\”,~,`,\",\',…,!,!,(,\(,),\),口,」,了,丫,㊀,。,门,X,卩,乂,一,丁,田,口,匕,《,》,化,*,厂,主,竹,-,人,八,七,,,、,闩,加,。,』,〔,飞,『,才,廿,来,兀,〜,\.,已,I,幺,去,足,上,円,于,丄,又,…,〉".decode("utf-8")
for letter in (string_ascii_lowercase + string_ascii_uppercase) :
pdf_punct += letter.decode("utf-8")
pdf_expr = r"([" + pdf_punct + "][" + pdf_punct + "]|[\x00-\x7F][\x00-\x7F]|[\x00-\x7F][" + pdf_punct + "]|[" + pdf_punct + "][\x00-\x7F])"
mverbose("Punctuation complete.")
period_mapping = {"days" : "week", "weeks" : "month", "months" : "year", "years" : "decade", "decades" : "decade"}
period_story_mapping = {"week" : "%a", "month" : "%m/%d", "year" : "%b", "decade" : "%Y"}
period_view_mapping = {"days" : "%a %I:%M:%S %p", "weeks" : "%m/%d %I:%M:%S %p", "months" : "%m/%d %I:%M:%S %p", "years" : "%m/%d %I:%M:%S %p", "decades" : "%m/%d/%y %I:%M:%S %p"}
translated_periods = { "days" : _("days"), "day" : _("day"), "weeks" : _("weeks"),
"week" : _("week"), "months" : _("months"), "month" : _("month"),
"years" : _("year"), "year" : _("years"), "decade" : _("decades") }
def parse_lt_objs (lt_objs, page_number):
text_content = []
images = []
if lt_objs :
if isinstance(lt_objs, LTTextBox) or isinstance(lt_objs, LTText):
text_content.append(lt_objs.get_text().strip())
elif isinstance(lt_objs, LTImage):
images.append(lt_objs.stream.get_data())
elif isinstance(lt_objs, LTContainer):
for lt_obj in lt_objs:
sub_text, sub_images = parse_lt_objs(lt_obj, page_number)
text_content = text_content + sub_text
for image in sub_images :
images.append(image)
return (text_content, images)
def filter_lines(data2) :
new_page = []
for line in data2 :
if line == "" :
continue
for match in re_compile(r'[0-9]+ +[0-9, ]+', flags=re_IGNORECASE).findall(line) :
line = line.replace(match, match.replace(" ", ""))
temp_line = line.strip().decode("utf-8") if isinstance(line, str) else line.strip()
if len(temp_line) == 3 and temp_line[0] == "(" and temp_line[-1] == ")" :
matches = re_compile(u'\(.\)', flags=re_IGNORECASE).findall(temp_line)
if len(matches) == 1 :
continue
line = re_sub(r'( *82303.*$|[0-9][0-9][0-9][0-9][0-9]+ *)', '', line)
test_all = re_sub(r'([\x00-\x7F]| )+', '', line)
if test_all == "" :
continue
no_numbers = re_sub(r"([0-9]| )+", "", line)
if isinstance(no_numbers, str) :
no_numbers = no_numbers.decode("utf-8")
while len(re_compile(pdf_expr).findall(no_numbers)) :
no_numbers = re_sub(pdf_expr, '', no_numbers)
continue
if len(no_numbers) <= 1 :
continue
new_page.append(line)
return new_page
def itemhelp(pairs) :
story = pairs[1]
total_memorized = story["total_memorized"] if "total_memorized" in story else 0
total_unique = story["total_unique"] if "total_unique" in story else 0
pr = int((float(total_memorized) / float(total_unique)) * 100) if total_unique else 0
story["pr"] = str(pr)
return pr
mverbose("Setting up prefixes.")
#username = getpwuid(os_getuid())[0]
relative_prefix_suffix = "serve"
relative_prefix = "/" + relative_prefix_suffix
def prefix(uri) :
result = re_compile("[^/]*\:\/\/([^/]*)(\/(.*))*").search(uri)
address = result.group(1)
path = result.group(3)
if path is None :
path = ""
return (address, path)
class Params(object) :
def __init__(self, environ):
self.pid = "none"
self.http = Request(environ)
self.not_replicated = False
self.human = True if int(self.http.params.get("human", "1")) else False
self.messages = ""
self.action = self.http.path[1:] if len(self.http.path) > 0 else None
self.environ = environ
minfo("Request: " + self.http.url + " action: " + self.action)
self.api = False
if self.action is None or self.action == "":
self.action = "index"
if self.action == "api" :
operation = self.http.params.get("alien", False)
if not operation :
mwarn("Parameters initialization bad request")
raise exc.HTTPBadRequest("init: you did a bad thing")
self.api = True
self.action = operation
self.unparsed_uri = self.http.url
self.uri = self.http.path
self.active = None
if self.action == "index" :
self.mpath = self.uri + relative_prefix_suffix
self.bootstrappath = self.uri + relative_prefix_suffix + "/bootstrap"
else :
self.mpath = self.uri + "/.." + relative_prefix
self.bootstrappath = self.uri + "/.." + relative_prefix + "/bootstrap"
class MICA(object):
def __init__(self, db_adapter):
self.serial = Serializable(params["serialize_couch_on_mobile"])
self.general_processor = Processor(self, params, "general")
self.translation_client = Translator(params["trans_id"], params["trans_secret"], params["trans_scope"], params["trans_access_token_url"], test = params["test"])
self.mutex = Lock()
self.sessionmutex = Lock()
self.jobsmutex = Lock()
self.transmutex = Lock()
self.imemutex = Lock()
self.rollmutex = Lock()
self.pid = "none"
self.dbs = {}
self.userdb = False
self.db_adapter = db_adapter
if not mobile :
self.jabber_crypt = Crypticle(params["jabber_auth"])
if mobile :
self.cs = self.db_adapter(params["couch"])
else :
if params["admin_user"] and params["admin_pass"] :
self.cs = self.db_adapter(couch_adapter.credentials(params), params["admin_user"], params["admin_pass"], refresh = True)
self.userdb = self.cs["_users"]
self.first_request = {}
self.views_ready = {}
self.view_runs = [ #name , #startend key or regular keys
('accounts/all', True),
('memorized2/allcount', True),
('chats/all', True),
('stories/original', True),
('stories/pages', True),
('stories/allpages', True),
('stories/all', True),
('stories/translating', True),
('stories/upgrading', True),
('stories/alloriginal', True),
('memorized2/all', False),
('tonechanges/all', False),
('mergegroups/all', False),
('splits/all', False),
]
self.processors = {}
for tofrom, readable in processor_map.iteritems() :
if processor_map[tofrom] :
self.processors[tofrom] = getattr(processors, processor_map[tofrom])(self, params, tofrom)
try :
mverbose("Checking database access")
if mobile :
self.db = self.cs[params["local_database"]]
self.sessiondb = self.cs["sessiondb"]
self.filedb = self.cs["files"]
else :
if self.userdb :
self.db = self.userdb
self.view_check("mica_admin", "accounts")
if "mica_admin" not in self.cs :
self.make_account(self, "mica_admin", "password", "[email protected]", "mica", admin = True, dbname = "mica_admin")
if "file_admin" not in self.cs :
self.make_account(self, "files", "password", "[email protected]", "mica", admin = False, dbname = "files", extra_roles = ["nobody"])
self.verify_db(False, "mica_admin", username = "mica_admin")
self.verify_db(False, "files", username = "files")
self.sessiondb = self.dbs["mica_admin"]
self.filedb = self.dbs["files"]
else :
mwarn("Admin credentials ommitted. Skipping administration setup.")
if not mobile :
self.view_check("mica_admin", "conflicts")
self.view_check("files", "readonly")
self.view_check("files", "download")
self.view_check("mica_admin", "sessions")
if not mobile :
for name, lgp in self.processors.iteritems() :
for f in lgp.get_dictionaries() :
if not self.filedb.doc_exist(dbtag + ":filelisting_" + f) :
self.filedb[dbtag + ":filelisting_" + f] = {"foo" : "bar"}
mdebug("Checking if files exist............")
for name, lgp in self.processors.iteritems() :
for f in lgp.get_dictionaries() :
listing = self.filedb[dbtag + ":filelisting_" + f]
fname = params["scratch"] + f
if '_attachments' not in listing or f not in listing['_attachments'] or not self.serial.safe_execute(False, self.size_check, f) :
if os_path.isfile(fname) :
minfo("Opening dict file: " + f)
fh = open(fname, 'r')
minfo("Uploading " + f + " to file listing...")
self.filedb.put_attachment(dbtag + ":filelisting_", f, fh, new_doc = listing)
fh.close()
minfo("Uploaded.")
else :
minfo("Cannot Upload " + f + ", not generated yet.")
else :
mdebug("File " + f + " already exists.")
lgp.test_dictionaries(retest = True)
if not params["keepsession"] :
current_session_time = int(timest())
while True :
session_delete = []
for result in self.sessiondb.view('sessions/all') :
sid = result["key"][0]
if sid == "debug" :
continue
session = result["value"]
last_refresh = 0
if "last_refresh" in session :
last_refresh = int(float(session["last_refresh"]))
session_diff = (current_session_time - last_refresh)
if "last_refresh" not in session or session_diff >= params["timeout"] :
mdebug("SESSION EXPIRED: " + str(sid) + " last refresh: " + str(last_refresh) + " diff: " + str(session_diff) + " > " + str(params["timeout"]))
session_delete.append(sid)
if len(session_delete) > 0 :
for sid in session_delete :
del self.sessiondb[self.session(str(sid))]
mdebug("Deleted session: " + str(sid))
session_delete = []
continue
break
except TypeError, e :
out = "Account documents don't exist yet. Probably they are being replicated: " + str(e)
for line in format_exc().splitlines() :
mwarn(line)
except couch_adapter.ResourceNotFound, e :
mwarn("Account document @ " + self.acct('mica_admin') + " not found: " + str(e))
except Exception, e :
for line in format_exc().splitlines() :
merr(line)
mwarn("Database not available yet: " + str(e))
if mobile and params["serialize_couch_on_mobile"] :
mdebug("Launching runloop timer")
rt = Thread(target=self.runloop)
rt.daemon = True
rt.start()
if not mobile :
mverbose("Starting view runner thread")
vt = Thread(target=self.view_runner_sched)
vt.daemon = True
vt.start()
def tofrom(self, story) :
return story["source_language"] + "," + story["target_language"]
def authenticate(self, username, password, auth_url) :
mverbose("Authenticating to: " + str(auth_url))
username = username.lower()
lookup_username = username
if not password :
password = params["admin_pass"]
username = params["admin_user"].lower()
lookup_username_unquoted = myquote(str(lookup_username))
username_unquoted = myquote(str(username))
for attempt in range(0, 20) :
try :
if attempt > 0 :
mdebug("Authentication attempt #" + str(attempt))
if isinstance(username, unicode) :
username = username.encode("utf-8").decode("latin1")
if isinstance(password, unicode) :
password = password.encode("utf-8").decode("latin1")
r = requests.get(auth_url + "/_users/org.couchdb.user:" + lookup_username_unquoted, auth=(username, password), timeout = 20 if attempt == 0 else 10)
if r.status_code == 401 :
mwarn("Got 401. Will try again.")
return False, _("Invalid credentials. Please try again") + "."
if r.status_code in [200, 201] :
rr = r.text
mdebug("Authentication success with username: " + username + " : " + str(rr) + " type " + str(type(rr)))
return json_loads(rr), False
mwarn("Got " + str(r.status_code) + ". Will try again.")
except requests.exceptions.ConnectionError, e :
mwarn("HTTP error: " + username + " " + str(e))
error = "(HTTP code: " + str(e) + ")"
except Exception, e :
for line in format_exc().splitlines() :
mwarn(line)
mwarn("Unknown error: " + username + " " + str(e))
error = "(Unknown error: " + str(e) + ")"
sleep(1)
merr("Authentication failure")
return False, _("Your device either does not have adequate signal strength or your connection does not have adequate connectivity. While you do have a connection (3/4G or Wifi), we were not able to reach the server.")
def prime_db(self, req, specific_views = False) :
username = req.session.value["username"].lower()
self.new_job(req, self.view_runner, _("Priming database for you. Please wait."), username, True, args = [username, self.dbs[username]], kwargs = dict(specific_views = specific_views))
def verify_db(self, req, dbname, cookie = False, password = False, username = False, prime = True) :
if not username :
username = req.session.value["username"].lower()
if username not in self.dbs or not self.dbs[username] :
mverbose("Database not set. Requesting object.")
if mobile :
mverbose("Setting mobile db to prexisting object.")
self.dbs[username] = self.db
else :
address = req.session.value["address"] if (req and "address" in req.session.value) else couch_adapter.credentials(params)
# In the past, we were interacting with user databases using their
# own credentials, but due to CouchDB timeouts, we need a reliable
# way to refresh the cookie without setting our own timeout and
# without storing user passwords in memory. At the most, they
# should remain salted and unrecoverable in couchdb.
# Thus, we depend on the admin password to perform all those
# interactions, but javascript (via chat) still depeneds on
# directly communicating with couchdb. We are already doing it
# this way for oauth-based databases, so it's not a big deal.
cs = self.db_adapter(address, params["admin_user"], params["admin_pass"], cookie, refresh = True)
if password :
req.session.value["cookie"] = cs.get_cookie(address, username, password)
req.session.save()
self.dbs[username] = cs[dbname]
self.views_ready[username] = 0
mverbose("Installing view counter.")
if username not in self.views_ready :
self.views_ready[username] = 0
if req :
req.db = self.dbs[username]
#if prime :
# self.prime_db(req)
# sleep(1)
if self.dbs[username].doc_exist(self.acct(username)) :
user = self.dbs[username][self.acct(username)]
def session(self, sid) :
return dbtag + ":sessions:" + sid
def tokens(self) :
return dbtag + ":push_tokens"
def acct(self, name) :
return dbtag + ":accounts:" + name
def key_common(self, username) :
return dbtag + ":" + username
def story(self, req, key) :
return self.key_common(req.session.value['username']) + ":stories:" + key
# How many days since 1970 instead of seconds
def current_day(self) :
return (int(timest()) / (params["seconds_in_day"]))
def current_period(self, period_key, current_day = False):
return int(current_day if current_day else self.current_day()) / params["counts"][period_key]
def chat_name(self, period, index, peer, current_day, extra = "") :
return "chat;" + period + ";" + str(index) + ";" + peer + extra
def chat(self, req, period, index, peer, current_day, extra = "") :
return self.story(req, self.chat_name(period, index, peer, current_day, extra))
def chat_period_name(self, period_key, peer, current_day, extra = "") :
return self.chat_name(period_key, self.current_period(period_key, current_day), peer, extra)
def chat_period(self, req, period_key, peer, current_day, extra = "") :
return self.chat(req, period_key, self.current_period(period_key, current_day), peer, extra)
def index(self, req, key) :
return self.key_common(req.session.value['username']) + ":story_index:" + key
def merge(self, req, key) :
return self.key_common(req.session.value['username']) + ":mergegroups:" + key
def splits(self, req, key) :
return self.key_common(req.session.value['username']) + ":splits:" + key
def tones(self, req, key) :
return self.key_common(req.session.value['username']) + ":tonechanges:" + key
def memorized(self, req, key):
return self.key_common(req.session.value['username']) + ":memorized:" + key
def install_local_language(self, req, language = False) :
if language :
l = language
elif "language" in req.session.value :
l = req.session.value["language"]
else :
l = get_global_language()
catalogs.language = l.split("-")[0]
return l
def runloop(self) :
mdebug("Runloop running.")
sleep(5)
while True :
loop_result = self.serial.safe_execute(False, self.db.runloop)
if loop_result :
if loop_result == 1 :
self.serial.q.put("stop_now")
elif loop_result == 2 :
self.serial.q.put("start_now")
sleep(1)
self.db.detach_thread()
def account_exists(self, username) :
if self.userdb.doc_exist("org.couchdb.user:" + username) :
dbname = self.userdb["org.couchdb.user:" + username]["mica_database"]
if dbname in self.cs :
newdb = self.cs[dbname]
if newdb.doc_exist(self.acct(username)) :
return True
return False
# This make_account is restartable now. In case of lost connectivity in the
# middle of any of it, the rest can be created later.
def make_account(self, req, username, password, email, source, admin = False, dbname = False, language = "en", extra_roles = []) :
username = username.lower()
if not dbname :
new_uuid = str(uuid_uuid4())
dbname = "mica_" + new_uuid
if not self.userdb.doc_exist("org.couchdb.user:" + username) :
mverbose("Creating user in _user database...")
user_doc = { "name" : username,
"password" : password,
"roles": [] if admin else [username + "_master", "nobody"],
"type": "user",
"mica_database" : dbname,
"language" : language,
"learnlanguage" : "en",
"date" : timest(),
"email" : email,
"source" : source,
"quota" : -1 if admin else 300,
}
mverbose("Putting doc: " + str(user_doc))
self.userdb["org.couchdb.user:" + username] = user_doc
else :
dbname = self.userdb["org.couchdb.user:" + username]["mica_database"]
mverbose("Retrieving new database: " + dbname)
newdb = self.cs[dbname]
new_security = newdb.get_security()
if len(new_security) == 0 :
mverbose("Installing security on admin database.")
new_security = {"admins" :
{
"names" : ["mica_admin"],
"roles" : [username + "_master"] if admin else []
},
"members" :
{
"names" : ["mica_admin" if admin else "nobody", username],
"roles" : [username + "_master"] + extra_roles
}
}
newdb.set_security(new_security)
if not newdb.doc_exist(self.acct(username)) :
mverbose("Making initial account parameters.")
newdb[self.acct(username)] = {
'app_chars_per_line' : 70,
'web_chars_per_line' : 70,
'default_app_zoom' : 1.0,
'default_web_zoom' : 1.0,
"language" : language,
"learnlanguage" : "en",
"source" : source,
"email" : email,
"filters" : {'files' : [], 'stories' : [] },
"story_format" : story_format,
}
self.check_all_views(username)
@serial
def view_runner(self, username, db, specific_views = False) :
# This only primes views for logged-in users.
# Scaling the backgrounding for all users will need more thought.
# FIXME: If the session expires, the backgrounding continues. Should we
# leave it that way?
mdebug("Priming views for user: " + username)
self.views_ready[username] = 0
if specific_views :
runners = specific_views
else :
runners = deepcopy(self.view_runs)
for (name, startend) in runners :
if not db.doc_exist("_design/" + name.split("/")[0]) :
mdebug("View " + name + " does not yet exist. Loading...")
self.view_check(username, name.split("/")[0], recreate = True)
mdebug("Done.")
continue
mdebug("Priming view for user: " + username + " db " + name)
if startend :
for unused in db.view(name, startkey=["foo", "bar"], endkey=["foo", "bar", "baz"]) :
pass
else :
for unused in db.view(name, keys = ["foo"], username = "bar") :
pass
self.views_ready[username] += 1
'''
mdebug("Auditing stories")
for result in db.view("stories/all", startkey=[username], endkey=[username, {}]) :
tmp_story = result["value"]
tmp_storyname = tmp_story["name"]
story_view_original = 0
story_view_original_found = 0
story_view_pages = 0
story_view_pages_found = 0
stories = {}
for oresult in db.view('stories/original', startkey=[username, tmp_storyname], endkey=[username, tmp_storyname, {}]) :
story_view_original = oresult['value']
break
for presult in db.view('stories/pages', startkey=[username, tmp_storyname], endkey=[username, tmp_storyname, {}]) :
story_view_pages = presult['value']
if tmp_storyname not in stories :
stories[tmp_storyname] = []
break
for sresult in db.view('stories/allpages', startkey=[username, tmp_storyname], endkey=[username, tmp_storyname, {}]) :
page = int(sresult["key"][2])
if page not in stories[tmp_storyname] :
stories[tmp_storyname].append(page)
if "nb_pages" in tmp_story :
if tmp_story["nb_pages"] != story_view_pages :
mdebug("Story " + tmp_storyname + " says it has " + str(tmp_story["nb_pages"]) + " pages.")
mdebug("Story " + tmp_storyname + " actually has: " + str(story_view_original) + " originals and " + str(story_view_pages) + " pages.")
mdebug("Story " + tmp_storyname + " pages: " + str(stories[tmp_storyname]))
else :
mdebug("Story " + tmp_storyname + " says unknown pages.")
'''
return _("Database optimized.")
def view_runner_sched(self) :
mverbose("Execute the view runner one time to get started...")
for username, db in self.dbs.iteritems() :
self.view_runner(username, db)
while True :
mverbose("View runner complete. Waiting until next time...")
sleep(1800)
for username, db in self.dbs.iteritems() :
self.view_runner(username, db)
def get_filter_params(self, req) :
filterparams = {"name" : "download/mobile"}
filterparams["stories"] = ",".join(["none"] + (req.session.value["filters"]["stories"] if "filters" in req.session.value else []))
files = ["none"]
if "filters" in req.session.value :
for tofrom in req.session.value["filters"]["files"] :
gp = self.processors[tofrom]
for f in gp.get_dictionaries() :
files.append(f)
filterparams["files"] = ",".join(files)
return json_dumps(filterparams)
@serial
def run_render(self, req) :
if 'connected' not in req.session.value :
mdebug("New session. Setting connected to false.")
req.session.value["connected"] = False
# Can't be sure we've authenticated yet
# Don't save
# req.session.save()
if "language" not in req.session.value and "HTTP_ACCEPT_LANGUAGE" in req.environ:
req.session.value["language"] = req.environ['HTTP_ACCEPT_LANGUAGE'].split("-")[0].split(",")[0]
mdebug("Setting session language to browser language: " + req.session.value["language"])
req.session.save()
if not mobile and not params["couch_server"].count("localhost") and not params["couch_server"].count("dev") :
req.front_ads = True
try:
if self.connected(req) :
username = req.session.value["username"]
if username not in self.dbs :
if mobile :
# Couchbase mobile can do cookie authentication, we're just not using it yet....
# FIXME to use cookies for replication instead of saving the user's
# password in the session file
# This is OK for now since we're running on a phone....
mdebug("Trying to restart replication...")
if not self.db.filters(params["local_database"], self.get_filter_params(req)) :
merr("Refreshing main filter installation failed.")
elif not self.db.replicate(req.session.value["address"], username, req.session.value["password"], req.session.value["database"], params["local_database"]) :
merr("Refreshing session failed to restart main replication: Although you have authenticated successfully, we could not start replication successfully. Please try again")
req.session.value["port"] = self.db.listen(username, req.session.value["password"], params["local_port"])
req.session.save()
if not self.filedb.filters("files", self.get_filter_params(req)) :
merr("Refreshing files filter installation failed.")
elif not self.filedb.replicate(req.session.value["address"], "files", "password", "files", "files") :
merr("Refreshing session failed to restart file replication: Although you have authenticated successfully, we could not start replication successfully. Please try again")
try :
self.verify_db(req, req.session.value["database"], prime = False)
resp = self.render(req)
except couch_adapter.CommunicationError, e :
for line in format_exc().splitlines() :
mwarn(line)
merr("Must re-login: " + str(e))
self.clean_session(req, force = True)
# The user has completed logging out / signing out already - then this message appears.
req.messages = _("Disconnected from Read Alien")
resp = self.render_frontpage(req)
except couch_adapter.ResourceNotFound, e :
mwarn("Problem before warn_not_replicated:")
for line in format_exc().splitlines() :
mwarn(line)
resp = self.warn_not_replicated(req)
except exc.HTTPTemporaryRedirect, e :
raise e
except exc.HTTPUnauthorized, e :
raise e
except exc.HTTPBadRequest, e :
raise e
except TemplateSyntaxError, e :
merr(_("Exception") + ":")
resp = "<h4>" + _("Exception") + ":</h4>"
for line in format_exc().splitlines() :
resp += "<br>" + line
merr(line)
resp += "<br/><h2>" + _("(template) Please report the above exception to the author. Thank you") + ".</h2>"
except Exception, msg:
merr(_("Exception") + ":")
resp = "<h4>" + _("Exception") + ":</h4>"
for line in format_exc().splitlines() :
resp += "<br>" + line
merr(line)
resp += "<br/><h2>" + _("(unknown) Please report the above exception to the author. Thank you") + ".</h2>"
if ((not isinstance(msg, str) and not isinstance(msg, unicode)) or (not msg.count("SAXParseException") and not msg.count("MissingRenderMethod" and not resp.count("TemplateSyntaxError")))) and self.connected(req) :
mwarn("Boo other, logging out user now.")
self.clean_session(req, force = True)
else :
if req.api and req.action not in (([] if mobile else params["oauth"].keys()) + ["connect", "disconnect"]):
raise exc.HTTPUnauthorized("you're not logged in anymore.")
if req.action in ["connect", "disconnect", "survey", "privacy", "help", "switchlang", "online", "instant", "auth", "push", "stories" ] + ([] if mobile else params["oauth"].keys() ):
self.install_local_language(req)
resp = self.render(req)
else :
resp = self.render_frontpage(req)
except exc.HTTPTemporaryRedirect, e :
resp = e
resp.location = req.dest + resp.location
except exc.HTTPUnauthorized, e:
resp = e
except exc.HTTPException, e:
resp = e
except couch_adapter.ResourceNotFound, e :
mwarn("Problem before warn_not_replicated:")
for line in format_exc().splitlines() :
mwarn(line)
resp = self.warn_not_replicated(req)
except couch_adapter.CommunicationError, e :
for line in format_exc().splitlines() :
merr(line)
if self.connected(req) :
mwarn("Not a well-caught exception. Setting connected to false.")
req.session.value["connected"] = False
req.session.save(force = True)
raise exc.HTTPUnauthorized("<h2>" + _("Lost connectivity to the database. Please come back later.") + "</h2>")
except Exception, e :
# This 'exception' appears when there is a bug in the software and the software is not functioning normally. A report of the details of the bug follow after the word "Exception"
aout = ""
resp = "<h4>" + _("Exception") + ":</h4>"
aout += "Exception\n"
for line in format_exc().splitlines() :
resp += "<br>" + line
aout += line + "\n"
resp += "<h2>" + _("(outer unknown) Please report the exception above to the author. Thank you.") + "</h2>"
merr(aout)
if self.connected(req) :
mwarn("Not a well-caught exception. Setting connected to false.")
req.session.value["connected"] = False
req.session.save(force = True)
return resp
def expired(self, uid, session):
mdebug("Session " + uid + " has expired.")
if params["keepsession"] :
mdebug("Need to keep the session")
return
if uid == "debug" :
mdebug("Not expiring debug session.")
return
unused, slock = session.uidcheck(uid)
slock.acquire()
skey = self.session(uid)
try :
if self.serial.safe_execute(False, self.sessiondb.doc_exist, skey) :
value = self.serial.safe_execute(False, self.sessiondb.__getitem__, skey)
if "username" in value :
self.clean_dbs(value["username"])
self.serial.safe_execute(False, self.sessiondb.__delitem__, skey)
mdebug("Deleted session.")
else :
mdebug("Not deleting session.")
except Exception, e :
for line in format_exc().splitlines() :
merr(line)
self.sessionmutex.acquire()
del sessions[uid]
self.sessionmutex.release()
slock.release()
def __call__(self, environ, start_response):
try :
# Hack to make WebOb work with Twisted
setattr(environ['wsgi.input'], "readline", environ['wsgi.input']._wrapped.readline)
req = Params(environ)
req.s = start_response.im_self.request.s
req.s.mica = self
req.mica = self
req.session = IDict(req.s)
req.source = environ["REMOTE_ADDR"]
req.db = False
req.dest = ""
req.front_ads = False
req.couch_cookie = False
if start_response.im_self.request.s.uid not in sessions :
self.sessionmutex.acquire()
sessions[start_response.im_self.request.s.uid] = Lock()
self.sessionmutex.release()
start_response.im_self.request.s.notifyOnExpire(lambda: self.expired(start_response.im_self.request.s.uid, req.session))
if req.action not in ["push", "auth", "disconnect"] and not mobile :
self.populate_oauth_state(req)
resp = self.run_render(req)
except couch_adapter.CommunicationError, e :
err = exc.HTTPUnauthorized("<h2>" + _("Lost connectivity to the database. Please come back later.") + "</h2>")
req.messages = err.detail
resp = Response(self.render_frontpage(req), status_code = err.code, status = err.code)
except exc.HTTPUnauthorized, e :
req.messages = e.detail
resp = Response(self.render_frontpage(req), status_code = e.code, status = e.code)
except exc.HTTPBadRequest, e :
req.messages = e.detail
resp = Response(self.render_frontpage(req), status_code = e.code, status = e.code)
except Exception, e :
merr("BAD Read Alien ********\nException:")
for line in format_exc().splitlines() :
merr(line)
r = None
try :
if isinstance(resp, str) or isinstance(resp, unicode):
if isinstance(resp, str) :
resp = resp.decode("utf-8")
webob_response = Response(resp)
if not mobile and 'cookie' in req.session.value :
cook = req.session.value["cookie"].split("=")[1]
webob_response.set_cookie("AuthSession", cook, max_age=params["timeout"])
r = webob_response(environ, start_response)
else :
r = resp(environ, start_response)
except Exception, e :
merr("RESPONSE Read Alien ********\nException:\n")
for line in format_exc().splitlines() :
merr(line)
return r
def template(self, template_prefix) :
contents_fh = open(cwd + relative_prefix + "/" + template_prefix + "_template.html", "r")
contents = contents_fh.read()
contents_fh.close()
return contents
def api(self, req, desc = "", json = False, error = False) :
cookie = req.db.gimme_cookie() if (not mobile and req.db) else False
if cookie :
req.session.value["cookie"] = cookie
req.session.save()
if not json :
json = {}
json["replicated"] = not req.not_replicated
if req.human :
return str(json["desc"]) if "desc" in json else desc
else :
if "desc" not in json :
json["desc"] = desc
if "success" not in json :
json["success"] = True if not error else False
if json["success"] and req.not_replicated :