public
Description: Google's Webkit, ported to Python, ported to Desktops.
Homepage: http://lkcl.net/pyjamas-desktop
Clone URL: git://github.com/lkcl/pyjamas-desktop.git
100755 458 lines (337 sloc) 12.912 kb
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
__access__ = 0
import cgi
 
# classes comprising the product
try:
    from mod_python.util import redirect
    from mod_python import apache
    from mod_python import Cookie
except ImportError, err:
    print "import error", err
    pass
 
from mainpage import ZCTmainpage
from zctlogin import ZCTlogin
 
from htmldict import HTMLdict
from urllib import urlencode
 
import os
 
# temporarily used to change the web site mode:
# currently "ajax" and "plain" is supported.
defaultmode = 'plain'
 
class SiteThingy:
 
    def __init__(self, z):
        self.z = z
 
    def nojs_staticlink(self, links={}):
 
        redirlink = "./?mode=plain"
        res = self
        for (k, v) in links.items():
            if v is None:
                continue
            if isinstance(v, type(())):
                (v, cls) = v
                content = simulate_get_content(self.z, v)
                res[k] = '<div id="%s" class="%s">%s</div>' % (k, cls, content)
            else:
                content = simulate_get_content(self.z, v)
                res[k] = '<div id="%s">%s</div>' % (k, content)
 
        return self
 
    def ajax_staticlink(self, links={}):
 
        res = self
        l = []
        for (k, v) in links.items():
            if v is None:
                continue
            cls = ''
            if isinstance(v, type(())):
                (v, cls) = v
                cls = ' class="%s"' % cls
            if self.z.info.has_key(k):
                self.z.info[k] = zct_parse_qs(v)
            txt = "ajax_dlink('%s','%s');" % (k, v)
            l.append(txt)
            res[k] = """
<div id="%s"%s> </div>
""" % (k, cls)
 
        res['prelinks'] = """
<script>
<!--
/* set up the content pages*/
%s
-->
</script>""" % "\n".join(l)
 
        return self
 
    def staticlink(self, links={}, override=0):
        """ this function fills in the links to other pages,
under the class-name sections specified in links.keys().
 
however, it's possible for visits from other pages
to have over-ridden some of those page sections. if you
want to "reset" those - i.e. for the links to be authoritative,
then you must set override=1.
 
override is particularly useful for the homepage where you want
to reset the content to a known state.
"""
 
 
        if not override:
            for (clsid, href) in links.items():
 
                if not self.z.info.has_key(clsid):
                    continue
                    
                (page, req) = self.z.info[clsid]
                links[clsid] = "%s?%s" % (page, urlencode(req, 1))
 
        if self.z.mode == 'ajax':
            return self.ajax_staticlink(links)
        return self.nojs_staticlink(links)
 
    def ajax_dynamiclink(self, contents={}, prelinks={}):
 
        res = self
 
        for (k, (classname, href, clsid, linktext)) in contents.items():
 
            page, req = zct_parse_qs(href)
 
            #if self.z.info.has_key(clsid):
                
            # (pagename, pageargs) = self.z.info[clsid]
 
            # if page == pagename and req == pageargs:
            # prelinks[clsid] = href
 
 
            req['source'] = clsid
            href = "%s?%s" % (page, urlencode(req, 1))
            txt = """
<a class="%s" href="%s"
onclick="ajax_dlink('%s','%s')">%s</a>
""" % (classname, href, clsid, href, linktext)
            res[k] = txt
            
        if prelinks:
            links = []
            for kv in prelinks.items():
                txt = "ajax_dlink('%s','%s');" % kv
                links.append(txt)
            res['prelinks'] = res.get('prelinks', '') + """
<script>
<!--
/* set up the content pages*/
%s
-->
</script>
""" % "\n".join(links)
 
        return self
 
    def nojs_dynamiclink(self, contents={}, prelinks={}):
 
        res = self
 
        for (k, (classname, href, clsid, linktext)) in contents.items():
 
            page, req = zct_parse_qs(href)
 
            req['source'] = clsid
            req['__mainpage__'] = "index"
            href = "%s?%s" % (page, urlencode(req, 1))
            txt = """
<a class="%s" href="%s">%s</a>
""" % (classname, href, linktext)
            res[k] = txt
            
        return self
 
    def dynamiclink(self, contents={}, prelinks={}):
 
        if self.z.mode == 'ajax':
            return self.ajax_dynamiclink(contents, prelinks)
        return self.nojs_dynamiclink(contents, prelinks)
 
    def nojs_formpost(self, formname, classname,
                    href, clsid, submitname):
 
        res = self
        res['action%s' % formname] = 'action="index"'
        res['submit%s' % formname] = """
<input class="%s" type="submit" name="%s" value="%s" />
<input name="__clsid__" type="hidden" value="%s" />
<input name="__postpage__" type="hidden" value="%s" />
""" % (classname, submitname, submitname, clsid, href)
 
    def ajax_formpost(self, formname, classname,
                    href, clsid, submitname):
 
        res = self
        res['action%s' % formname] = 'action="%s"' % (href)
        res['submit%s' % formname] = """
<input class="%s" type="button" name="%s" value="%s"
onclick="ajax_post('%s', './%s', this.form);" />
""" % (classname, submitname, submitname, clsid, href)
 
    def formpost(self, formname, classname, href, clsid, submitname):
 
        if self.z.mode == 'ajax':
            fn = self.ajax_formpost
        else:
            fn = self.nojs_formpost
        return fn(formname, classname, href, clsid, submitname)
 
class DynamicHTMLdict(HTMLdict, SiteThingy):
 
    def __init__(self, z, fname=None, htmlescape=0):
        fname = z.tmpl_path(fname)
        HTMLdict.__init__(self, fname, htmlescape)
        SiteThingy.__init__(self, z)
 
class SiteDict(dict, SiteThingy):
 
    def __init__(self, z):
        dict.__init__(self)
        SiteThingy.__init__(self, z)
 
 
class ZCTclass(ZCTmainpage, ZCTlogin):
    """ ZCT class.
"""
 
    def __init__(self):
        """initialize a new instance of ZCT"""
 
        self.db = None
        self.template_dir = None
        self.filename = None
 
    def __del__(self):
 
        del self.db
 
    def set_options(self, req):
 
        self.req = req
        self.mode = req.form.get('mode', defaultmode)
 
        opts = req.get_options()
        #filename = opts.get('database', "zctdb:missingmarbles@localhost")
        #if filename and self.filename != filename:
        # self.filename = filename
            #self.db = Database(self.filename, engine='pgsql')
 
        template_dir = opts.get('templates',
                os.path.join("/home/lkcl/src/pyjamas-desktop/pyjamas-web", 'www'))
                #os.path.join(req.document_root(), 'www'))
        if template_dir and self.template_dir != template_dir:
            self.template_dir = template_dir
 
    def tmpl_path(self, name):
        return os.path.join(self.template_dir, name+".tmpl")
 
    def straightload(self, name):
        idx = name.rfind('_')
        name = name[:idx] + '.' + name[idx+1:]
        fullpath = os.path.join(self.template_dir, name)
        f = open(fullpath)
        return f.read()
 
    def tmpl(self, name, REQUEST=None):
        d = DynamicHTMLdict(self, name)
        if REQUEST:
            d.update(REQUEST)
        return d
 
    def prevnext(self, REQUEST, start, pagecount, count, targetpage=None,
                 ajaxid='centercontent'):
 
        if start < 0:
            start = 0
 
        next = start + pagecount
        prev = start - pagecount
 
        d = {}
        options = {}
 
        if targetpage is None:
            targetpage = self.req.uri.split("/")[-1]
        if next < count:
            REQUEST['start'] = start+pagecount
            url = './%s?%s' % (targetpage, urlencode(REQUEST))
            options['nextpage'] = ("", url, ajaxid, "Next")
 
        if prev < 0:
            prev = 0
 
        if prev != start:
            REQUEST['start'] = prev
            url = './%s?%s' % (targetpage, urlencode(REQUEST))
            options['prevpage'] = ("", url, ajaxid, "Prev")
 
        if next > count:
            next = count
 
        if start != 0 or next != count:
            d['countstuff'] = 1
            
        d['start'] = start + 1
        d['next'] = next
        d['count'] = count
        d['ajaxid'] = ajaxid
 
        page = self.tmpl('prevnext', d)
        page.dynamiclink(options)
 
        return page
 
    def ajax_linkredirect(self, REQUEST, href, clsid=None, mainpage=None):
        return redirect(self.req, href)
 
    def nojs_linkredirect(self, REQUEST, href, clsid=None, mainpage=None):
 
        clsid = clsid or str(REQUEST['__clsid__'])
        mainpage = mainpage or str(REQUEST['__postpage__'])
 
        self.info[clsid] = zct_parse_qs(href)
        self.req.err_headers_out["Location"] = mainpage
        self.req.status = apache.HTTP_MOVED_TEMPORARILY
        return None
 
    def linkredirect(self, REQUEST, href, clsid=None, mainpage=None):
 
        if self.mode == 'ajax':
            fn = self.ajax_linkredirect
        else:
            fn = self.nojs_linkredirect
        return fn(REQUEST, href, clsid, mainpage)
 
    def linkprocess(self, REQUEST, pagename):
 
        source = REQUEST.get('source')
        if source:
            del REQUEST['source']
 
        self.info = self.get_browser_info()
        if source:
            self.info[source] = (pagename, REQUEST)
                                
        mainpage = REQUEST.get('__mainpage__')
        postpage = REQUEST.get('__postpage__')
        if mainpage:
            del REQUEST['__mainpage__']
            #href = "%s?%s" % (mainpage, urlencode(REQUEST))
            #self.req.err_headers_out["Location"] = href
            #self.req.status = apache.HTTP_MOVED_TEMPORARILY
 
        elif postpage:
            clsid = str(REQUEST['__clsid__'])
            del REQUEST['__clsid__']
            del REQUEST['__postpage__']
            self.info[clsid] = (postpage, REQUEST)
 
            mainpage = pagename
 
        else:
            mainpage = pagename
 
        return mainpage
 
    def action_login(self, username, password):
        """ performs a login validation and session start
- checks the username and password.
- checks that the existing session is valid
- creates a new one if it's not
"""
 
        username = str(username)
        password = str(password)
 
        if not self.db.test_login(username, password):
            return 0
 
        if self.login_check():
            return 1
 
        sk = sessionkey(username, password)
 
        Cookie.add_cookie(self.req, Cookie.Cookie('sessionkey', sk))
 
        # sets the session key in the database
        self.db.set_session(username, sk)
 
        return 1
 
    def set_useful_info(self, info):
        """ sets the "state" info for the browser
"""
 
        info = repr(info)
        Cookie.add_cookie(self.req, Cookie.Cookie('stateinfo', info))
 
    def get_useful_info(self):
        """ gets the "state" info for the browser
"""
        
        cookies = Cookie.get_cookies(self.req)
 
        if not cookies.has_key('stateinfo'):
            return {}
 
        info = cookies['stateinfo'].value
        info = eval(info)
        return info
 
    def set_browser_info(self, info):
        """ sets the "state" info for the browser
"""
 
        #info = base64.encodestring(repr(info))
        info = repr(info)
        Cookie.add_cookie(self.req, Cookie.Cookie('browseinfo', info))
 
    def get_browser_info(self):
        """ gets the "state" info for the browser
"""
        
        cookies = Cookie.get_cookies(self.req)
 
        if not cookies.has_key('browseinfo'):
            return {}
 
        info = cookies['browseinfo'].value
        #info = eval(base64.decodestring(info))
        info = eval(info)
        return info
 
    def get_session_info(self):
        """ checks to see if the user is logged in, via the session cookie.
"""
        
        cookies = Cookie.get_cookies(self.req)
 
        if not cookies.has_key('sessionkey'):
            return None
 
        return cookies['sessionkey'].value
 
def zct_parse_qs(v):
 
    l = v.split('?')
    page = l[0]
    if len(l) <= 1:
        req = {}
    else:
        args = cgi.parse_qsl(l[1])
        req = {}
        for (k, v) in args:
            # there's probably a much more elegant way to do this...
            if req.has_key(k):
                if isinstance(req[k], type([])):
                    req[k].append(v)
                else:
                    req[k] = [req[k], v]
            else:
                req[k] = v
 
    return page, req
 
def simulate_get_content(z, v):
 
    page, req = zct_parse_qs(v)
    fn = getattr(z, page)
    return fn(req)