Source

trac-userscriptservernotes-plugin / src / usernotes / notes_mail.py

Full commit
  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
import re, sys
import datetime, string
import collections

from trac.core import Component, implements, ExtensionPoint
from trac.util import Markup #, format_datetime

from trac.web import IRequestHandler
from trac.perm import IPermissionRequestor
from trac.web.chrome import INavigationContributor, ITemplateProvider
from trac.config import Option, ListOption, PathOption, BoolOption
from trac.web.chrome import add_stylesheet, add_script
from trac.util.presentation import Paginator
from trac.util import Markup, format_datetime
from trac.util.datefmt import localtz

from trac.util.translation import domain_functions
_, tag_, N_, ngettext, add_domain = domain_functions('usernotes',
    '_', 'tag_', 'N_', 'ngettext', 'add_domain')

import cgi
import logging
import string
from time import strftime, localtime
import os.path

from sqlalchemy import Column, Integer, String
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy import create_engine
from sqlalchemy.orm import create_session
from sqlalchemy.sql import desc
import sqlalchemy.sql.functions as by

from db.session import context
from db.model import NotesMail

import web_nav

PACKAGE = "usernotes"
TITLE = "Userscript ServerNotes Mail"

import os.path

def strU(text):
    try:
        return unicode(text)
    except:
        return unicode(str(text), "utf-8")
def str8_(text):
    if isinstance(text, unicode):
        return text.encode("utf-8")
    else:
        return str(text)
def str8(text):
    return str(text)

def esc(text):
    if not text: return u""
    return cgi.escape(strU(text))

class UserNotesMail(Component):
    
    implements(IRequestHandler)

    domainlist = ListOption(PACKAGE, "domain_list", "domain1, domain2",
          doc="The domains that you want to create databases for")
    
    def __init__(self):
        locale_dir = os.path.join(os.path.dirname(__file__), "locale")
        add_domain(self.env.path, locale_dir)
        
    
    """
      Determines if request should be handled by this plugin.
    """
    def match_request(self, req):
        m = re.match(r"/%s\b/%s\b(/.*)?" % (web_nav.URL, web_nav.MAIL), req.path_info)
        if not m:
            return False
        domainpage = m.group(1)
        if not domainpage: domainpage = ""
        req.args["domainpage"] = domainpage
        return True

    """
      Handles display, append and delete requests on this plugin.
    """
    def process_request(self, req):
        req.perm.assert_permission(web_nav.VIEW)
        self.locale_dir = os.path.join(os.path.dirname(__file__), "locale")
        domainpage = req.args["domainpage"]
        if domainpage:
            return self.do_mail(req, domainpage)
        return self.do_default(req, message="[%s]" % domainpage)

    def do_default(self, req, message=""):
        data = {}
        data["title"] = TITLE
        data["domains"] = self._domains(req)
        data["message"] = message
        data["ngettext"] = ngettext
        data["_"] = _
        add_stylesheet(req, PACKAGE + '/css/userscriptservernotes.css')
        add_script(req, 'common/js/trac.js')
        add_script(req, 'common/js/wikitoolbar.js')
        return ('usernotes_default.html', data, None)

    def home_url(self, req, domain): 
        return Markup(u'<div><a href="%s">[welcome]</a></div>' % self.base_url(req, domain))
    def base_url(self, req, domain):
        return req.href(web_nav.URL + "/" + web_nav.MAIL + "/" + domain)
    def do_mail(self, req, path):
        username = req.authname
        m = re.match("^/([^/]+)(/.*)?", path)
        if m and username:
            add_stylesheet(req, PACKAGE + '/css/userscriptservernotes.css')
            add_script(req, 'common/js/trac.js')
            domain = m.group(1)
            render = m.group(2)
            base_url = self.base_url(req, domain)
            op = req.args.get("op", "")
            if not op: op = render
            # xx._scripts = _scripts
            if op == "showall":
                return self.do_showall(req, domain)
            elif op == "userlist":
                return self.do_userlist(req, domain)
            elif op == "search":
                return self.do_search(req, domain)
            elif op == "insert":
                return self.do_insert(req, domain)
            elif op == "clear":
                return self.do_clear(req, domain)
            sell = DbNotesMailRequest(self.env, req, domain)
            sell.set_username(username)
            sell.set_base_url(base_url).set_cookie(req.outcookie)
            if op == "import":
                return self.do_import(req, sell)
            elif op == "createtablemail":
                text = u"\n".join(sell.op_createtablemail())
            elif op == "droptablemail":
                text = u"\n".join(sell.op_droptablemail())
            elif op == "showallmail":
                text = u"\n".join(sell.op_showall())
            elif op == "userlistmail":
                text = u"\n".join(sell.op_userlist())
            elif op == "searchmail":
                text = u"\n".join(sell.op_search())
            elif op == "insertmail":
                text = u"\n".join(sell.op_insert())
            elif op == "download":
                text = u"\n".join(sell.op_download())
            else:
                text = sell.op_welcome(op)
            if type(text) is tuple:
                data = text[1]
                data["domains"] = self._domains(req)
                return text
            data = {}
            data["content"] = Markup(text)
            data["domains"] = self._domains(req)
            return "usernotes_default.html", data, None
        else:
            return self.do_default(req, path)

    def _domains(self, req):
        return self.domainlist
    def do_import(self, req, sell):
        created = 0
        current_time = datetime.datetime.now()
        domain = sell._domain
        all2 = sell.all()
        session = context(self.env)
        try:
            for old in all2:
                item = NotesMail()
                item.created_by = req.authname
                item.created_on = current_time
                item.mail_domain = sell._domain 
                item.mail_from = self.to_unicode(old.mail_from)
                item.mail_user = self.to_unicode(old.mail_user)
                item.mail_date = self.to_datetime(old.mail_date)
                item.mail_date = item.mail_date + datetime.timedelta(milliseconds = created)
                item.mail_call = self.to_unicode(old.mail_call)
                item.mail_text = self.to_unicode(old.mail_text)
                item.mail_info = self.to_unicode(old.mail_info)
                item.mimetype = old.mimetype
                item.encrypted = old.encrypted
                session.add(item)
                created += 1
            session.flush()
            return self.do_default(req, "imported %s entries from %s" % (created, sell.database_name())) 
        except Exception, e:
            session.rollback()
            return self.do_default(req, "ERROR: %s" % e)
    def to_datetime(self, old):
        if not old or len(old) < 12 or old.startswith("("):
            now = datetime.datetime(2000,1,1,0,0, tzinfo = localtz) 
            return now 
        if old.startswith("1000"): 
            now = datetime.datetime(2000,1,1,0,0, tzinfo = localtz) 
            return now 
        if old[8] not in string.digits:
            old = old[0:8] + "0000"
        self.log.warning("OLD '%s'", old)
        _ = long(old)
        return datetime.datetime(int(old[0:4]),
                                     int(old[4:6]),
                                     int(old[6:8]),
                                     int(old[8:10]),
                                     int(old[10:12]), 
                                     tzinfo = localtz)
    def color_mail_user(self, mail_user):
        return u"#" + (((u"222" + strU(hash(mail_user)))[-3:]).replace(u"0", u"A").replace(u"1", u"B"))
    def do_clear(self, req, domain):
        deleted = 0
        session = context(self.env)
        for item in session.query(NotesMail).filter_by(mail_domain = domain).all():
            session.delete(item)
            deleted += 1
        session.flush()
        return self.do_default(req, "deleted %s entries" % deleted) 
    def to_unicode(self, text):
        if isinstance(text, unicode):
            return text
        try:
            return unicode(text, "utf-8")
        except:
            return unicode(text, "latin-1")
    def do_userlist(self, req, domain):
        Item = collections.namedtuple("Item", ["mail_user", "mail_date"])
        session = context(self.env)
        q = session.query(NotesMail.mail_user, by.max(NotesMail.mail_date))
        q = q.filter_by(mail_domain = domain)
        q = q.group_by(NotesMail.mail_user).order_by(desc(NotesMail.mail_date))
        datalist = []
        for item in q.all():
            datalist.append(Item(*item))
        message = "found %s entries for %s" % (len(datalist), domain)
        base_url = req.href(web_nav.URL + "/" + web_nav.MAIL + "/" + domain)
        data = {}
        data["base_url"] = base_url
        data["color_mail_user"] = self.color_mail_user
        data["localtz"] = localtz
        data["datalist"] = datalist
        data["title"] = TITLE
        data["domains"] = self._domains(req)
        data["message"] = message
        data["ngettext"] = ngettext
        data["_"] = _
        add_stylesheet(req, PACKAGE + '/css/userscriptservernotes.css')
        add_script(req, 'common/js/trac.js')
        add_script(req, 'common/js/wikitoolbar.js')
        return ('notes_mail_userlist.html', data, None)
    def do_search(self, req, domain):
        mail_user = req.args.get("user", "")
        if not mail_user:
            self.log.info("no 'user' on search")
            req.send_response(400)
            return self.do_default(req, "no 'user' on search")
        data = {}
        data["home_url"] = self.home_url(req, domain)
        data["mail_user"] = mail_user
        session = context(self.env)
        q = session.query(NotesMail.mail_from, NotesMail.mail_user, NotesMail.mail_date,
                                NotesMail.mail_call, NotesMail.mail_text, NotesMail.mail_info,
                                NotesMail.mimetype, NotesMail.encrypted)
        q = q.filter_by(mail_user=mail_user, mail_domain = domain)
        q = q.order_by(desc(NotesMail.mail_date))
        datalist = []
        for item in q.all():
            datalist.append(item)
        message = len(datalist)
        data["datalist"] = datalist
        data["markup_mail_info"] = self.markup_mail_info
        data["markup_mail_text"] = self.markup_mail_text
        data["domains"] = self._domains(req)
        data["title"] = TITLE
        data["domains"] = self._domains(req)
        data["message"] = message
        data["ngettext"] = ngettext
        data["_"] = _
        add_stylesheet(req, PACKAGE + '/css/userscriptservernotes.css')
        add_script(req, 'common/js/trac.js')
        add_script(req, 'common/js/wikitoolbar.js')
        return ('notes_mail_textlist.html', data, None)
    def do_showall(self, req, domain):
        data = {}
        data["home_url"] = self.home_url(req, domain)
        data["mail_user"] = "ALL"
        session = context(self.env)
        q = session.query(NotesMail.mail_from, NotesMail.mail_user, NotesMail.mail_date,
                                NotesMail.mail_call, NotesMail.mail_text, NotesMail.mail_info,
                                NotesMail.mimetype, NotesMail.encrypted)
        q = q.filter_by(mail_domain = domain)
        q = q.order_by(desc(NotesMail.mail_date))
        datalist = []
        for item in q.all():
            datalist.append(item)
        message = len(datalist)
        data["datalist"] = datalist
        data["markup_mail_info"] = self.markup_mail_info
        data["markup_mail_text"] = self.markup_mail_text
        data["domains"] = self._domains(req)
        data["title"] = TITLE
        data["domains"] = self._domains(req)
        data["message"] = message
        data["ngettext"] = ngettext
        data["_"] = _
        add_stylesheet(req, PACKAGE + '/css/userscriptservernotes.css')
        add_script(req, 'common/js/trac.js')
        add_script(req, 'common/js/wikitoolbar.js')
        return ('notes_mail_textlist.html', data, None)
    def markup_mail_info(self, mail_info):
        return Markup(self.span_mail_info(mail_info))
    def span_mail_info(self, mail_info):
        if not mail_info:
            return ""
        info = mail_info.strip()
        if info.startswith("w "):
            return u'<span style="color: red">%s</span>' % esc(info).replace(u"w ", u"w&nbsp;")
        elif info.startswith(u"m "):
            return u'<span style="color: blue">%s</span>' % esc(info).replace(u"m ", u"m&nbsp;")
        elif info.startswith("undefined"):
            return u'<span style="color: #DDD; font-size: xx-small">%s</span>' % esc(info)
        else:
            return '<span style="font-size: xx-small">%s</span>' % esc(info)
    def markup_mail_text(self, mail_text):
        return Markup(self.span_mail_text(mail_text))
    def span_mail_text(self, mail_text):
        if not mail_text:
            return ""
        return u"<p>" + esc(mail_text).strip().replace(u"\n\n", u"</p><p>").replace(u"\n", u"<br />") + u"</p>"
    def do_insert(self, req, domain):
        mail_from = req.args.get("from", "")
        mail_user = req.args.get("user", "")
        import parsedate
        mail_date = parsedate.parse_datetime(req.args.get("date", ""))
        mail_call = req.args.get("call", "")
        mail_text = req.args.get("text", "")
        mail_info = req.args.get("info", "")
        mail_body = req.args.get("body", "")
        mimetype = req.args.get("mimetype", "")
        encrypted = req.args.get("encrypted", "")
        if mail_body:
            mimetype = "text/html"
            mail_text = mail_body            
        if not mail_date:
            req.send_response(400)
            message = u"datetime %s text not understood" % (req.args.get("date", ""))
            self.log.info(message)
            return self.do_default(req, message)
        if not mail_user:
            req.send_response(400)
            message = u"no 'user' on insert %s " % mail_date
            self.log.info(message)
            return self.do_default(req, message)
        session = context(self.env)
        status = ""
        try:
            self.log.info("going to insert %s", mail_user)
            q = session.query(NotesMail)
            q = q.filter_by(mail_from=mail_from, mail_user=mail_user, mail_date=mail_date)
            result = q.count()
            if result > 0:
                self.log.info(u"entry does already exist for %s", strU(mail_user))
                status = u'<div class="status"><span class="statushead">OOPS EXISTS</span>: entry does already exist %s</div>' % esc(result)
            else:
                self.log.info("running sql for %s", mail_user)
                mail = NotesMail(mail_from=mail_from, mail_user=mail_user, mail_date=mail_date,
                                 mail_call=mail_call, mail_text=mail_text, mail_info=mail_info,
                                 mimetype=mimetype, encrypted=encrypted,
                                 mail_domain = domain, 
                                 created_by = req.authname,
                                 created_on = datetime.datetime.now())
                session.add(mail)
                status = u'<div class="status"><span class="statushead">OK SAVED</span>: entry was saved just fine</div>'
            session.flush()
            data = {}
            data["title"] = TITLE
            data["domains"] = self._domains(req)
            data["message"] = Markup(status)
            data["body"] = self.markup_mail_text(mail_text)
            data["ngettext"] = ngettext
            data["_"] = _
            add_stylesheet(req, PACKAGE + '/css/userscriptservernotes.css')
            add_script(req, 'common/js/trac.js')
            add_script(req, 'common/js/wikitoolbar.js')
            return ('notes_mail_insert.html', data, None)
        except Exception, e:
            import traceback
            message = u"FAIL:(12) " + strU(e) + " @ " + traceback.format_exc()
            self.log.error(u"OOPS " + strU(e) + " @ " + traceback.format_exc())
            return self.do_default(req, message)

# =======================================================================

ModelBase = declarative_base()

class System(ModelBase):
    __tablename__ = "system"
    name = Column(String, primary_key=True)
    value = Column(String)

class Mail(ModelBase):
    __tablename__ = "mail"
    mail_from = Column(String, primary_key=True)
    mail_user = Column(String, primary_key=True)
    mail_date = Column(String, primary_key=True)
    mail_call = Column(String)
    mail_text = Column(String)
    mail_info = Column(String)
    mimetype = Column(String)
    encrypted = Column(String)

if __name__ == "__main__":
    from sqlalchemy import create_engine
    engine = create_engine('sqlite:///:memory:', echo=True)
    ModelBase.metadata.create_all(engine) 

xhtml_content = u'text/html; charset=utf8'
xhtml_doctype = (u'<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN"' + "\n"
                 '      "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">')

class DbNotesMailRequest:
    def __init__(self, env, req, domain):
        self.env = env
        self.req = req
        self._domain = domain
        self._cookie = None
        self._base_url = u"/usernotes/mail/%s" % domain
        self._username = None
        self._password = None
        self._engine = None
        self._db_session = None
        self._scripts = []
        self._logg = None
        self.mail_db_version = 2
        self.download_prefix = u"usernotes"
        self.download_extension = u"sqlite"
        self._done_http = False
        self._http = {u'Content-Type' : xhtml_content}
    def domain(self): 
        return self._domain
    def path(self):
        target = os.path.join(self.env.path, u"usernotes")
        if not os.path.isdir(target):
            os.mkdir(target)
        return target
    def database_name(self): 
        name = u"mail.%s.%s.3db" % (self.domain(), self.username)
        return os.path.join(self.path(), name)
    def logfile_name(self):
        name = u"mail.%s.log" % self.domain()
        return os.path.join(self.path(), name)
    def username_logfile_name(self, username):
        name = u"mail.%s.%s.log" % (self.domain(), username)
        return os.path.join(self.path(), name)
    def logg(self):
        if self._logg is None:
            self._logg = logging.getLogger(self.domain())
            self._logg.addHandler(logging.FileHandler(self.logfile_name()))
            self._logg.setLevel(logging.DEBUG)
        return self._logg
    def getvalue(self, name, default=None):
        return self.req.args.get(name, default)
    def set_cookie(self, cookie):
        self._cookie = cookie
        return self
    def get_cookie(self):
        return self._cookie
    def set_base_url(self, base_url):
        self._base_url = base_url
        return self
    def get_base_url(self):
        return self._base_url
    def set_password(self, password):
        self._password = password
        return self
    def get_password(self):
        return self._password
    def set_username(self, username):
        self._username = username
        logg_file = self.username_logfile_name(username)
        self.logg().addHandler(logging.FileHandler(logg_file))
        return self
    def get_username(self):
        return self._username
    username = property(get_username, set_username)    #
    password = property(get_password, set_password)
    base_url = property(get_base_url, set_base_url)
    cookie = property(get_cookie, set_cookie)
    def http(self, name, value):
        self._http[name] = value
    def http_header(self, a=None, b=None):
        if self._done_http: return False
        self._done_http = True
        if isinstance(a, basestring): 
            self.http('Content-Type', str8(a))
        elif type(a) is int:
            self.req.send_response(a) 
        else: 
            pass  # sef.req.send_response(203)
        for name, value in self._http.items():
            self.req.send_header(str8(name), str8(value)),
        # self.req.end_headers()
    #
    def color_mail_user(self, mail_user):
        return u"#" + (((u"222" + strU(hash(mail_user)))[-3:]).replace(u"0", u"A").replace(u"1", u"B"))
    def href_mail_user(self, mail_user):
        return (u'<a href="%s?op=search&user=%s" style="color: %s">%s</a>' 
                % (self.base_url, esc(mail_user),
                   self.color_mail_user(mail_user), esc(mail_user)))
    def span_mail_info(self, mail_info):
        info = mail_info.strip()
        if info.startswith("w "):
            return u'<span style="color: red">%s</span>' % esc(info).replace(u"w ", u"w&nbsp;")
        elif info.startswith(u"m "):
            return u'<span style="color: blue">%s</span>' % esc(info).replace(u"m ", u"m&nbsp;")
        elif info.startswith("undefined"):
            return u'<span style="color: #DDD; font-size: xx-small">%s</span>' % esc(info)
        else:
            return '<span style="font-size: xx-small">%s</span>' % esc(info)
    def span_mail_text(self, mail_text):
        return u"<p>" + esc(mail_text).strip().replace(u"\n\n", u"</p><p>").replace(u"\n", u"<br />") + u"</p>"
    
    def color_notes_user(self, notes_user): return self.color_mail_user(notes_user)
    def href_notes_user(self, notes_user): return self.href_mail_user(notes_user)
    def span_notes_text(self, notes_text): return self.span_mail_text(notes_text)
    
    def home_url(self): 
        return u'<div><a href="%s">[welcome]</a></div>' % self.base_url
    def back_url(self):
        new_url = strU(self.base_url)
        x = new_url.rfind(u"/")
        if x > 0: new_url = new_url[:x]
        return u'<div><a href="%s">[back]</a></div>' % (new_url)
    
    def engine(self):
        if not self._engine:
            engine = create_engine('sqlite:///' + self.database_name(), echo=True)
            self._engine = engine
        return self._engine
    def db(self):
        if not self._db_session:
            self._db_session = create_session(bind=self.engine())
        return self._db_session
    def commit(self):
        pass # self.engine().commit()
        if self._db_session:
            self._db_session.flush()
    def close(self):
        pass # self.engine().close()
        pass # self._engine = None
        if self._db_session:
            self._db_session.close()
            self._db_session = None
    def init_system(self):
        try:
            System.__table__.create(bind=self.engine()) #@UndefinedVariable
        except Exception, e:
            self.logg().debug(u"FAIL:(1) " + strU(e))
            return
    def select_db_version(self, name):
        try:
            q = self.db().query(System.value).filter_by(name=name)
            for version, in q.all():
                self.logg().debug("* %s version = %s" % (name, version))
                return int(version) 
            return 0
        except Exception, e:
            self.logg().info(u"FAIL:(2) " + strU(e))
            self.init_system()
            return 0
    def delete_db_version(self, name):
        try:
            self.db().query(System).filter_by(name=name).delete()
            self.commit()
            return True
        except Exception, e:
            self.logg().debug(u"FAIL:(3) " + strU(e))
            self.init_system()
            return None
    def insert_db_version(self, name, value):
        try:
            self.init_system()
            self.engine().execute("INSERT OR REPLACE INTO system VALUES (?,?)", (name, value))
            return value
        except Exception, e:
            self.logg().debug(u"FAIL:(4) " + strU(e))
            raise
            return None
    def op_createtablemail(self):
        self.http_header(xhtml_content)
        yield xhtml_doctype
        yield u'<div class="body">' + u"%s<h3>CREATE TABLE MAIL</h3>" % self.home_url()
        try:
            sure = self.getvalue("sure", "")
            if sure:
                yield self.createtablemail()
                self.close()
            else:
                yield u"IGNORED, you need to kick the checkbox to be 'sure'"
        except Exception, e:
            yield u"FAIL:(7) " + strU(e)
        yield u"</div>"
    def createtablemail(self):
        result = u""
        version = self.select_db_version('mail')
        if not version:
            Mail.__table__.create(bind=self.engine()) #@UndefinedVariable
            result = u"OK, done the CREATE TABLE MAIL"
        elif version == 1:
            add_cols = [ "mimetype", "encrypted" ]
            for col in add_cols:
                self.db().execute("ALTER TABLE mail ADD COLUMN %s" % col) 
            self.commit()
            result = u"OK, done the UPGRADE TABLE MAIL"
        self.insert_db_version('mail', 2)
        self.commit()
        return result
    def op_droptablemail(self):
        self.http_header(xhtml_content)
        yield xhtml_doctype
        yield u'<div class="body">' + "%s<h3>DROP TABLE MAIL</h3>" % self.home_url()
        try:
            sure = self.getvalue("sure", "")
            if sure:
                self.delete_db_version('mail')
                Mail.__table__.drop(bind=self.engine()) #@UndefinedVariable
                yield u"OKAY, done the DROP TABLE MAIL"
                self.commit()
                self.close()
            else:
                yield u"IGNORED, you need to kick the checkbox to be 'sure'"
        except Exception, e:
            yield "FAIL:(8) " + strU(e)
        yield "</div>"
    def op_showall(self):
        self.http_header(xhtml_content)
        yield xhtml_doctype
        yield u'<div class="body">' + "%s<h3>SHOWALL</h3>" % self.home_url()
        # mail_user = self.getvalue("user", "")
        try:
            if self.select_db_version('mail') < self.mail_db_version:
                yield u"<div>%s</div>" % esc(self.createtablemail())
            q = self.db().query(Mail).order_by(desc(Mail.mail_date))
            yield "<table>"
            for item in q.all():
                yield u'<tr valign="top">'
                yield u"<td>%s</td>" % esc(item.mail_from)
                yield u"<td>%s</td>" % self.href_mail_user(item.mail_user)
                yield u"<td>%s</td>" % esc(self.str_localtime_date(item.mail_date, "?"))
                yield u"<td>%s</td>" % esc(item.mail_call)
                yield u'</tr><tr valign="top">'
                yield u"<td>%s</td>" % self.span_mail_info(item.mail_info)
                yield u'<td colspan="3">%s</td>' % self.span_mail_text(item.mail_text)
                yield u"</tr>"
            yield u"</table>"
            self.close()
        except Exception, e:
            yield "FAIL:(9) " + esc(e)
            self.logg().error(u"OOPS " + strU(e))
        yield "</div>"
    def op_userlist(self):   
        self.http_header(xhtml_content)
        yield xhtml_doctype
        yield u'<div class="body">' + "%s<h3>USERLIST</h3>" % self.home_url()
        # mail_user = self.getvalue("user", "")
        try:
            q = self.db().query(Mail.mail_user, by.max(Mail.mail_date))
            q = q.group_by(Mail.mail_user).order_by(desc(Mail.mail_date))
            result = q.all()            
            yield u"<table>"
            for mail_user, mail_date in result:
                try:
                    # mail_user = unicode(mail_user, "utf-8").encode("utf-8")
                    # mail_date = unicode(mail_date, "utf-8").encode("utf-8")
                    yield u"<tr>"
                    yield u'<td>%s</td>' % self.href_mail_user(mail_user)
                    yield u'<td>%s</td>' % esc(self.str_localtime_date(mail_date, "?"))
                    yield u'<td><small style="color: #bbb">%s</small></td>' % self.color_mail_user(mail_user)
                    yield u"</tr>"
                except:
                    import traceback
                    yield u"<pre>%s</pre>" % esc(traceback.format_exc())
            yield u"</table>"
            self.close()
        except Exception, e:
            import traceback
            yield u"FAIL:(10) %s @ %s " % (strU(e), traceback.format_exc())
            self.logg().error(u"OOPS %s @ %s" % (strU(e), traceback.format_exc()))
        yield u"</div>"
    def op_search(self):   
        self.http_header(xhtml_content)
        mail_user = self.getvalue("user", "")
        if not mail_user:
            self.http_header(400, "no 'user' on search")
            yield u"no 'user' on search"
            self.logg().info("no 'user' on search")
            return
        yield xhtml_doctype
        yield u'<div class="body">' + "%s<h3>SEARCH %s</h3>" % (self.home_url(), esc(mail_user))
        try:
            if self.select_db_version('mail') < self.mail_db_version:
                yield u"<div>DB: %s</div>" % esc(self.createtablemail())
            q = self.db().query(Mail.mail_from, Mail.mail_user, Mail.mail_date,
                                Mail.mail_call, Mail.mail_text, Mail.mail_info,
                                Mail.mimetype, Mail.encrypted)
            q = q.filter_by(mail_user=mail_user)
            q = q.order_by(desc(Mail.mail_date))
            result = q.all()
            yield u'<table class="resulttable">'
            for mail_from, mail_user, mail_date, mail_call, mail_text, mail_info, mimetype, encrypted in result:
                try:
                    yield u'<tr valign="top">'
                    yield u'<td width="1%%">%s</td>' % esc(mail_from)
                    yield u'<td width="1%%">%s</td>' % self.href_mail_user(mail_user)
                    yield u'<td width="1%%">%s</td>' % esc(self.str_localtime_date(mail_date, "?"))
                    yield u'<td>%s</td>' % esc(mail_call)
                    yield u'<td></td>'
                    yield u'</tr><tr valign="top">'
                    yield u'<td>%s</td>' % (self.span_mail_info(mail_info))
                    if encrypted:
                        html = u'<div encrypted="%s" type="%s">%s</div>' % (encrypted, mimetype, mail_text)
                        yield u'<td colspan="4">%s</td>' % (html)
                    elif mimetype in [ "html", "text/html", "xml", "text/xml" ]:
                        html = u'<div type="%s">%s</div>' % (mimetype, mail_text)
                        yield u'<td colspan="4">%s</td>' % (html) 
                    else:
                        yield u'<td colspan="4">%s</td>' % self.span_mail_text(mail_text)
                    yield u"</tr>"
                except:
                    import traceback
                    yield u"<pre>%s</pre>" % esc(traceback.format_exc())
            yield u"</table>"
            self.close()
        except Exception, e:
            yield u"FAIL:(11) " + strU(e)
            self.logg().error(u"OOPS " + strU(e))
        yield u"</div>"
    def op_insert(self):                           
        mail_from = self.getvalue("from", "")
        mail_user = self.getvalue("user", "")
        import parsedate
        mail_datetime = parsedate.parse(self.getvalue("date", ""))
        mail_date = self.localtime_date(str(mail_datetime))
        mail_call = self.getvalue("call", "")
        mail_text = self.getvalue("text", "")
        mail_info = self.getvalue("info", "")
        mail_body = self.getvalue("body", "")
        mimetype = self.getvalue("mimetype", "")
        encrypted = self.getvalue("encrypted", "")
        if mail_body:
            mimetype = "text/html"
            mail_text = mail_body            
        if not mail_datetime:
            self.http_header(400, "datetime text not understood")
            yield u"datetime %s text not understood" % (self.getvalue("date", ""))
            self.logg().info("datetime %s text not understood" % (self.getvalue("date", "")))
            return
        if not mail_user:
            self.http_header(400, "no 'user' on insert")
            yield u"no 'user' on insert %s " % mail_datetime
            self.logg().info("no 'user' on insert")
            return
        self.http_header(xhtml_content)
        yield xhtml_doctype
        yield u'<div class="body">' + "%s<h3>INSERT</h3>" % self.home_url()
        try:
            if self.select_db_version('mail') < self.mail_db_version:
                yield u"<div>DB: %s</div>" % esc(self.createtablemail())
            self.logg().info("going to insert %s", mail_user)
            result = self.db().query(Mail).filter_by(mail_from=mail_from, mail_user=mail_user, mail_date=mail_date).count()
            if result > 0:
                self.logg().info(u"entry does already exist for %s", strU(mail_user))
                yield u'<div class="status"><span class="statushead">OOPS EXISTS</span>: entry does already exist %sx</div>' % result
            else:
                self.logg().info("running sql for %s", mail_user)
                mail = Mail(mail_from=mail_from, mail_user=mail_user, mail_date=mail_date,
                            mail_call=mail_call, mail_text=mail_text, mail_info=mail_info,
                            mimetype=mimetype, encrypted=encrypted)
                self.db().add(mail)
                yield  u'<div class="status"><span class="statushead">OK SAVED</span>: entry was saved just fine</div>'
            self.commit()
            self.logg().info("done - now generate mail_text as response")
            yield strU(mail_text)
            self.close()
            self.logg().info("close and exit")
        except Exception, e:
            import traceback
            yield u"FAIL:(12) " + strU(e) + " @ " + traceback.format_exc()
            self.logg().error(u"OOPS " + strU(e) + " @ " + traceback.format_exc())
        yield u"</div>"
    def op_download(self):
        db_name = self.database_name()
        if not os.path.isfile(db_name):
            msg = u"%s has no database here" % (self.username)
            self.http_header(404, msg)
            yield msg ; self.logg().info(msg)
            return
        downloadname = self.getvalue("downloadname", "")
        if not downloadname:
            self.http_header(400, "no 'downloadname' on download")
            yield u"no 'downloadname' on download"
            self.logg().info("no 'downloadname' on download")
            return
        content_type = u"application/x-sqlite3"
        content_disposition = u"attachment; filename=%s" % (downloadname)
        content_length = os.path.getsize(db_name)
        try:
            f = open(db_name)
            self.http("Content-Disposition", content_disposition)   
            self.http("Content-Length", content_length)
            self.http("Content-Type", content_type)   
            self.http_header()
            yield f.read(),
            f.close()
        except Exception, e:
            self.http_header(404, "could not open the database")
            self.logg().info(u"downloading " + strU(db_name) + u": " + strU(e))
    def op_welcome(self, op=""):
        data = {}
        data["username"] = self.username
        data["str_localtime_date"] = self.str_localtime_date
        data["downloadname"] = self.downloadname()
        return "notes_mail_index.html", data, None
    def all(self):
        # return self.db().query(Mail).all()
        # => problem with old imports being non-utf8
        import sqlite3
        db = sqlite3.connect(self.database_name())
        db.text_factory = str
        stmt = db.cursor()
        for row in stmt.execute("SELECT count(*) FROM mail"):
            self.logg().info("count = %s", row[0])
        all1 = []
        all2 = []
        for row in stmt.execute("SELECT mail_from, mail_user, mail_date FROM mail WHERE mail_date is not null"):
            all1.append({ "mail_from" : row[0], "mail_user" : row[1], "mail_date" : row[2]}) # primary key
            self.logg().info("got %s", row[2])
        for entry in all1:
            sql = "SELECT mail_from, mail_user, mail_date, mail_call, mail_text, mail_info, mimetype, encrypted"
            sql += " FROM mail WHERE "
            sql += " AND ".join([" %s = '%s'" % (key, value.replace("'", "''")) for key, value in entry.items()])
            self.logg().info("sql %s", sql)
            for row in stmt.execute(sql):
                item = Mail()
                item.mail_from = row[0]
                item.mail_user = row[1]
                item.mail_date = row[2]
                item.mail_call = row[3]
                item.mail_text = row[4]
                item.mail_info = row[5]
                item.mimetype = row[6]
                item.encrypted = row[7]
                all2 += [ item ]
                self.logg().info("row %s", item.mail_date)
        stmt.close()
        db.close()
        return all2
    #  ====================================================================
    #  ====================================================================
    #  ====================================================================
    def downloadname(self):
        return ("%s-%s-%s-%s.%s" % 
                    (self.download_prefix, self.username, self.domain(),
                     self.localtime_date(), self.download_extension))
    def localtime_date(self, inputdate=None):
        if inputdate:
            val = inputdate.replace("-", "").replace(":", "").replace(".", "")
            if len(val) < 3 * 4: val += " " * (3 * 4 - len(val))
            return val
        return strU(strftime("%Y%m%d%H%M", localtime()))
    def str_localtime_date(self, inputdate=None, default=None):
        if not inputdate: inputdate = default
        val = self.localtime_date(inputdate)
        if len(val) > 10:
            return val[0:4] + "-" + val[4:6] + "-" + val[6:8] + "." + val[8:10] + ":" + val[10:]
        return val

if __name__ == "__main__":
    from sqlalchemy import create_engine
    engine = create_engine('sqlite:///:memory:', echo=True)
    ModelBase.metadata.create_all(engine)