Source

drink / drink / __init__.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
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
from __future__ import absolute_import, with_statement
"""
Drink!

"""
__all__ = ['get_object',
 'classes',
 'update_property',
 'add_upload_handler',
 'request', 'response',
 'Page', 'ListPage'
 'omni', 'bytes2human',
 'db', 'unauthorized',
 'make_app', 'init']
# imports + basic configuration

import os
import logging
logging.basicConfig()
import signal
signal.signal(signal.SIGPIPE, signal.SIG_IGN)
dbg_in_env = 'DEBUG' in os.environ
if dbg_in_env:
    logging.getLogger().setLevel(logging.NOTSET)
else:
    logging.getLogger().setLevel(logging.WARNING)

log = logging.getLogger('core')

from drink.config import config, BASE_DIR
import bottle
from hashlib import sha1
try:
    from json import loads
except ImportError:
    from simplejson import loads

try:
    import pyjaco
except ImportError:
    log.info("Can't find pyjaco ( http://pyjaco.org/ )")
else:
    #: compile python to javascript using `Pyjaco <http://pyjaco.org/>`_
    def js(text):
        c = pyjaco.Compiler()
        c.append_string(text)
        return str(c)


#: All kind of drink objects as a ``{"name": Page_class}`` mapping.

classes = {}
if config.get('server', 'templates'):
    bottle.TEMPLATE_PATH.append(config.get('server', 'templates').strip())
bottle.TEMPLATE_PATH.append(os.path.join(BASE_DIR, 'templates'))
STATIC_PATH = config.get('server', 'static_folder') or os.path.abspath(os.path.join(BASE_DIR, "static"))
BASE_DIR = os.path.dirname(STATIC_PATH.rstrip(os.path.sep))
import drink_defaults
DEFAULTS_DIR = os.path.dirname(drink_defaults.__file__)
ORIG_DB_PATH = os.path.abspath(os.path.join(DEFAULTS_DIR, 'database'))

DB_PATH = config.get('server', 'database') or ORIG_DB_PATH
if not DB_PATH.endswith(os.sep):
    DB_PATH += os.sep

#: update some property
def update_property(pklass, klass, name, value):
    """ Update one page property (dicts) """
    name = '_'+name
    d = getattr(pklass, name).copy()
    d.update(value)
    setattr(klass, name, d)

# auto-guess & set datadir in case of inchanged default
log.debug("Using DB informations from %s", DB_PATH)
def _fix_datadir(txt, zeo_fname=None):
    try:
        i = txt.index('%define DATADIR database\n')
    except ValueError:
        i = -1
    if i >= 0:
        txt[i] = '%%define DATADIR %s\n'%DB_PATH
    if zeo_fname:
        for idx, line in enumerate(txt):
            if ' zeo.conf' in line:
                txt[idx] = line.replace("zeo.conf", zeo_fname)
    return ''.join(txt)

try:
    DB_CONFIG = _fix_datadir(open(os.path.join(DB_PATH, "zodb.conf")).readlines())
except IOError:
    import shutil
    try:
        os.makedirs(os.path.join(DB_PATH, 'blobs'))
        os.makedirs(os.path.join(DB_PATH, 'cache'))
    except OSError:
        pass
    shutil.copy( os.path.join(ORIG_DB_PATH, 'zodb.conf'), os.path.join(DB_PATH, 'zodb.conf'))
    shutil.copy( os.path.join(ORIG_DB_PATH, 'zeo.conf'), os.path.join(DB_PATH, 'zeo.conf'))
    shutil.copy( os.path.join(ORIG_DB_PATH, 'blobs', '.layout'), os.path.join(DB_PATH, 'blobs', '.layout'))
    DB_CONFIG = _fix_datadir(open(os.path.join(DB_PATH, "zodb.conf")).readlines())

# Import main modules used + namespace setup

# http
from bottle import route, static_file, request, response, redirect as rdr, abort
# templating
from urllib import unquote

#: A json serialization function
dumps = bottle.JSONPlugin().json_dumps

def bytes2human(num):
    ''' Converts an integer or float value to human-readable string

    :arg num: Number of bytes
    :type num: `int` or `float`
    :returns: a short display string containing the value + the "best fitting" unit
    :rtype: `unicode`
    '''
    for u in ('k', 'M', 'G'):
        num /= 1000.0
        if num < 951:
            break
    return u'%.1f %s'%(num, u)

def omni(txt):
    ''' Converts any text form to unicode text

    :arg txt: the "unknown state" text
    :type txt: `unicode` or `str`
    :returns: an "http" unquoted unicode string
    :rtype: `unicode`
    '''
    if isinstance(txt, unicode):
        return txt
    else:
        txt = unquote(txt)
        try:
            return txt.decode('utf-8')
        except UnicodeError:
            return txt.decode('latin1')

def init():
    """ Re-initialize drink's database """
    from drink.objects.finder import reset
    reset()
    with db as root:
        root.clear()
        transaction.commit()

        from .objects import users as obj

        class FakeId(object):
            user = None

            def access(self, obj):
                return 'rowat'

        request.identity = FakeId()
        groups = root['groups'] = obj.GroupList('groups', '/')
        users = root['users'] = obj.UserList('users', '/')
        root['groups']['users'] = obj.Group('users', '/groups/')

        admin = obj.User('admin', '/users/')
        request.identity.user = admin

        anon = obj.User('anonymous', '/users/')

        groups.owner = admin
        groups.read_groups = set()
        groups.write_groups = set()

        users.owner = admin
        users.read_groups = set()
        users.write_groups = set()
        users.min_rights = 't'

        root['users']['anonymous'] = anon
        root['users']['admin'] = admin

        admin.set_field('password', 'admin')
        admin.surname = "BOFH"
        admin.name = "Mr Admin"
        admin.owner = admin

        anon.groups = set()
        anon.owner = admin

        users = root['groups']['users']
        users.owner = admin
        users.read_groups = set()
        users.write_groups = set()
        users.min_rights = 't'

        settings = Settings('settings', '/')
        settings.server_backend = config.get('server', 'backend')
        settings.server_port = int(config.get('server', 'port'))
        settings.server_address = config.get('server', 'host')
        settings.debug_framework = config.get('server', 'debug')
        settings.active_objects = set(config.items('objects'))

        root['settings'] = settings

        root['pages'] = Page('pages', '/')

        # deploy layout
        for pagename, name in config.items('layout'):
            try:
                root[pagename] = classes[ name ](pagename, '/')
            except Exception, e:
                log.error('Unable to create %r element with type %r (%r)\nexpect problems, try to enable this object type next time.'%(pagename, name, e))

        mdown = classes['Web page (markdown)']('help', '/pages/')
        help = os.path.abspath(os.path.join(DEFAULTS_DIR, "HELP.md"))
        mdown.content = open(help).read()
        mdown.owner = admin
        mdown.min_rights = 'r'
        root['pages']['help'] = mdown

# Setup db
reset_required = False
try:
    from .zdb import Database, DataBlob, Model, transaction, PersistentList as List
    PERSISTENT_STORAGE = True
    log.info("Enabling persistent storage, using ZODB")
except ImportError:
    log.warning("Not enabling persistent storage, using dumb db")
    PERSISTENT_STORAGE = False
    from .dumbdb import Database, DataBlob, Model, transaction, PersistentList as List

#: The database object, prefer using :func:`drink.get_object` instead

db = Database(bottle.app(), DB_CONFIG)

# Load Basic objects
from .objects.generic import Page, ListPage, Settings, default_view
from .objects import classes as obj_classes, get_object, init as init_objects

def add_upload_handler(ext, obj_name):
    """ Add an opload handler into drink upload system

    :arg ext: extension to register
    :type ext: `str` or `list` of `str`
    :arg obj_name: object name, will be looked up via :obj:`drink.classes`
    :type obj_name: `str`
     """

    if isinstance(ext, basestring):
        ext = [ext]
    for e in ext:
        Page.upload_map[e] = obj_name

# Finally load all the objects
init_objects()
classes.update(obj_classes)
del init_objects, obj_classes

def unauthorized(message='Action NOT allowed', code=401):
    ''' Returns proper value to indicate the user has no access to this ressource

    :arg message: Message to show to the user
    :type message: `unicode` or `str`
    :arg code: HTTP error code, defaults to ``401``
    :type code: int
    '''
    if request.identity:
        return {'error': True, 'message': message, 'code': code}
    else:
        return rdr('/login?from='+request.path)

#import cgi
#def escape(text):
#    """ Escapes the given string """
#    # TODO: in python3, use html.escape
#    assert isinstance(text, unicode)
#    return cgi.escape(text).encode('ascii', 'xmlcharrefreplace')

# Declare "drink" wsgi loader
class DrinkServer(bottle.ServerAdapter):
    """ Drink-flavored bottle runner.
    Will try gevent, paste, bjoern >=1.2, rocket, fapws3 or wsgiref (in this order)
    """
    adapters = [bottle.GeventServer, bottle.PasteServer,
        bottle.RocketServer, bottle.FapwsServer, bottle.WSGIRefServer]

    def run(self, handler):
        adapters = list(self.adapters)

        try:
            bjoern_req_version = (1, 2, 0)
            import bjoern
        except ImportError:
            log.info("You can try installing bjoern >= %s", '.'.join(str(x) for x in bjoern_req_version))
        else:
            if bjoern.version >= bjoern_req_version:
                adapters.insert(1, bottle.BjoernServer)


        for sa in adapters:
            try:
                log.warning("* Trying %s"%sa.__name__)
                return sa(self.host, self.port, **self.options).run(handler)
            except ImportError:
                pass

bottle.server_names['drink'] = DrinkServer

# Real code starts here

class Authenticator(object):
    """ Authentication class, handles user's identity """

    __slots__ = ['user', 'success', 'session', 'groups', 'admin', 'id']

    def __init__(self):
        self.session = session = bottle.request.environ.get('beaker.session')
        log.debug('session = %r', self.session)
        logged_in = session.get('logged_in', '')
        log.debug('logged_in = %r', logged_in)
        if logged_in:
            self.user = db.db['users'][session['login']]
            ok = self.user.password == logged_in
            if not ok:
                self.user = None
            self.success = ok
        else:
            self.success = False

        if self.success:
            #: set of current user's groups
            self.groups = self.user.groups.copy()
            self.groups.add('users')
            #: is the user an admin ?
            self.admin = 'admin' in self.groups or self.user.id == 'admin'
        else:
            self.user = db.db['users']['anonymous']
            self.admin = False
            self.groups = set()

        self.groups.add('anonymous')

        #: `id` of the user (Current :data:`~drink.objects.users.User.id`)
        self.id = self.user.id

    def access(self, obj):
        """ Returns a string describing possible access to `obj`

        :arg obj: the object you want to inspect access
        :type obj: any Drink-stored object
        :returns: a string componed of single-letter symbols
        :rtype: str

        String is a combination of:
            :o: owner
            :w: write
            :r: read
            :a: add / append
            :t: traverse (access sub-content but don't imply read access)
        """

        groups = self.groups
        rights = ''

        if self.admin or self.id == obj.owner.id:
            rights = 'owart'
        elif groups.intersection(obj.write_groups):
            rights = 'wart'
        elif self.success and 'users' in obj.write_groups:
            rights = 'wrt'
        elif groups.intersection(obj.read_groups):
            rights = 'rt'

        return rights+obj.min_rights

    def __nonzero__(self):
        return self.success


# Root routing functions

@route('/')
def main_index():
    rdr('/pages/')

@route('/static/:filename#.*#')
def server_static(filename):
    # TODO: add authentication filter here ?
    return static_file(filename, root=os.path.join(BASE_DIR, 'static'))

@route("/struct", method=['GET', 'POST'])
def login_struct():
    return {}

@route("/actions", method=['GET', 'POST'])
def login_actions():
    return []

@route("/login", method=['GET', 'POST'])
def log_in():
    request.identity = Authenticator()
    if request.forms.get('login_name', ''):
        session = request.identity.session
        session['logged_in'] = sha1(request.forms.get('login_password', '')).hexdigest()
        session['login'] = request.forms.get('login_name', '')
        log.debug('LOGGING-IN! session=%r', session)
        session.save()
        return rdr(request.params.get('from', '/'))
    else:
        html='''
        <h1>Connect to drink</h1>
        <form name="login_form" id="login_form" class="autovalidate" action="/login" method="post">
            <div class="label"><label for="ilogin">Authenticate as:</label></div>
            <div><input type="text" class="required" name="login_name" id="ilogin" /></div>
            <div class="label"><label for="ipasswd">Password:</label></div>
            <div><input type="password" class="required" name="login_password" id="ipassword" /></div>
            <div><input type="hidden" name="from" value="%s" /></div>
            <div><input class="submit" type="submit" value="Log in!"/></div>
        </form>

        '''%request.params.get('from', '/')
        return default_view(db.db['pages'], page='main.html', html=html, classes={}, no_auth=True)


@route("/logout", method=['GET', 'POST'])
def log_out():
    log.debug('LOGGING-OUT!')
    session = bottle.request.environ.get('beaker.session')
    session['logged_in'] = ''
    session.save()
    return rdr('/')

# generic dispatcher method
@route("/:objpath#.+#", method=['GET', 'POST', 'PUT', 'DELETE'])
def glob_index(objpath="/"):
    request.identity = Authenticator()
    try:
        o = get_object(db.db, objpath)
    except AttributeError, e:
        return abort(404, "%s not found"%objpath)

    if callable(o):
        o = o()

    t = type(o)

    if t == dict:
        if not request.is_ajax:
            if 'redirect' in o:
                return rdr(omni(o['redirect']).encode('utf-8'))
            if 'error' in o:
                return abort(o['code'], o['message'])
        response.content_type = "application/json"
        return dumps(o)
    elif hasattr(o, 'drink_name'): # isinstance(o, 'Model') but more implicit
        try:
            return getattr(o, o.default_action)()
        except AttributeError:
            o = o[o.default_action]
            return getattr(o, o.default_action)()
    elif t in (list, tuple):
        response.content_type = "application/json"
        return dumps(o)
    return o

def fake_authentication():
    def unauthorized(message='Action NOT allowed', code=401):
        print("UNAUTHORIZED: %r [%d]"%(message, code))
    globals()['unauthorized'] = unauthorized
    bottle.request.environ = dict()
    bottle.request.environ['beaker.session'] = s = os.environ.copy()
    s['password'] = s['login'] = s['logged_in'] = 'admin'
    admin = db.db['users']['admin']
    request.identity = Authenticator()
    request.identity.user = admin

def startup():
    """ Starts drink application """
    import sys

    try:
        import setproctitle
    except ImportError:
        log.warning("Unable to set process' name, easy_install setproctitle, if you want it.")
    else:
        setproctitle.setproctitle('drink')

    # handle commands
    # TODO: create "update" command
    if len(sys.argv) == 2 and sys.argv[1] == "help":
        print """
Drink help

commands:
    make    : make a new drink project
    start   : start all required servers
    run     : starts the server
    db      : starts the database server
    stopdb  : stops the database server
    init    : reset database
    pack    : pack database (more compact/faster)
    rebuild : EXPERIMENTAL, will try to convert & clean an old database to newer format
    export  : EXPERIMENTAL, will try to dump all the data into the given folder
    debug   : run a debugger after loading
    help    : this help :)

Without any argument, it will just run the server.
if DEBUG environment variable is set, it will start in debug mode.
        """
    elif len(sys.argv) == 2 and sys.argv[1] == "init":
        init()
        db.pack()
    elif len(sys.argv) == 2 and sys.argv[1] in ("run", "db", "start"):
        if sys.argv[1] != "run":
            fname = os.path.join(DB_PATH, 'zeo.conf')
            log.debug('fixing %r', fname)
            new_conf = _fix_datadir(open(fname).readlines(), fname)
            open(fname, 'w').write(new_conf)
            cmd = 'zeoctl -C %s start'%(fname)
            os.system(cmd)
        if sys.argv[1] != "db":
            host = config.get('server', 'host')
            port = int(config.get('server', 'port'))
            app = make_app(full=True)
            bottle.run(app=app, host=host, port=port, reloader=debug, server='wsgiref' if debug else config.get('server', 'backend'))
    elif len(sys.argv) == 2 and sys.argv[1] == "stopdb":
        cmd = "zeoctl -C %s stop"%os.path.join(DB_PATH, 'zeo.conf')
        print(cmd)
        os.system(cmd)
    elif len(sys.argv) == 2 and sys.argv[1] == "make":
        def inp(txt):
            return raw_input(txt+': ').strip()

        import shutil
        import drink
        import drink_defaults

        fold = inp('Project folder')

        if os.path.exists(fold):
            shutil.rmtree(fold)

        # fresh copy
        os.mkdir(fold)

        fold = os.path.abspath(fold)

        for project_fold, subs in (
            [ os.path.dirname(drink_defaults.__file__), None],
            [ os.path.join(os.path.dirname(drink.__file__)), ['static', 'templates']],
            ):
            for src in subs or os.listdir(project_fold):
                f = os.path.join(project_fold, src)
                if os.path.isdir(f):
                    if fold.endswith('_'):
                        os.symlink(f, os.path.join(fold, src))
                    else:
                        shutil.copytree(f, os.path.join(fold, src))

        cust = inp('Additional python package with drink objects\n(can contain dots)')
        host = inp('Ip to use (just ENTER to allow all)') or '0.0.0.0'
        port = inp('HTTP port number (ex: "80"), by default %s:5000 will be used'%host) or '5000'
        print "Objects to activate:"
        objs = [
            ('a gtd-like tasklist', 'tasks'),
            ('a wiki-like web page in markdown format', 'markdown'),
            ('a tool to find objects in database', 'finder'),
            ('a filesystem proxy, allow sharing of arbitrary folder or static websites', 'filesystem'),
            ('a simple but powerful spreadsheet', 'spreadsheet'),
        ]
        objects = []
        for o in objs:
            #ans = inp('Activate %s, %s (y/N)'%(o[1], o[0]))
            ans = 'y'
            print("%s : %s"%(' - '.join(o), ans))
            if ans.lower() == 'y':
                objects.append(o[1]+'=')

        layout = []
        k = classes.keys()
        while True:
            name = inp('Additional root item name (just ENTER to finish)')
            if not name:
                break
            for i, n in enumerate(k):
                print "%2d - %s"%(i, n)
            idx = int(inp('Select the desired type index'))
            layout.append('%s = %s'%(name, k[idx]))
        conf = """[server]
database = %s%sdatabase
objects_source = %s
templates = %s
static_folder = %s
host = %s
port = %s


[objects]
%s

[layout]
pages = Folder index
search = Finder
%s
"""%(fold, os.path.sep, cust,
        os.path.abspath(os.path.join(fold, 'templates')),
        os.path.abspath(os.path.join(fold, 'static')),
        host, port,
        '\n'.join(objects),
        '\n'.join(layout),
        )
        open( os.path.join(fold, 'drink.ini'), 'w' ).write(conf)
        conf = """#!/bin/sh
SOCK_DIR="/tmp"
cat << EOF
Example of nginx configation:
upstream drink {
    ip_hash;
    server unix:${SOCK_DIR}/uwsgi.sock;
}
location / {
    uwsgi_pass drink;
    include uwsgi_params;
}
EOF

if [ ! -z "$VIRTUAL_ENV" ] ; then
    export PYTHONHOME=$VIRTUAL_ENV
fi

export PYTHONPATH="${PWD}:%(proj)s:${PYTHONPATH}"

cd "%(proj)s"

http='--http %(host)s:%(port)s'
sock="-s ${SOCK_DIR}/uwsgi.sock -C 666"
stats="--stats ${SOCK_DIR}/stats.socket"
stats='' # disable stats

zeoctl -C database/zeo.conf start

exec uwsgi -p 1 $sock $http $stats --module 'drink:make_app()'
"""%dict(proj=fold, host=host, port=port)
        open( os.path.join(fold, 'start_uwsgi'), 'w' ).write(conf)
        os.chmod(os.path.join(fold, 'start_uwsgi'), 0777)
        if cust.strip():
            try:
                __import__(cust)
            except ImportError:
                cust_dir = os.path.join(fold, cust.strip())
                os.mkdir(cust_dir)
                open(os.path.join(cust_dir, '__init__.py'), 'w')
        print """Project created successfuly.

You can now go into the %s folder and run

- drink db (to start the database daemon)
- drink run (to start the web server)

If you run with DEBUG=1 in environment, templates and python code should reload automatically when changed.
For static files changes, no restart is needed.
        """%fold
    elif len(sys.argv) == 2 and sys.argv[1] == "pack":
        from drink.objects import finder
        finder.init()
        finder.indexer.optimize()
        db.pack()
        print "packed."

    elif len(sys.argv) == 2 and sys.argv[1] == "rebuild":

        from .zdb import Blob

        if not 'settings' in db.db:
            # TODO: request.identity.user = admin
            fake_authentication()
            settings = Settings('settings', '/')
            settings.server_backend = config.get('server', 'backend')
            db.db['settings'] = settings

        objs = list(db.db['pages'].values())
        objs.extend(db.db['users'].itervalues())
        for o in objs:
            try:
                log.info("+%r", o.id)
            except Exception, e:
                import pdb; pdb.set_trace()

            for k, v in o.iteritems():
                k2 = omni(k)
                k3 = omni(v.id)
                try:
                    del o[k]
                except KeyError:
                    pass
                try:
                    del o[k2]
                except KeyError:
                    pass

                v.id = k3
                o[v.id] = v

            try:
                o.reset_items()
            except AttributeError:
                pass

            if not getattr(o, '_no_scan', None):
                objs.extend(o.values())

            f_set = set(('path', 'description', 'id', 'title', 'mime'))

            broken_content = getattr(o, 'content_name', '').endswith('.blob') and 'blobs' in getattr(o, 'content_name', '')

            for name, caster in o.editable_fields.iteritems():
                v = caster.get(o, name)
                if isinstance(v, DataBlob) and broken_content:
                    cur_data = v.open().read()
                    if not cur_data:
                        log.error("FIXING BROKEN BLOB")
                        inp = open(o.content_name, 'rb')
                        out = v.open('w')
                        sz = 2**20
                        while True:
                            data = inp.read(sz)
                            if not data:
                                break
                            out.write(data)
                        inp.close()
                        out.close()
                        os.unlink(o.content_name)
                        o.set_field(name, v)
                        o.content_name = o.title
                elif isinstance(v, Blob):
                    blob = DataBlob(v)
                    setattr(o, name, blob)
                else:
                    try:
                        o.set_field(name, v)
                        f_set.discard(name)
                    except AttributeError:
                        log.error("Could not refresh %r on %r", name, o.id)
                    except (UnicodeError, TypeError), e:
                        import pdb; pdb.set_trace()
            for field in f_set:
                try:
                    _d = getattr(o, field)
                    if isinstance(_d, basestring):
                        setattr(o, field, omni(_d))
                except AttributeError:
                    log.error("Could not set %r on %r", field, o.id)
                except (UnicodeError, TypeError), e:
                    import pdb; pdb.set_trace()

            try:
                transaction.commit()
            except ValueError:
                log.error("** cannot commit **")

        log.info("Whooshing...")
        for x in db.db['search'].rebuild():
            log.info(x.strip())

    elif len(sys.argv) == 3 and sys.argv[1] == "import":
        fake_authentication()
        base = sys.argv[2]
        c_map = {}
        all_objs = []
        log.info("Importing %s", base)
        for root, dirs, files in os.walk(base):
            content = [f for f in files if f.startswith('!content_')]
            if len(content) == 1:
                data = loads(open(os.path.join(root, content[0])).read())
                if data:
                    rp = data['rootpath']
                    klass = content[0][9:] # skip !content_ prefix
                    if klass not in c_map:
                        mod, nspace = klass.split('.', 1)
                        mod = __import__(mod)
                        for submod in nspace.split('.'):
                            mod = getattr(mod, submod)
                        c_map[klass] = mod
                    klass = c_map[klass]
                    obj = klass(data['id'])
                    obj.__dict__.update(data)
                    root = db.db
                    print "creating %r in %r"%(obj.id, rp)
                    for p in rp.split('/')[1:-1]:
                        root = root[p]
                    root[obj.id] = obj
                    all_objs.append(obj)
                else:
                    print "WARN: empty content for", root
            else:
                print "Incorrect content files: %r"%', '.join(content)

        users = db.db['users']
        for obj in all_objs:
            if isinstance(obj.owner, basestring):
                obj.owner =   users[obj.owner]
                obj.repair()

        transaction.commit()
        db.pack()
    elif len(sys.argv) == 3 and sys.argv[1] == "export":
        import datetime
        base = sys.argv[2]
        log.info("Exploring %s", base)

        all_obj = [ (db.db, '/') ]
        for obj, obj_path in all_obj:
            log.info("-"*80)
            nbase = os.path.join(base, (obj_path or obj.path).lstrip(os.path.sep))
            try:
                os.mkdir(nbase)
            except OSError:
                pass
            log.debug("%s %s", nbase, type(obj)) #.id if hasattr(obj, 'id') else 'ROOT'
            data = obj.__dict__.copy()
            for k, v in data.iteritems():
                if k.startswith('_v_'):
                    continue
                if isinstance(v, datetime.date):
                    data[k] = "%s/%s/%s"%(v.day, v.month, v.year)
                elif isinstance(v, DataBlob):
                    try:
                        data[k] = v.filename
                    except Exception: # unreadable
                        data[k] = None
                        log.warning('Unable to recover %s...'%k)
                    else:
                        try:
                            os.link(v.filename, os.path.join(nbase, data['content_name']))
                        except OSError, e:
                            log.info('%r : %r', v.filename, e)
                elif isinstance(v, set):
                    data[k] = list(v)
                elif k == 'owner':
                    data[k] = v.id
            if 'data' in data:
                del data['data']
            if obj.__class__.__module__:
                name = "%s.%s"%(obj.__class__.__module__, obj.__class__.__name__)
            else:
                name = obj.__class__.__name___

            try:
                file( os.path.join(nbase, '!content_%s'%obj.__class__.__name__), 'w').write(
                    dumps(data)
                )
            except IOError:
                log.error('Unable to dump %r !'%(obj.rootpath+obj.id))
            except TypeError:
                log.warning('Forcing serialization')
                for k, v in data.items():
                    if not isinstance(v, (tuple, list, basestring, dict, set)):
                        log.debug('removing %r'%k)
                        del data[k]

            # recurse
            if len(obj):
                for k in obj:
                    all_obj.append((obj[k], None))
    elif len(sys.argv) == 2 and sys.argv[1] == "debug":
        try:
            import readline
            import rlcompleter
            readline.parse_and_bind('tab: complete')
        except ImportError:
            print "Disabling completion..."
        import code
        import drink
        with db as root:
            l = {'db': root, 'drink': drink}
            request.identity = FakeId()
            code.interact('Shell variables: %s'%', '.join(l.keys()), local=l)

from beaker.middleware import SessionMiddleware

def make_app(full=False):
    """ Returns Drink WSGI application """
    global reset_required, debug
    if not PERSISTENT_STORAGE or 'BOTTLE_CHILD' not in os.environ:
        with db as c:
            if len(c) < 3:
                reset_required = True

        if reset_required:
            init()

    # And now, http/wsgi part

    mode = config.get('server', 'backend')

    # try some (optional) asynchronous optimization

    async = False

    if dbg_in_env:
        mode = 'debug'

    if full and mode not in ('debug', 'paste', 'rocket'):
        try:
            import gevent.monkey
            gevent.monkey.patch_all()
        except ImportError:
            async = False
        else:
            log.warning('Using gevent for asynchronous processing')
            async = True

    config.async = async

    app = bottle.app()
    session_opts = {
        'session.auto': False,
        'session.type': 'file',
        'session.key': 'drink_cookie',
        'session.cookie_expires': False,
        'session.data_dir':  DB_PATH,
        #'session.validate_key': 'drink-key-you-must-change-this-in-cookies',
        #'session.encryption_key': ''.join(chr(randint(65, 122)) for x in xrange(100)
    }
    app = SessionMiddleware(app, session_opts)

    if not full:
        return app

    # handle debug mode
    debug = False
    if dbg_in_env:
        debug = True
        # trick to allow debug-wrapping
        app.catchall = False

        def dbg_repoze(app):
            from repoze.debug.pdbpm import PostMortemDebug
            app = PostMortemDebug(app)
            log.debug("Installed repoze.debug's debugging middleware")
            return app

        def dbg_werkzeug(app):
            from werkzeug.debug import DebuggedApplication
            app = DebuggedApplication(app, evalex=True)
            log.debug("Installed werkzeug debugging middleware")
            return app

        def dbg_weberror(app):
            from weberror.evalexception import EvalException
            app = EvalException(app)
            log.debug("Installed weberror debugging middleware")
            return app

        dbg_backend = config.get('server', 'debug')

        if dbg_backend == 'auto':
            backends = [dbg_werkzeug, dbg_repoze, dbg_weberror]
        else:
            backends = [locals()['dbg_%s'%dbg_backend]]

        # debug middleware loading
        for loader in backends:
            try:
                app = loader(app)
                break
            except ImportError:
                continue
        else:
            debug = False
            log.error("Unable to install the debugging middleware, current setting: %s", dbg_backend)
    # /end dbg_in_env

    #from wsgiauth.ip import ip
    #@ip
    #def authenticate(env, ip_addr):
    #    return ip_addr == '127.0.0.1'
    #
    #app = authenticate(app)

    # Let's run !
    bottle.debug(debug)
    return app