Browse Source

Renaming repository to new name: luminotes

Dan Helfman 11 years ago
commit
02cfca5322
76 changed files with 13890 additions and 0 deletions
  1. 674
    0
      COPYING
  2. 26
    0
      INSTALL
  3. 71
    0
      README
  4. 18
    0
      config/Common.py
  5. 19
    0
      config/Development.py
  6. 14
    0
      config/Production.py
  7. 0
    0
      config/__init__.py
  8. 16
    0
      controller/Async.py
  9. 214
    0
      controller/Database.py
  10. 15
    0
      controller/Expire.py
  11. 87
    0
      controller/Expose.py
  12. 146
    0
      controller/Html_cleaner.py
  13. 52
    0
      controller/Html_nuker.py
  14. 398
    0
      controller/Notebooks.py
  15. 60
    0
      controller/Root.py
  16. 123
    0
      controller/Scheduler.py
  17. 70
    0
      controller/Updater.py
  18. 232
    0
      controller/Users.py
  19. 244
    0
      controller/Validate.py
  20. 0
    0
      controller/__init__.py
  21. 8
    0
      controller/test/Stub_view.py
  22. 98
    0
      controller/test/Test_controller.py
  23. 196
    0
      controller/test/Test_database.py
  24. 714
    0
      controller/test/Test_notebooks.py
  25. 34
    0
      controller/test/Test_root.py
  26. 147
    0
      controller/test/Test_users.py
  27. 0
    0
      controller/test/__init__.py
  28. 33
    0
      limitedmedium.py
  29. 52
    0
      model/Entry.py
  30. 162
    0
      model/Notebook.py
  31. 28
    0
      model/Persistent.py
  32. 29
    0
      model/Read_only_notebook.py
  33. 92
    0
      model/User.py
  34. 0
    0
      model/__init__.py
  35. 44
    0
      model/test/Test_entry.py
  36. 176
    0
      model/test/Test_notebook.py
  37. 50
    0
      model/test/Test_persistent.py
  38. 73
    0
      model/test/Test_read_only_notebook.py
  39. 97
    0
      model/test/Test_user.py
  40. 60
    0
      static/css/download.css
  41. 36
    0
      static/css/entry.css
  42. 20
    0
      static/css/ie.css
  43. 257
    0
      static/css/style.css
  44. 21
    0
      static/html/about.html
  45. 19
    0
      static/html/advanced browser features.html
  46. 37
    0
      static/html/features.html
  47. 23
    0
      static/html/login.html
  48. 5
    0
      static/html/navigation.html
  49. 3
    0
      static/html/password reset.html
  50. 18
    0
      static/html/reload.html
  51. 29
    0
      static/html/supported browsers.html
  52. 3
    0
      static/html/take a tour.html
  53. 39
    0
      static/html/try it out.html
  54. 25
    0
      static/html/welcome to your wiki.html
  55. BIN
      static/images/1x1.png
  56. 442
    0
      static/js/Editor.js
  57. 81
    0
      static/js/Invoker.js
  58. 6911
    0
      static/js/MochiKit.js
  59. 69
    0
      static/js/MochiKit_LICENSE
  60. 596
    0
      static/js/Wiki.js
  61. 35
    0
      tools/dumpdb.py
  62. 117
    0
      tools/initdb.py
  63. 77
    0
      tools/updatedb.py
  64. 17
    0
      view/Entry_page.py
  65. 36
    0
      view/Error_page.py
  66. 40
    0
      view/Html_file.py
  67. 23
    0
      view/Json.py
  68. 14
    0
      view/Link_area.py
  69. 51
    0
      view/Main_page.py
  70. 77
    0
      view/Node.py
  71. 23
    0
      view/Not_found_page.py
  72. 35
    0
      view/Page.py
  73. 13
    0
      view/Search_form.py
  74. 107
    0
      view/Tags.py
  75. 19
    0
      view/Toolbar.py
  76. 0
    0
      view/__init__.py

+ 674
- 0
COPYING View File

@@ -0,0 +1,674 @@
1
+                    GNU GENERAL PUBLIC LICENSE
2
+                       Version 3, 29 June 2007
3
+
4
+ Copyright (C) 2007 Free Software Foundation, Inc. <http://fsf.org/>
5
+ Everyone is permitted to copy and distribute verbatim copies
6
+ of this license document, but changing it is not allowed.
7
+
8
+                            Preamble
9
+
10
+  The GNU General Public License is a free, copyleft license for
11
+software and other kinds of works.
12
+
13
+  The licenses for most software and other practical works are designed
14
+to take away your freedom to share and change the works.  By contrast,
15
+the GNU General Public License is intended to guarantee your freedom to
16
+share and change all versions of a program--to make sure it remains free
17
+software for all its users.  We, the Free Software Foundation, use the
18
+GNU General Public License for most of our software; it applies also to
19
+any other work released this way by its authors.  You can apply it to
20
+your programs, too.
21
+
22
+  When we speak of free software, we are referring to freedom, not
23
+price.  Our General Public Licenses are designed to make sure that you
24
+have the freedom to distribute copies of free software (and charge for
25
+them if you wish), that you receive source code or can get it if you
26
+want it, that you can change the software or use pieces of it in new
27
+free programs, and that you know you can do these things.
28
+
29
+  To protect your rights, we need to prevent others from denying you
30
+these rights or asking you to surrender the rights.  Therefore, you have
31
+certain responsibilities if you distribute copies of the software, or if
32
+you modify it: responsibilities to respect the freedom of others.
33
+
34
+  For example, if you distribute copies of such a program, whether
35
+gratis or for a fee, you must pass on to the recipients the same
36
+freedoms that you received.  You must make sure that they, too, receive
37
+or can get the source code.  And you must show them these terms so they
38
+know their rights.
39
+
40
+  Developers that use the GNU GPL protect your rights with two steps:
41
+(1) assert copyright on the software, and (2) offer you this License
42
+giving you legal permission to copy, distribute and/or modify it.
43
+
44
+  For the developers' and authors' protection, the GPL clearly explains
45
+that there is no warranty for this free software.  For both users' and
46
+authors' sake, the GPL requires that modified versions be marked as
47
+changed, so that their problems will not be attributed erroneously to
48
+authors of previous versions.
49
+
50
+  Some devices are designed to deny users access to install or run
51
+modified versions of the software inside them, although the manufacturer
52
+can do so.  This is fundamentally incompatible with the aim of
53
+protecting users' freedom to change the software.  The systematic
54
+pattern of such abuse occurs in the area of products for individuals to
55
+use, which is precisely where it is most unacceptable.  Therefore, we
56
+have designed this version of the GPL to prohibit the practice for those
57
+products.  If such problems arise substantially in other domains, we
58
+stand ready to extend this provision to those domains in future versions
59
+of the GPL, as needed to protect the freedom of users.
60
+
61
+  Finally, every program is threatened constantly by software patents.
62
+States should not allow patents to restrict development and use of
63
+software on general-purpose computers, but in those that do, we wish to
64
+avoid the special danger that patents applied to a free program could
65
+make it effectively proprietary.  To prevent this, the GPL assures that
66
+patents cannot be used to render the program non-free.
67
+
68
+  The precise terms and conditions for copying, distribution and
69
+modification follow.
70
+
71
+                       TERMS AND CONDITIONS
72
+
73
+  0. Definitions.
74
+
75
+  "This License" refers to version 3 of the GNU General Public License.
76
+
77
+  "Copyright" also means copyright-like laws that apply to other kinds of
78
+works, such as semiconductor masks.
79
+
80
+  "The Program" refers to any copyrightable work licensed under this
81
+License.  Each licensee is addressed as "you".  "Licensees" and
82
+"recipients" may be individuals or organizations.
83
+
84
+  To "modify" a work means to copy from or adapt all or part of the work
85
+in a fashion requiring copyright permission, other than the making of an
86
+exact copy.  The resulting work is called a "modified version" of the
87
+earlier work or a work "based on" the earlier work.
88
+
89
+  A "covered work" means either the unmodified Program or a work based
90
+on the Program.
91
+
92
+  To "propagate" a work means to do anything with it that, without
93
+permission, would make you directly or secondarily liable for
94
+infringement under applicable copyright law, except executing it on a
95
+computer or modifying a private copy.  Propagation includes copying,
96
+distribution (with or without modification), making available to the
97
+public, and in some countries other activities as well.
98
+
99
+  To "convey" a work means any kind of propagation that enables other
100
+parties to make or receive copies.  Mere interaction with a user through
101
+a computer network, with no transfer of a copy, is not conveying.
102
+
103
+  An interactive user interface displays "Appropriate Legal Notices"
104
+to the extent that it includes a convenient and prominently visible
105
+feature that (1) displays an appropriate copyright notice, and (2)
106
+tells the user that there is no warranty for the work (except to the
107
+extent that warranties are provided), that licensees may convey the
108
+work under this License, and how to view a copy of this License.  If
109
+the interface presents a list of user commands or options, such as a
110
+menu, a prominent item in the list meets this criterion.
111
+
112
+  1. Source Code.
113
+
114
+  The "source code" for a work means the preferred form of the work
115
+for making modifications to it.  "Object code" means any non-source
116
+form of a work.
117
+
118
+  A "Standard Interface" means an interface that either is an official
119
+standard defined by a recognized standards body, or, in the case of
120
+interfaces specified for a particular programming language, one that
121
+is widely used among developers working in that language.
122
+
123
+  The "System Libraries" of an executable work include anything, other
124
+than the work as a whole, that (a) is included in the normal form of
125
+packaging a Major Component, but which is not part of that Major
126
+Component, and (b) serves only to enable use of the work with that
127
+Major Component, or to implement a Standard Interface for which an
128
+implementation is available to the public in source code form.  A
129
+"Major Component", in this context, means a major essential component
130
+(kernel, window system, and so on) of the specific operating system
131
+(if any) on which the executable work runs, or a compiler used to
132
+produce the work, or an object code interpreter used to run it.
133
+
134
+  The "Corresponding Source" for a work in object code form means all
135
+the source code needed to generate, install, and (for an executable
136
+work) run the object code and to modify the work, including scripts to
137
+control those activities.  However, it does not include the work's
138
+System Libraries, or general-purpose tools or generally available free
139
+programs which are used unmodified in performing those activities but
140
+which are not part of the work.  For example, Corresponding Source
141
+includes interface definition files associated with source files for
142
+the work, and the source code for shared libraries and dynamically
143
+linked subprograms that the work is specifically designed to require,
144
+such as by intimate data communication or control flow between those
145
+subprograms and other parts of the work.
146
+
147
+  The Corresponding Source need not include anything that users
148
+can regenerate automatically from other parts of the Corresponding
149
+Source.
150
+
151
+  The Corresponding Source for a work in source code form is that
152
+same work.
153
+
154
+  2. Basic Permissions.
155
+
156
+  All rights granted under this License are granted for the term of
157
+copyright on the Program, and are irrevocable provided the stated
158
+conditions are met.  This License explicitly affirms your unlimited
159
+permission to run the unmodified Program.  The output from running a
160
+covered work is covered by this License only if the output, given its
161
+content, constitutes a covered work.  This License acknowledges your
162
+rights of fair use or other equivalent, as provided by copyright law.
163
+
164
+  You may make, run and propagate covered works that you do not
165
+convey, without conditions so long as your license otherwise remains
166
+in force.  You may convey covered works to others for the sole purpose
167
+of having them make modifications exclusively for you, or provide you
168
+with facilities for running those works, provided that you comply with
169
+the terms of this License in conveying all material for which you do
170
+not control copyright.  Those thus making or running the covered works
171
+for you must do so exclusively on your behalf, under your direction
172
+and control, on terms that prohibit them from making any copies of
173
+your copyrighted material outside their relationship with you.
174
+
175
+  Conveying under any other circumstances is permitted solely under
176
+the conditions stated below.  Sublicensing is not allowed; section 10
177
+makes it unnecessary.
178
+
179
+  3. Protecting Users' Legal Rights From Anti-Circumvention Law.
180
+
181
+  No covered work shall be deemed part of an effective technological
182
+measure under any applicable law fulfilling obligations under article
183
+11 of the WIPO copyright treaty adopted on 20 December 1996, or
184
+similar laws prohibiting or restricting circumvention of such
185
+measures.
186
+
187
+  When you convey a covered work, you waive any legal power to forbid
188
+circumvention of technological measures to the extent such circumvention
189
+is effected by exercising rights under this License with respect to
190
+the covered work, and you disclaim any intention to limit operation or
191
+modification of the work as a means of enforcing, against the work's
192
+users, your or third parties' legal rights to forbid circumvention of
193
+technological measures.
194
+
195
+  4. Conveying Verbatim Copies.
196
+
197
+  You may convey verbatim copies of the Program's source code as you
198
+receive it, in any medium, provided that you conspicuously and
199
+appropriately publish on each copy an appropriate copyright notice;
200
+keep intact all notices stating that this License and any
201
+non-permissive terms added in accord with section 7 apply to the code;
202
+keep intact all notices of the absence of any warranty; and give all
203
+recipients a copy of this License along with the Program.
204
+
205
+  You may charge any price or no price for each copy that you convey,
206
+and you may offer support or warranty protection for a fee.
207
+
208
+  5. Conveying Modified Source Versions.
209
+
210
+  You may convey a work based on the Program, or the modifications to
211
+produce it from the Program, in the form of source code under the
212
+terms of section 4, provided that you also meet all of these conditions:
213
+
214
+    a) The work must carry prominent notices stating that you modified
215
+    it, and giving a relevant date.
216
+
217
+    b) The work must carry prominent notices stating that it is
218
+    released under this License and any conditions added under section
219
+    7.  This requirement modifies the requirement in section 4 to
220
+    "keep intact all notices".
221
+
222
+    c) You must license the entire work, as a whole, under this
223
+    License to anyone who comes into possession of a copy.  This
224
+    License will therefore apply, along with any applicable section 7
225
+    additional terms, to the whole of the work, and all its parts,
226
+    regardless of how they are packaged.  This License gives no
227
+    permission to license the work in any other way, but it does not
228
+    invalidate such permission if you have separately received it.
229
+
230
+    d) If the work has interactive user interfaces, each must display
231
+    Appropriate Legal Notices; however, if the Program has interactive
232
+    interfaces that do not display Appropriate Legal Notices, your
233
+    work need not make them do so.
234
+
235
+  A compilation of a covered work with other separate and independent
236
+works, which are not by their nature extensions of the covered work,
237
+and which are not combined with it such as to form a larger program,
238
+in or on a volume of a storage or distribution medium, is called an
239
+"aggregate" if the compilation and its resulting copyright are not
240
+used to limit the access or legal rights of the compilation's users
241
+beyond what the individual works permit.  Inclusion of a covered work
242
+in an aggregate does not cause this License to apply to the other
243
+parts of the aggregate.
244
+
245
+  6. Conveying Non-Source Forms.
246
+
247
+  You may convey a covered work in object code form under the terms
248
+of sections 4 and 5, provided that you also convey the
249
+machine-readable Corresponding Source under the terms of this License,
250
+in one of these ways:
251
+
252
+    a) Convey the object code in, or embodied in, a physical product
253
+    (including a physical distribution medium), accompanied by the
254
+    Corresponding Source fixed on a durable physical medium
255
+    customarily used for software interchange.
256
+
257
+    b) Convey the object code in, or embodied in, a physical product
258
+    (including a physical distribution medium), accompanied by a
259
+    written offer, valid for at least three years and valid for as
260
+    long as you offer spare parts or customer support for that product
261
+    model, to give anyone who possesses the object code either (1) a
262
+    copy of the Corresponding Source for all the software in the
263
+    product that is covered by this License, on a durable physical
264
+    medium customarily used for software interchange, for a price no
265
+    more than your reasonable cost of physically performing this
266
+    conveying of source, or (2) access to copy the
267
+    Corresponding Source from a network server at no charge.
268
+
269
+    c) Convey individual copies of the object code with a copy of the
270
+    written offer to provide the Corresponding Source.  This
271
+    alternative is allowed only occasionally and noncommercially, and
272
+    only if you received the object code with such an offer, in accord
273
+    with subsection 6b.
274
+
275
+    d) Convey the object code by offering access from a designated
276
+    place (gratis or for a charge), and offer equivalent access to the
277
+    Corresponding Source in the same way through the same place at no
278
+    further charge.  You need not require recipients to copy the
279
+    Corresponding Source along with the object code.  If the place to
280
+    copy the object code is a network server, the Corresponding Source
281
+    may be on a different server (operated by you or a third party)
282
+    that supports equivalent copying facilities, provided you maintain
283
+    clear directions next to the object code saying where to find the
284
+    Corresponding Source.  Regardless of what server hosts the
285
+    Corresponding Source, you remain obligated to ensure that it is
286
+    available for as long as needed to satisfy these requirements.
287
+
288
+    e) Convey the object code using peer-to-peer transmission, provided
289
+    you inform other peers where the object code and Corresponding
290
+    Source of the work are being offered to the general public at no
291
+    charge under subsection 6d.
292
+
293
+  A separable portion of the object code, whose source code is excluded
294
+from the Corresponding Source as a System Library, need not be
295
+included in conveying the object code work.
296
+
297
+  A "User Product" is either (1) a "consumer product", which means any
298
+tangible personal property which is normally used for personal, family,
299
+or household purposes, or (2) anything designed or sold for incorporation
300
+into a dwelling.  In determining whether a product is a consumer product,
301
+doubtful cases shall be resolved in favor of coverage.  For a particular
302
+product received by a particular user, "normally used" refers to a
303
+typical or common use of that class of product, regardless of the status
304
+of the particular user or of the way in which the particular user
305
+actually uses, or expects or is expected to use, the product.  A product
306
+is a consumer product regardless of whether the product has substantial
307
+commercial, industrial or non-consumer uses, unless such uses represent
308
+the only significant mode of use of the product.
309
+
310
+  "Installation Information" for a User Product means any methods,
311
+procedures, authorization keys, or other information required to install
312
+and execute modified versions of a covered work in that User Product from
313
+a modified version of its Corresponding Source.  The information must
314
+suffice to ensure that the continued functioning of the modified object
315
+code is in no case prevented or interfered with solely because
316
+modification has been made.
317
+
318
+  If you convey an object code work under this section in, or with, or
319
+specifically for use in, a User Product, and the conveying occurs as
320
+part of a transaction in which the right of possession and use of the
321
+User Product is transferred to the recipient in perpetuity or for a
322
+fixed term (regardless of how the transaction is characterized), the
323
+Corresponding Source conveyed under this section must be accompanied
324
+by the Installation Information.  But this requirement does not apply
325
+if neither you nor any third party retains the ability to install
326
+modified object code on the User Product (for example, the work has
327
+been installed in ROM).
328
+
329
+  The requirement to provide Installation Information does not include a
330
+requirement to continue to provide support service, warranty, or updates
331
+for a work that has been modified or installed by the recipient, or for
332
+the User Product in which it has been modified or installed.  Access to a
333
+network may be denied when the modification itself materially and
334
+adversely affects the operation of the network or violates the rules and
335
+protocols for communication across the network.
336
+
337
+  Corresponding Source conveyed, and Installation Information provided,
338
+in accord with this section must be in a format that is publicly
339
+documented (and with an implementation available to the public in
340
+source code form), and must require no special password or key for
341
+unpacking, reading or copying.
342
+
343
+  7. Additional Terms.
344
+
345
+  "Additional permissions" are terms that supplement the terms of this
346
+License by making exceptions from one or more of its conditions.
347
+Additional permissions that are applicable to the entire Program shall
348
+be treated as though they were included in this License, to the extent
349
+that they are valid under applicable law.  If additional permissions
350
+apply only to part of the Program, that part may be used separately
351
+under those permissions, but the entire Program remains governed by
352
+this License without regard to the additional permissions.
353
+
354
+  When you convey a copy of a covered work, you may at your option
355
+remove any additional permissions from that copy, or from any part of
356
+it.  (Additional permissions may be written to require their own
357
+removal in certain cases when you modify the work.)  You may place
358
+additional permissions on material, added by you to a covered work,
359
+for which you have or can give appropriate copyright permission.
360
+
361
+  Notwithstanding any other provision of this License, for material you
362
+add to a covered work, you may (if authorized by the copyright holders of
363
+that material) supplement the terms of this License with terms:
364
+
365
+    a) Disclaiming warranty or limiting liability differently from the
366
+    terms of sections 15 and 16 of this License; or
367
+
368
+    b) Requiring preservation of specified reasonable legal notices or
369
+    author attributions in that material or in the Appropriate Legal
370
+    Notices displayed by works containing it; or
371
+
372
+    c) Prohibiting misrepresentation of the origin of that material, or
373
+    requiring that modified versions of such material be marked in
374
+    reasonable ways as different from the original version; or
375
+
376
+    d) Limiting the use for publicity purposes of names of licensors or
377
+    authors of the material; or
378
+
379
+    e) Declining to grant rights under trademark law for use of some
380
+    trade names, trademarks, or service marks; or
381
+
382
+    f) Requiring indemnification of licensors and authors of that
383
+    material by anyone who conveys the material (or modified versions of
384
+    it) with contractual assumptions of liability to the recipient, for
385
+    any liability that these contractual assumptions directly impose on
386
+    those licensors and authors.
387
+
388
+  All other non-permissive additional terms are considered "further
389
+restrictions" within the meaning of section 10.  If the Program as you
390
+received it, or any part of it, contains a notice stating that it is
391
+governed by this License along with a term that is a further
392
+restriction, you may remove that term.  If a license document contains
393
+a further restriction but permits relicensing or conveying under this
394
+License, you may add to a covered work material governed by the terms
395
+of that license document, provided that the further restriction does
396
+not survive such relicensing or conveying.
397
+
398
+  If you add terms to a covered work in accord with this section, you
399
+must place, in the relevant source files, a statement of the
400
+additional terms that apply to those files, or a notice indicating
401
+where to find the applicable terms.
402
+
403
+  Additional terms, permissive or non-permissive, may be stated in the
404
+form of a separately written license, or stated as exceptions;
405
+the above requirements apply either way.
406
+
407
+  8. Termination.
408
+
409
+  You may not propagate or modify a covered work except as expressly
410
+provided under this License.  Any attempt otherwise to propagate or
411
+modify it is void, and will automatically terminate your rights under
412
+this License (including any patent licenses granted under the third
413
+paragraph of section 11).
414
+
415
+  However, if you cease all violation of this License, then your
416
+license from a particular copyright holder is reinstated (a)
417
+provisionally, unless and until the copyright holder explicitly and
418
+finally terminates your license, and (b) permanently, if the copyright
419
+holder fails to notify you of the violation by some reasonable means
420
+prior to 60 days after the cessation.
421
+
422
+  Moreover, your license from a particular copyright holder is
423
+reinstated permanently if the copyright holder notifies you of the
424
+violation by some reasonable means, this is the first time you have
425
+received notice of violation of this License (for any work) from that
426
+copyright holder, and you cure the violation prior to 30 days after
427
+your receipt of the notice.
428
+
429
+  Termination of your rights under this section does not terminate the
430
+licenses of parties who have received copies or rights from you under
431
+this License.  If your rights have been terminated and not permanently
432
+reinstated, you do not qualify to receive new licenses for the same
433
+material under section 10.
434
+
435
+  9. Acceptance Not Required for Having Copies.
436
+
437
+  You are not required to accept this License in order to receive or
438
+run a copy of the Program.  Ancillary propagation of a covered work
439
+occurring solely as a consequence of using peer-to-peer transmission
440
+to receive a copy likewise does not require acceptance.  However,
441
+nothing other than this License grants you permission to propagate or
442
+modify any covered work.  These actions infringe copyright if you do
443
+not accept this License.  Therefore, by modifying or propagating a
444
+covered work, you indicate your acceptance of this License to do so.
445
+
446
+  10. Automatic Licensing of Downstream Recipients.
447
+
448
+  Each time you convey a covered work, the recipient automatically
449
+receives a license from the original licensors, to run, modify and
450
+propagate that work, subject to this License.  You are not responsible
451
+for enforcing compliance by third parties with this License.
452
+
453
+  An "entity transaction" is a transaction transferring control of an
454
+organization, or substantially all assets of one, or subdividing an
455
+organization, or merging organizations.  If propagation of a covered
456
+work results from an entity transaction, each party to that
457
+transaction who receives a copy of the work also receives whatever
458
+licenses to the work the party's predecessor in interest had or could
459
+give under the previous paragraph, plus a right to possession of the
460
+Corresponding Source of the work from the predecessor in interest, if
461
+the predecessor has it or can get it with reasonable efforts.
462
+
463
+  You may not impose any further restrictions on the exercise of the
464
+rights granted or affirmed under this License.  For example, you may
465
+not impose a license fee, royalty, or other charge for exercise of
466
+rights granted under this License, and you may not initiate litigation
467
+(including a cross-claim or counterclaim in a lawsuit) alleging that
468
+any patent claim is infringed by making, using, selling, offering for
469
+sale, or importing the Program or any portion of it.
470
+
471
+  11. Patents.
472
+
473
+  A "contributor" is a copyright holder who authorizes use under this
474
+License of the Program or a work on which the Program is based.  The
475
+work thus licensed is called the contributor's "contributor version".
476
+
477
+  A contributor's "essential patent claims" are all patent claims
478
+owned or controlled by the contributor, whether already acquired or
479
+hereafter acquired, that would be infringed by some manner, permitted
480
+by this License, of making, using, or selling its contributor version,
481
+but do not include claims that would be infringed only as a
482
+consequence of further modification of the contributor version.  For
483
+purposes of this definition, "control" includes the right to grant
484
+patent sublicenses in a manner consistent with the requirements of
485
+this License.
486
+
487
+  Each contributor grants you a non-exclusive, worldwide, royalty-free
488
+patent license under the contributor's essential patent claims, to
489
+make, use, sell, offer for sale, import and otherwise run, modify and
490
+propagate the contents of its contributor version.
491
+
492
+  In the following three paragraphs, a "patent license" is any express
493
+agreement or commitment, however denominated, not to enforce a patent
494
+(such as an express permission to practice a patent or covenant not to
495
+sue for patent infringement).  To "grant" such a patent license to a
496
+party means to make such an agreement or commitment not to enforce a
497
+patent against the party.
498
+
499
+  If you convey a covered work, knowingly relying on a patent license,
500
+and the Corresponding Source of the work is not available for anyone
501
+to copy, free of charge and under the terms of this License, through a
502
+publicly available network server or other readily accessible means,
503
+then you must either (1) cause the Corresponding Source to be so
504
+available, or (2) arrange to deprive yourself of the benefit of the
505
+patent license for this particular work, or (3) arrange, in a manner
506
+consistent with the requirements of this License, to extend the patent
507
+license to downstream recipients.  "Knowingly relying" means you have
508
+actual knowledge that, but for the patent license, your conveying the
509
+covered work in a country, or your recipient's use of the covered work
510
+in a country, would infringe one or more identifiable patents in that
511
+country that you have reason to believe are valid.
512
+
513
+  If, pursuant to or in connection with a single transaction or
514
+arrangement, you convey, or propagate by procuring conveyance of, a
515
+covered work, and grant a patent license to some of the parties
516
+receiving the covered work authorizing them to use, propagate, modify
517
+or convey a specific copy of the covered work, then the patent license
518
+you grant is automatically extended to all recipients of the covered
519
+work and works based on it.
520
+
521
+  A patent license is "discriminatory" if it does not include within
522
+the scope of its coverage, prohibits the exercise of, or is
523
+conditioned on the non-exercise of one or more of the rights that are
524
+specifically granted under this License.  You may not convey a covered
525
+work if you are a party to an arrangement with a third party that is
526
+in the business of distributing software, under which you make payment
527
+to the third party based on the extent of your activity of conveying
528
+the work, and under which the third party grants, to any of the
529
+parties who would receive the covered work from you, a discriminatory
530
+patent license (a) in connection with copies of the covered work
531
+conveyed by you (or copies made from those copies), or (b) primarily
532
+for and in connection with specific products or compilations that
533
+contain the covered work, unless you entered into that arrangement,
534
+or that patent license was granted, prior to 28 March 2007.
535
+
536
+  Nothing in this License shall be construed as excluding or limiting
537
+any implied license or other defenses to infringement that may
538
+otherwise be available to you under applicable patent law.
539
+
540
+  12. No Surrender of Others' Freedom.
541
+
542
+  If conditions are imposed on you (whether by court order, agreement or
543
+otherwise) that contradict the conditions of this License, they do not
544
+excuse you from the conditions of this License.  If you cannot convey a
545
+covered work so as to satisfy simultaneously your obligations under this
546
+License and any other pertinent obligations, then as a consequence you may
547
+not convey it at all.  For example, if you agree to terms that obligate you
548
+to collect a royalty for further conveying from those to whom you convey
549
+the Program, the only way you could satisfy both those terms and this
550
+License would be to refrain entirely from conveying the Program.
551
+
552
+  13. Use with the GNU Affero General Public License.
553
+
554
+  Notwithstanding any other provision of this License, you have
555
+permission to link or combine any covered work with a work licensed
556
+under version 3 of the GNU Affero General Public License into a single
557
+combined work, and to convey the resulting work.  The terms of this
558
+License will continue to apply to the part which is the covered work,
559
+but the special requirements of the GNU Affero General Public License,
560
+section 13, concerning interaction through a network will apply to the
561
+combination as such.
562
+
563
+  14. Revised Versions of this License.
564
+
565
+  The Free Software Foundation may publish revised and/or new versions of
566
+the GNU General Public License from time to time.  Such new versions will
567
+be similar in spirit to the present version, but may differ in detail to
568
+address new problems or concerns.
569
+
570
+  Each version is given a distinguishing version number.  If the
571
+Program specifies that a certain numbered version of the GNU General
572
+Public License "or any later version" applies to it, you have the
573
+option of following the terms and conditions either of that numbered
574
+version or of any later version published by the Free Software
575
+Foundation.  If the Program does not specify a version number of the
576
+GNU General Public License, you may choose any version ever published
577
+by the Free Software Foundation.
578
+
579
+  If the Program specifies that a proxy can decide which future
580
+versions of the GNU General Public License can be used, that proxy's
581
+public statement of acceptance of a version permanently authorizes you
582
+to choose that version for the Program.
583
+
584
+  Later license versions may give you additional or different
585
+permissions.  However, no additional obligations are imposed on any
586
+author or copyright holder as a result of your choosing to follow a
587
+later version.
588
+
589
+  15. Disclaimer of Warranty.
590
+
591
+  THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
592
+APPLICABLE LAW.  EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
593
+HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
594
+OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
595
+THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
596
+PURPOSE.  THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
597
+IS WITH YOU.  SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
598
+ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
599
+
600
+  16. Limitation of Liability.
601
+
602
+  IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
603
+WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
604
+THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
605
+GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
606
+USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
607
+DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
608
+PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
609
+EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
610
+SUCH DAMAGES.
611
+
612
+  17. Interpretation of Sections 15 and 16.
613
+
614
+  If the disclaimer of warranty and limitation of liability provided
615
+above cannot be given local legal effect according to their terms,
616
+reviewing courts shall apply local law that most closely approximates
617
+an absolute waiver of all civil liability in connection with the
618
+Program, unless a warranty or assumption of liability accompanies a
619
+copy of the Program in return for a fee.
620
+
621
+                     END OF TERMS AND CONDITIONS
622
+
623
+            How to Apply These Terms to Your New Programs
624
+
625
+  If you develop a new program, and you want it to be of the greatest
626
+possible use to the public, the best way to achieve this is to make it
627
+free software which everyone can redistribute and change under these terms.
628
+
629
+  To do so, attach the following notices to the program.  It is safest
630
+to attach them to the start of each source file to most effectively
631
+state the exclusion of warranty; and each file should have at least
632
+the "copyright" line and a pointer to where the full notice is found.
633
+
634
+    <one line to give the program's name and a brief idea of what it does.>
635
+    Copyright (C) <year>  <name of author>
636
+
637
+    This program is free software: you can redistribute it and/or modify
638
+    it under the terms of the GNU General Public License as published by
639
+    the Free Software Foundation, either version 3 of the License, or
640
+    (at your option) any later version.
641
+
642
+    This program is distributed in the hope that it will be useful,
643
+    but WITHOUT ANY WARRANTY; without even the implied warranty of
644
+    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
645
+    GNU General Public License for more details.
646
+
647
+    You should have received a copy of the GNU General Public License
648
+    along with this program.  If not, see <http://www.gnu.org/licenses/>.
649
+
650
+Also add information on how to contact you by electronic and paper mail.
651
+
652
+  If the program does terminal interaction, make it output a short
653
+notice like this when it starts in an interactive mode:
654
+
655
+    <program>  Copyright (C) <year>  <name of author>
656
+    This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
657
+    This is free software, and you are welcome to redistribute it
658
+    under certain conditions; type `show c' for details.
659
+
660
+The hypothetical commands `show w' and `show c' should show the appropriate
661
+parts of the General Public License.  Of course, your program's commands
662
+might be different; for a GUI interface, you would use an "about box".
663
+
664
+  You should also get your employer (if you work as a programmer) or school,
665
+if any, to sign a "copyright disclaimer" for the program, if necessary.
666
+For more information on this, and how to apply and follow the GNU GPL, see
667
+<http://www.gnu.org/licenses/>.
668
+
669
+  The GNU General Public License does not permit incorporating your program
670
+into proprietary programs.  If your program is a subroutine library, you
671
+may consider it more useful to permit linking proprietary applications with
672
+the library.  If this is what you want to do, use the GNU Lesser General
673
+Public License instead of this License.  But first, please read
674
+<http://www.gnu.org/philosophy/why-not-lgpl.html>.

+ 26
- 0
INSTALL View File

@@ -0,0 +1,26 @@
1
+To use the Limited Medium wiki, please see the included README file instead of
2
+this INSTALL file. This file contains details about installing the Limited
3
+Medium server, which you shouldn't need if you only want to make a wiki.
4
+
5
+First, install the prerequisites:
6
+
7
+ * Python 2.5
8
+ * CherryPy 2.2
9
+ * simplejson 1.3
10
+
11
+If you're interested in running unit tests, also install:
12
+
13
+  * nose 0.9.0
14
+
15
+Run the server in development mode:
16
+
17
+  python2.5 limitedmedium.py -d
18
+
19
+Connect to the following URL in a web browser running on the same machine:
20
+
21
+  http://localhost:8080/
22
+
23
+You can run unit tests by running:
24
+
25
+  nosetests
26
+

+ 71
- 0
README View File

@@ -0,0 +1,71 @@
1
+Limited Medium
2
+
3
+http://somewhere
4
+
5
+Limited Medium is a lightweight personal wiki notebook for organizing your
6
+notes and ideas. It's designed for:
7
+
8
+ * Writers. Keep track of your characters, plots, and scenes.
9
+ * Students. Take notes and make links between related concepts.
10
+ * Game designers. Build up your world one detail at a time.
11
+ * Creative types. If you've outgrown a Word doc or text file full of
12
+   disorganized notes, Limited Medium can help.
13
+
14
+Here's how Limited Medium differs from other personal wikis:
15
+
16
+ * What you see is what you mean. You can forget about markup or markdown.
17
+ * Integrated viewing and editing. Update any wiki entry without switching
18
+   back and forth.
19
+ * View multiple wiki entries at once. Perfect for notes and brainstorming.
20
+ * Access your wiki from anywhere. All your work is automatically saved to the
21
+   server.
22
+ * Use any sort of link titles you want. Wiki links aren't expected to
23
+   LookLikeThis.
24
+
25
+Limited Medium also has the following features:
26
+
27
+ * Built-in searching. A single search looks through every word in the entire
28
+   wiki.
29
+
30
+Limited Medium makes use of some advanced browser features, so not all
31
+browsers will work for editing your wiki. Supported browsers include:
32
+
33
+ * Internet Explorer 6+
34
+ * Firefox 1.5+
35
+ * SeaMonkey 1.0+
36
+ * Iceweasel 1.5+
37
+ * Iceape 1.0+
38
+
39
+The following web browsers are known not to work with Limited Medium:
40
+
41
+ * Safari
42
+ * Opera
43
+ * Konqueror
44
+ * Lynx
45
+
46
+If you're looking for a personal wiki with more minimal browser requirements,
47
+you might want to try TiddlyWiki. If you're looking for a more general-purpose
48
+wiki for multiple users, check out MoinMoin.
49
+
50
+If you'd like to actually install the Limited Medium server, see the INSTALL
51
+file.
52
+
53
+Enjoy!
54
+
55
+Limited Medium Copyright (C) 2007 Dan Helfman
56
+
57
+This program is free software: you can redistribute it and/or modify
58
+it under the terms of the GNU General Public License as published by
59
+the Free Software Foundation, either version 3 of the License, or
60
+(at your option) any later version.
61
+
62
+This program is distributed in the hope that it will be useful,
63
+but WITHOUT ANY WARRANTY; without even the implied warranty of
64
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
65
+GNU General Public License for more details.
66
+
67
+You should have received a copy of the GNU General Public License
68
+along with this program.  If not, see <http://www.gnu.org/licenses/>.
69
+
70
+See the COPYING file for more information. Also note that MochiKit has its
71
+own separate license. See static/js/MochiKit_LICENSE.

+ 18
- 0
config/Common.py View File

@@ -0,0 +1,18 @@
1
+import cherrypy
2
+
3
+
4
+settings = { 
5
+  "global": {
6
+    "server.socket_port": 8080,
7
+    "server.environment": "production",
8
+    "session_filter.on": True,
9
+    "session_filter.storage_type": "file",
10
+    "session_filter.storage_path": "session",
11
+    "session_filter.timeout": 60 * 72, # 72 hours
12
+    "session_filter.clean_up_delay": 5,
13
+    "encoding_filter.on": True,
14
+    "encoding_filter.encoding": "utf-8",
15
+    "decoding_filter.on": True,
16
+    "decoding_filter.encoding": "utf-8",
17
+  },
18
+}

+ 19
- 0
config/Development.py View File

@@ -0,0 +1,19 @@
1
+import os
2
+import cherrypy
3
+
4
+
5
+settings = { 
6
+  "global": {
7
+    "server.thread_pool": 10,
8
+    "autoreload.on": True,
9
+    "static_filter.root": os.path.abspath( "." ),
10
+  },
11
+  "/static": {
12
+    "static_filter.on": True,
13
+    "static_filter.dir": "static",
14
+  },
15
+  "/favicon.ico": {
16
+    "static_filter.on": True,
17
+    "static_filter.file": "static/images/favicon.ico",
18
+  },
19
+}

+ 14
- 0
config/Production.py View File

@@ -0,0 +1,14 @@
1
+import cherrypy
2
+
3
+
4
+settings = { 
5
+  "global": {
6
+    "server.socket_queue_size": 15,
7
+    "server.thread_pool": 40,
8
+    "base_url_filter.on": True,
9
+    "base_url_filter.use_x_forwarded_host": True,
10
+    "server.log_to_screen": False,
11
+    "server.log_file": "limitedmedium.log",
12
+    "server.log_access_file": "limitedmedium.log",
13
+  },
14
+}

+ 0
- 0
config/__init__.py View File


+ 16
- 0
controller/Async.py View File

@@ -0,0 +1,16 @@
1
+import cherrypy
2
+
3
+
4
+def async( method ):
5
+  """
6
+  A decorator for a generator method that causes it to be invoked asynchronously. In other words,
7
+  whenever a generator method decorated by this decorator is called, its generator is added to
8
+  the scheduler for later execution.
9
+
10
+  This decorator expects a self.scheduler member containing the scheduler to use.
11
+  """
12
+  def schedule( self, *args, **kwargs ):
13
+    thread = method( self, *args, **kwargs )
14
+    self.scheduler.add( thread )
15
+  
16
+  return schedule

+ 214
- 0
controller/Database.py View File

@@ -0,0 +1,214 @@
1
+import re
2
+import bsddb
3
+import random
4
+import cPickle
5
+from cStringIO import StringIO
6
+from copy import copy
7
+from model.Persistent import Persistent
8
+from Async import async
9
+
10
+
11
+class Database( object ):
12
+  ID_BITS = 128 # number of bits within an id
13
+  ID_DIGITS = "0123456789abcdefghijklmnopqrstuvwxyz"
14
+
15
+  def __init__( self, scheduler, database_path = None ):
16
+    """
17
+    Create a new database and return it.
18
+
19
+    @type scheduler: Scheduler
20
+    @param scheduler: scheduler to use
21
+    @type database_path: unicode
22
+    @param database_path: path to the database file
23
+    @rtype: Database
24
+    @return: database at the given path
25
+    """
26
+    self.__scheduler = scheduler
27
+    self.__env = bsddb.db.DBEnv()
28
+    self.__env.open( None, bsddb.db.DB_CREATE | bsddb.db.DB_PRIVATE | bsddb.db.DB_INIT_MPOOL )
29
+    self.__db = bsddb.db.DB( self.__env )
30
+    self.__db.open( database_path, "database", bsddb.db.DB_HASH, bsddb.db.DB_CREATE )
31
+    self.__cache = {}
32
+
33
+  def __persistent_id( self, obj, skip = None ):
34
+    # save the object and return its persistent id
35
+    if obj != skip and isinstance( obj, Persistent ):
36
+      self.__save( obj )
37
+      return obj.object_id
38
+
39
+    # returning None indicates that the object should be pickled normally without using a persistent id
40
+    return None
41
+
42
+  @async
43
+  def save( self, obj, callback = None ):
44
+    """
45
+    Save the given object to the database, including any objects that it references.
46
+
47
+    @type obj: Persistent
48
+    @param obj: object to save
49
+    @type callback: generator or NoneType
50
+    @param callback: generator to wakeup when the save is complete (optional)
51
+    """
52
+    self.__save( obj )
53
+    yield callback
54
+
55
+  def __save( self, obj ):
56
+    # if this object's current revision is already saved, bail
57
+    revision_id = obj.revision_id()
58
+    if revision_id in self.__cache:
59
+      return
60
+
61
+    object_id = unicode( obj.object_id ).encode( "utf8" )
62
+    revision_id = unicode( obj.revision_id() ).encode( "utf8" )
63
+    secondary_id = obj.secondary_id and unicode( obj.secondary_id ).encode( "utf8" ) or None
64
+
65
+    # update the cache with this saved object
66
+    self.__cache[ object_id ] = obj
67
+    self.__cache[ revision_id ] = copy( obj )
68
+    if obj.secondary_id:
69
+      self.__cache[ secondary_id ] = obj
70
+
71
+    # set the pickler up to save persistent ids for every object except for the obj passed in, which
72
+    # will be pickled normally
73
+    buffer = StringIO()
74
+    pickler = cPickle.Pickler( buffer, protocol = -1 )
75
+    pickler.persistent_id = lambda o: self.__persistent_id( o, skip = obj )
76
+
77
+    # pickle the object and write it to the database under both its id key and its revision id key
78
+    pickler.dump( obj )
79
+    pickled = buffer.getvalue()
80
+    self.__db.put( object_id, pickled )
81
+    self.__db.put( revision_id, pickled )
82
+
83
+    # write the pickled object id (only) to the database under its secondary id
84
+    if obj.secondary_id:
85
+      buffer = StringIO()
86
+      pickler = cPickle.Pickler( buffer, protocol = -1 )
87
+      pickler.persistent_id = lambda o: self.__persistent_id( o )
88
+      pickler.dump( obj )
89
+      self.__db.put( secondary_id, buffer.getvalue() )
90
+
91
+    self.__db.sync()
92
+
93
+  @async
94
+  def load( self, object_id, callback, revision = None ):
95
+    """
96
+    Load the object corresponding to the given object id from the database, and yield the provided
97
+    callback generator with the loaded object as its argument, or None if the object_id is unknown.
98
+    If a revision is provided, a specific revision of the object will be loaded.
99
+
100
+    @type object_id: unicode
101
+    @param object_id: id of the object to load
102
+    @type callback: generator
103
+    @param callback: generator to send the loaded object to
104
+    @type revision: int or NoneType
105
+    @param revision: revision of the object to load (optional)
106
+    """
107
+    obj = self.__load( object_id, revision )
108
+    yield callback, obj
109
+
110
+  def __load( self, object_id, revision = None ):
111
+    if revision is not None:
112
+      object_id = Persistent.make_revision_id( object_id, revision )
113
+
114
+    object_id = unicode( object_id ).encode( "utf8" )
115
+
116
+    # if the object corresponding to the given id has already been loaded, simply return it without
117
+    # loading it again
118
+    obj = self.__cache.get( object_id )
119
+    if obj is not None:
120
+      return obj
121
+
122
+    # grab the object for the given id from the database
123
+    buffer = StringIO()
124
+    unpickler = cPickle.Unpickler( buffer )
125
+    unpickler.persistent_load = self.__load
126
+
127
+    pickled = self.__db.get( object_id )
128
+    if pickled is None or pickled == "":
129
+      return None
130
+
131
+    buffer.write( pickled )
132
+    buffer.flush()
133
+    buffer.seek( 0 )
134
+
135
+    # unpickle the object and update the cache with this saved object
136
+    obj = unpickler.load()
137
+    if obj is None:
138
+      print "error unpickling %s: %s" % ( object_id, pickled )
139
+      return None
140
+    self.__cache[ unicode( obj.object_id ).encode( "utf8" ) ] = obj
141
+    self.__cache[ unicode( obj.revision_id() ).encode( "utf8" ) ] = obj
142
+
143
+    return obj
144
+
145
+  @staticmethod
146
+  def generate_id():
147
+    int_id = random.getrandbits( Database.ID_BITS )
148
+
149
+    base = len( Database.ID_DIGITS )
150
+    digits = []
151
+
152
+    while True:
153
+      index = int_id % base
154
+      digits.insert( 0, Database.ID_DIGITS[ index ] )
155
+      int_id = int_id / base
156
+      if int_id == 0:
157
+        break
158
+
159
+    return "".join( digits )
160
+
161
+  @async
162
+  def next_id( self, callback ):
163
+    """
164
+    Generate the next available object id, and yielded the provided callback generator with the
165
+    object id as its argument.
166
+
167
+    @type callback: generator
168
+    @param callback: generator to send the next available object id to
169
+    """
170
+    # generate a random id, but on the off-chance that it collides with something else already in
171
+    # the database, try again
172
+    next_id = Database.generate_id()
173
+    while self.__db.get( next_id, default = None ) is not None:
174
+      next_id = Database.generate_id()
175
+
176
+    # save the next_id as a key in the database so that it's not handed out again to another client
177
+    self.__db[ next_id ] = ""
178
+
179
+    yield callback, next_id
180
+
181
+  @async
182
+  def close( self ):
183
+    """
184
+    Shutdown the database.
185
+    """
186
+    self.__db.close()
187
+    self.__env.close()
188
+    yield None
189
+
190
+  @async
191
+  def clear_cache( self ):
192
+    """
193
+    Clear the memory object cache.
194
+    """
195
+    self.__cache.clear()
196
+    yield None
197
+
198
+  scheduler = property( lambda self: self.__scheduler )
199
+
200
+
201
+class Valid_id( object ):
202
+  """
203
+  Validator for an object id.
204
+  """
205
+  ID_PATTERN = re.compile( "^[%s]+$" % Database.ID_DIGITS )
206
+
207
+  def __init__( self, none_okay = False ):
208
+    self.__none_okay = none_okay
209
+
210
+  def __call__( self, value ):
211
+    if self.__none_okay and value is None: return None
212
+    if self.ID_PATTERN.search( value ): return str( value )
213
+
214
+    raise ValueError()

+ 15
- 0
controller/Expire.py View File

@@ -0,0 +1,15 @@
1
+import cherrypy
2
+
3
+
4
+def strongly_expire( function ):
5
+    """
6
+    Decorator that sends headers that instruct browsers and proxies not to cache.
7
+    """
8
+    def expire( *args, **kwargs ):
9
+        cherrypy.response.headers[ "Expires" ] = "Sun, 19 Nov 1978 05:00:00 GMT"
10
+        cherrypy.response.headers[ "Cache-Control" ] = "no-store, no-cache, must-revalidate, post-check=0, pre-check=0"
11
+        cherrypy.response.headers[ "Pragma" ] = "no-cache"
12
+
13
+        return function( *args, **kwargs )
14
+
15
+    return expire

+ 87
- 0
controller/Expose.py View File

@@ -0,0 +1,87 @@
1
+import cherrypy
2
+
3
+from Validate import Validation_error
4
+
5
+# module-level variable that, when set to a view, overrides the view for all exposed methods. used
6
+# by unit tests
7
+view_override = None
8
+
9
+
10
+def expose( view = None, rss = None ):
11
+  """
12
+  expose() can be used to tag a method as available for publishing to the web via CherryPy. In
13
+  other words, methods that are not exposed cannot be accessed from the web.
14
+
15
+  The expose() method itself is evaluated where it is used as a decorator, which just puts the view
16
+  variable into the enclosing scope of the decorate() function and returns decorate() to be used as
17
+  the actual decorator.
18
+
19
+  Example usage:
20
+
21
+    @expose( view = Json )
22
+    def method(): pass
23
+  """
24
+  def decorate( function ):
25
+    """
26
+    When the method being decorated is invoked, its decorator gets invoked instead and is supposed
27
+    to return a new function to use in place of the method being decorated (or a modified version
28
+    of that function). In this case, the decorator is our decorate() function, and the function it
29
+    returns is the render() function. decorate()'s first argument is the method being decorated.
30
+    """
31
+    def render( *args, **kwargs ):
32
+      """
33
+      render() pretends that it's the method being decorated. It takes the same arguments and then
34
+      invokes the actual method being decorated, passing in those arguments.
35
+
36
+      With whatever result it gets from calling that method, render() invokes the view from the
37
+      outer scope to try to render it. It then results that rendered result.
38
+      """
39
+      result = {}
40
+
41
+      # if rss was requested, and this method was exposed for rss, then use rss as the view
42
+      if u"rss" in kwargs:
43
+        del kwargs[ u"rss" ]
44
+        use_rss = True
45
+      else:
46
+        use_rss = False
47
+
48
+      # kwarg names must be of type str, not unicode
49
+      kwargs = dict( [ ( str( key ), value ) for ( key, value ) in kwargs.items() ] )
50
+
51
+      # try executing the exposed function
52
+      try:
53
+        result = function( *args, **kwargs )
54
+      except Validation_error, error:
55
+        result = dict( name = error.name, value = error.value, error = error.message )
56
+
57
+      redirect = result.get( u"redirect", None )
58
+
59
+      # try using the supplied view to render the result
60
+      try:
61
+        if view_override is None:
62
+          if rss and use_rss:
63
+            cherrypy.response.headers[ u"Content-Type" ] = u"application/xml"
64
+            return unicode( rss( **result ) )
65
+          else:
66
+            return unicode( view( **result ) )
67
+        else:
68
+          return unicode( view_override( **result ) )
69
+      except:
70
+        if redirect is None:
71
+          print "error: %s" % result
72
+          raise
73
+
74
+      # if that doesn't work, and there's a redirect, then redirect
75
+      del( result[ u"redirect" ] )
76
+      from urllib import urlencode
77
+
78
+      if result == {}:
79
+        raise cherrypy.HTTPRedirect( u"%s" % redirect )
80
+      else:
81
+        url_args = urlencode( result )
82
+        raise cherrypy.HTTPRedirect( u"%s?%s" % ( redirect, url_args ) )
83
+
84
+    render.exposed = True
85
+    return render
86
+
87
+  return decorate

+ 146
- 0
controller/Html_cleaner.py View File

@@ -0,0 +1,146 @@
1
+# originally from http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/496942
2
+
3
+from htmllib import HTMLParser
4
+from cgi import escape
5
+from urlparse import urlparse
6
+from formatter import AbstractFormatter, NullWriter
7
+from htmlentitydefs import entitydefs
8
+from xml.sax.saxutils import quoteattr
9
+
10
+def xssescape(text):
11
+  """Gets rid of < and > and & and, for good measure, :"""
12
+  return escape(text, quote=True).replace(':','&#58;')
13
+
14
+class Html_cleaner(HTMLParser):
15
+  """
16
+  Cleans HTML of any tags not matching a whitelist.
17
+  """
18
+  def __init__( self ):
19
+    HTMLParser.__init__( self, AbstractFormatter( NullWriter() ) )
20
+    self.result = []
21
+    self.open_tags = []
22
+    # A list of the only tags allowed.  Be careful adding to this.  Adding
23
+    # "script," for example, would not be smart.  'img' is out by default 
24
+    # because of the danger of IMG embedded commands, and/or web bugs.
25
+    self.permitted_tags = [
26
+      'a',
27
+      'b',
28
+      'br',
29
+      'em',
30
+      'h3',
31
+      'i',
32
+      'li',
33
+      'ol',
34
+      'ul',
35
+      'p',
36
+      'strong',
37
+    ]
38
+
39
+    # A list of tags that are forcibly removed from the input. Tags that
40
+    # are not in permitted_tags and not in stripped_tags are simply
41
+    # escaped.
42
+    self.stripped_tags = [
43
+      'span',
44
+    ]
45
+
46
+    # A list of tags that require no closing tag.
47
+    self.requires_no_close = [ 'img', 'br' ]
48
+
49
+    # A dictionary showing the only attributes allowed for particular tags.
50
+    # If a tag is not listed here, it is allowed no attributes.  Adding
51
+    # "on" tags, like "onhover," would not be smart.  Also be very careful
52
+    # of "background" and "style."
53
+    self.allowed_attributes = {
54
+      'a': [ 'href' ],
55
+    }
56
+
57
+    # The only schemes allowed in URLs (for href and src attributes).
58
+    # Adding "javascript" or "vbscript" to this list would not be smart.
59
+    self.allowed_schemes = ['http','https','ftp', '']
60
+
61
+  def handle_data(self, data):
62
+    if data:
63
+      self.result.append( xssescape(data) )
64
+
65
+  def handle_charref(self, ref):
66
+    if len(ref) < 7 and ref.isdigit():
67
+      self.result.append( '&#%s;' % ref )
68
+    else:
69
+      self.result.append( xssescape('&#%s' % ref) )
70
+
71
+  def handle_entityref(self, ref):
72
+    if ref in entitydefs:
73
+      self.result.append( '&%s;' % ref )
74
+    else:
75
+      self.result.append( xssescape('&%s' % ref) )
76
+
77
+  def handle_comment(self, comment):
78
+    if comment:
79
+      self.result.append( xssescape("<!--%s-->" % comment) )
80
+
81
+  def handle_starttag(self, tag, method, attrs):
82
+    if tag not in self.permitted_tags:
83
+      if tag not in self.stripped_tags:
84
+        self.result.append( xssescape("<%s>" %  tag) )
85
+    else:
86
+      bt = "<" + tag
87
+      if tag in self.allowed_attributes:
88
+        attrs = dict(attrs)
89
+        self.allowed_attributes_here = \
90
+          [x for x in self.allowed_attributes[tag] if x in attrs \
91
+           and len(attrs[x]) > 0]
92
+        for attribute in self.allowed_attributes_here:
93
+          if attribute in ['href', 'src', 'background']:
94
+            if self.url_is_acceptable(attrs[attribute]):
95
+              bt += ' %s="%s"' % (attribute, attrs[attribute])
96
+          else:
97
+            bt += ' %s=%s' % \
98
+               (xssescape(attribute), quoteattr(attrs[attribute]))
99
+      if bt == "<a" or bt == "<img":
100
+        return
101
+      if tag in self.requires_no_close:
102
+        bt += "/"
103
+      bt += ">"           
104
+      self.result.append( bt )
105
+      self.open_tags.insert(0, tag)
106
+      
107
+  def handle_endtag(self, tag, attrs):
108
+    bracketed = "</%s>" % tag
109
+    if tag not in self.permitted_tags:
110
+      if tag not in self.stripped_tags:
111
+        self.result.append( xssescape(bracketed) )
112
+    elif tag in self.open_tags:
113
+      self.result.append( bracketed )
114
+      self.open_tags.remove(tag)
115
+      
116
+  def unknown_starttag(self, tag, attributes):
117
+    self.handle_starttag(tag, None, attributes)
118
+
119
+  def unknown_endtag(self, tag):
120
+    self.handle_endtag(tag, None)
121
+
122
+  def url_is_acceptable(self,url):
123
+    parsed = urlparse(url)
124
+    return parsed[0] in self.allowed_schemes
125
+
126
+  def strip(self, rawstring):
127
+    """Returns the argument stripped of potentially harmful HTML or Javascript code"""
128
+    self.reset()
129
+    self.result = []
130
+    self.feed(rawstring)
131
+    for endtag in self.open_tags:
132
+      if endtag not in self.requires_no_close:
133
+        self.result.append( "</%s>" % endtag )
134
+    return "".join( self.result )
135
+
136
+  def xtags(self):
137
+    """Returns a printable string informing the user which tags are allowed"""
138
+    self.permitted_tags.sort()
139
+    tg = ""
140
+    for x in self.permitted_tags:
141
+      tg += "<" + x
142
+      if x in self.allowed_attributes:
143
+        for y in self.allowed_attributes[x]:
144
+          tg += ' %s=""' % y
145
+      tg += "> "
146
+    return xssescape(tg.strip())

+ 52
- 0
controller/Html_nuker.py View File

@@ -0,0 +1,52 @@
1
+from htmllib import HTMLParser
2
+from formatter import AbstractFormatter, NullWriter
3
+
4
+
5
+class Html_nuker( HTMLParser ):
6
+  """
7
+  Nukes HTML of all tags.
8
+  """
9
+  def __init__( self, allow_refs = False ):
10
+    HTMLParser.__init__( self, AbstractFormatter( NullWriter() ) )
11
+    self.result = []
12
+    self.allow_refs = allow_refs
13
+
14
+  def handle_data( self, data ):
15
+    if data and "<" not in data and ">" not in data:
16
+      self.result.append( data )
17
+      
18
+  def handle_charref( self, ref ):
19
+    if self.allow_refs:
20
+      self.result.append( ref )
21
+
22
+  def handle_entityref( self, ref ):
23
+    if self.allow_refs:
24
+      self.result.append( ref )
25
+
26
+  def handle_comment( self, comment ):
27
+    pass
28
+
29
+  def handle_starttag( self, tag, method, attrs ):
30
+    pass
31
+      
32
+  def handle_endtag( self, tag, attrs ):
33
+    pass
34
+      
35
+  def unknown_starttag( self, tag, attributes ):
36
+    pass
37
+
38
+  def unknown_endtag( self, tag ):
39
+    pass
40
+
41
+  def nuke( self, rawstring ):
42
+    """
43
+    Nukes the given string of all HTML tags.
44
+    """
45
+    if rawstring is None:
46
+      return u""
47
+
48
+    self.reset()
49
+    self.result = []
50
+    self.feed( rawstring )
51
+
52
+    return u"".join( self.result )

+ 398
- 0
controller/Notebooks.py View File

@@ -0,0 +1,398 @@
1
+import cherrypy
2
+from Scheduler import Scheduler
3
+from Expose import expose
4
+from Validate import validate, Valid_string, Validation_error, Valid_bool
5
+from Database import Valid_id
6
+from Users import grab_user_id
7
+from Updater import wait_for_update, update_client
8
+from Expire import strongly_expire
9
+from Html_nuker import Html_nuker
10
+from Async import async
11
+from model.Notebook import Notebook
12
+from model.Entry import Entry
13
+from view.Main_page import Main_page
14
+from view.Json import Json
15
+from view.Entry_page import Entry_page
16
+from view.Html_file import Html_file
17
+
18
+
19
+class Access_error( Exception ):
20
+  def __init__( self, message = None ):
21
+    if message is None:
22
+      message = u"You don't have access to that notebook."
23
+
24
+    Exception.__init__( self, message )
25
+    self.__message = message
26
+
27
+  def to_dict( self ):
28
+    return dict(
29
+      error = self.__message
30
+    )
31
+
32
+
33
+class Notebooks( object ):
34
+  def __init__( self, scheduler, database ):
35
+    self.__scheduler = scheduler
36
+    self.__database = database
37
+
38
+  @expose( view = Main_page )
39
+  @validate(
40
+    notebook_id = Valid_id(),
41
+  )
42
+  def default( self, notebook_id ):
43
+    return dict(
44
+      notebook_id = notebook_id,
45
+    )
46
+
47
+  @expose( view = Json )
48
+  @strongly_expire
49
+  @wait_for_update
50
+  @grab_user_id
51
+  @async
52
+  @update_client
53
+  @validate(
54
+    notebook_id = Valid_id(),
55
+    user_id = Valid_id( none_okay = True ),
56
+  )
57
+  def contents( self, notebook_id, user_id ):
58
+    self.check_access( notebook_id, user_id, self.__scheduler.thread )
59
+    if not ( yield Scheduler.SLEEP ):
60
+      raise Access_error()
61
+
62
+    self.__database.load( notebook_id, self.__scheduler.thread )
63
+    notebook = ( yield Scheduler.SLEEP )
64
+
65
+    yield dict(
66
+      notebook = notebook,
67
+    )
68
+
69
+  @expose( view = Json )
70
+  @strongly_expire
71
+  @wait_for_update
72
+  @grab_user_id
73
+  @async
74
+  @update_client
75
+  @validate(
76
+    notebook_id = Valid_id(),
77
+    entry_id = Valid_id(),
78
+    user_id = Valid_id( none_okay = True ),
79
+  )
80
+  def load_entry( self, notebook_id, entry_id, user_id ):
81
+    self.check_access( notebook_id, user_id, self.__scheduler.thread )
82
+    if not ( yield Scheduler.SLEEP ):
83
+      raise Access_error()
84
+
85
+    self.__database.load( notebook_id, self.__scheduler.thread )
86
+    notebook = ( yield Scheduler.SLEEP )
87
+
88
+    if notebook is None:
89
+      entry = None
90
+    else:
91
+      entry = notebook.lookup_entry( entry_id )
92
+
93
+    yield dict(
94
+      entry = entry,
95
+    )
96
+
97
+  @expose( view = Json )
98
+  @strongly_expire
99
+  @wait_for_update
100
+  @grab_user_id
101
+  @async
102
+  @update_client
103
+  @validate(
104
+    notebook_id = Valid_id(),
105
+    entry_title = Valid_string( min = 1, max = 500 ),
106
+    user_id = Valid_id( none_okay = True ),
107
+  )
108
+  def load_entry_by_title( self, notebook_id, entry_title, user_id ):
109
+    self.check_access( notebook_id, user_id, self.__scheduler.thread )
110
+    if not ( yield Scheduler.SLEEP ):
111
+      raise Access_error()
112
+
113
+    self.__database.load( notebook_id, self.__scheduler.thread )
114
+    notebook = ( yield Scheduler.SLEEP )
115
+
116
+    if notebook is None:
117
+      entry = None
118
+    else:
119
+      entry = notebook.lookup_entry_by_title( entry_title )
120
+
121
+    yield dict(
122
+      entry = entry,
123
+    )
124
+
125
+  @expose( view = Json )
126
+  @wait_for_update
127
+  @grab_user_id
128
+  @async
129
+  @update_client
130
+  @validate(
131
+    notebook_id = Valid_id(),
132
+    entry_id = Valid_id(),
133
+    contents = Valid_string( min = 1, max = 25000, escape_html = False ),
134
+    startup = Valid_bool(),
135
+    user_id = Valid_id( none_okay = True ),
136
+  )
137
+  def save_entry( self, notebook_id, entry_id, contents, startup, user_id ):
138
+    self.check_access( notebook_id, user_id, self.__scheduler.thread )
139
+    if not ( yield Scheduler.SLEEP ):
140
+      raise Access_error()
141
+
142
+    self.__database.load( notebook_id, self.__scheduler.thread )
143
+    notebook = ( yield Scheduler.SLEEP )
144
+
145
+    if not notebook:
146
+      yield dict(
147
+        saved = False,
148
+      )
149
+      return
150
+
151
+    self.__database.load( entry_id, self.__scheduler.thread )
152
+    entry = ( yield Scheduler.SLEEP )
153
+
154
+    # if the entry is already in the database, load it and update it. otherwise, create it
155
+    if entry and entry in notebook.entries:
156
+      notebook.update_entry( entry, contents )
157
+    else:
158
+      entry = Entry( entry_id, contents )
159
+      notebook.add_entry( entry )
160
+
161
+    if startup:
162
+      notebook.add_startup_entry( entry )
163
+    else:
164
+      notebook.remove_startup_entry( entry )
165
+
166
+    self.__database.save( notebook )
167
+
168
+    yield dict(
169
+      saved = True,
170
+    )
171
+
172
+  @expose( view = Json )
173
+  @wait_for_update
174
+  @grab_user_id
175
+  @async
176
+  @update_client
177
+  @validate(
178
+    notebook_id = Valid_id(),
179
+    entry_id = Valid_id(),
180
+    user_id = Valid_id( none_okay = True ),
181
+  )
182
+  def add_startup_entry( self, notebook_id, entry_id, user_id ):
183
+    self.check_access( notebook_id, user_id, self.__scheduler.thread )
184
+    if not ( yield Scheduler.SLEEP ):
185
+      raise Access_error()
186
+
187
+    self.__database.load( notebook_id, self.__scheduler.thread )
188
+    notebook = ( yield Scheduler.SLEEP )
189
+
190
+    if not notebook:
191
+      yield dict()
192
+      return # TODO: raising an exception here would be nice
193
+
194
+    self.__database.load( entry_id, self.__scheduler.thread )
195
+    entry = ( yield Scheduler.SLEEP )
196
+
197
+    if entry:
198
+      notebook.add_startup_entry( entry )
199
+      self.__database.save( notebook )
200
+
201
+    yield dict()
202
+
203
+  @expose( view = Json )
204
+  @wait_for_update
205
+  @grab_user_id
206
+  @async
207
+  @update_client
208
+  @validate(
209
+    notebook_id = Valid_id(),
210
+    entry_id = Valid_id(),
211
+    user_id = Valid_id( none_okay = True ),
212
+  )
213
+  def remove_startup_entry( self, notebook_id, entry_id, user_id ):
214
+    self.check_access( notebook_id, user_id, self.__scheduler.thread )
215
+    if not ( yield Scheduler.SLEEP ):
216
+      raise Access_error()
217
+
218
+    self.__database.load( notebook_id, self.__scheduler.thread )
219
+    notebook = ( yield Scheduler.SLEEP )
220
+
221
+    if not notebook:
222
+      yield dict()
223
+      return # TODO: raising an exception here would be nice
224
+
225
+    self.__database.load( entry_id, self.__scheduler.thread )
226
+    entry = ( yield Scheduler.SLEEP )
227
+
228
+    if entry:
229
+      notebook.remove_startup_entry( entry )
230
+      self.__database.save( notebook )
231
+
232
+    yield dict()
233
+
234
+  @expose( view = Json )
235
+  @wait_for_update
236
+  @grab_user_id
237
+  @async
238
+  @update_client
239
+  @validate(
240
+    notebook_id = Valid_id(),
241
+    entry_id = Valid_id(),
242
+    user_id = Valid_id( none_okay = True ),
243
+  )
244
+  def delete_entry( self, notebook_id, entry_id, user_id ):
245
+    self.check_access( notebook_id, user_id, self.__scheduler.thread )
246
+    if not ( yield Scheduler.SLEEP ):
247
+      raise Access_error()
248
+
249
+    self.__database.load( notebook_id, self.__scheduler.thread )
250
+    notebook = ( yield Scheduler.SLEEP )
251
+
252
+    if not notebook:
253
+      yield dict()
254
+      return # TODO: raising an exception here would be nice
255
+
256
+    self.__database.load( entry_id, self.__scheduler.thread )
257
+    entry = ( yield Scheduler.SLEEP )
258
+
259
+    if entry:
260
+      notebook.remove_entry( entry )
261
+      self.__database.save( notebook )
262
+
263
+    yield dict()
264
+
265
+  @expose( view = Entry_page )
266
+  @validate( id = Valid_id() )
267
+  def blank_entry( self, id ):
268
+    return dict( id = id )
269
+
270
+  @expose( view = Json )
271
+  @strongly_expire
272
+  @wait_for_update
273
+  @grab_user_id
274
+  @async
275
+  @update_client
276
+  @validate(
277
+    notebook_id = Valid_id(),
278
+    search_text = Valid_string( min = 0, max = 100 ),
279
+    user_id = Valid_id( none_okay = True ),
280
+  )
281
+  def search( self, notebook_id, search_text, user_id ):
282
+    self.check_access( notebook_id, user_id, self.__scheduler.thread )
283
+    if not ( yield Scheduler.SLEEP ):
284
+      raise Access_error()
285
+
286
+    self.__database.load( notebook_id, self.__scheduler.thread )
287
+    notebook = ( yield Scheduler.SLEEP )
288
+
289
+    if not notebook:
290
+      yield dict(
291
+        entries = [],
292
+      )
293
+      return
294
+
295
+    search_text = search_text.lower()
296
+    title_matches = []
297
+    content_matches = []
298
+    nuker = Html_nuker()
299
+
300
+    if len( search_text ) > 0:
301
+      for entry in notebook.entries:
302
+        if search_text in nuker.nuke( entry.title ).lower():
303
+          title_matches.append( entry )
304
+        elif search_text in nuker.nuke( entry.contents ).lower():
305
+          content_matches.append( entry )
306
+
307
+    entries = title_matches + content_matches
308
+
309
+    yield dict(
310
+      entries = entries,
311
+    )
312
+
313
+  @expose( view = Json )
314
+  @strongly_expire
315
+  @wait_for_update
316
+  @grab_user_id
317
+  @async
318
+  @update_client
319
+  @validate(
320
+    notebook_id = Valid_id(),
321
+    user_id = Valid_id( none_okay = True ),
322
+  )
323
+  def recent_entries( self, notebook_id, user_id ):
324
+    self.check_access( notebook_id, user_id, self.__scheduler.thread )
325
+    if not ( yield Scheduler.SLEEP ):
326
+      raise Access_error()
327
+
328
+    self.__database.load( notebook_id, self.__scheduler.thread )
329
+    notebook = ( yield Scheduler.SLEEP )
330
+
331
+    if not notebook:
332
+      yield dict(
333
+        entries = [],
334
+      )
335
+      return
336
+
337
+    RECENT_COUNT = 10
338
+    entries = notebook.entries
339
+    entries.sort( lambda a, b: cmp( b.revision, a.revision ) )
340
+
341
+    yield dict(
342
+      entries = entries[ :RECENT_COUNT ],
343
+    )
344
+
345
+  @expose( view = Html_file )
346
+  @strongly_expire
347
+  @wait_for_update
348
+  @grab_user_id
349
+  @async
350
+  @update_client
351
+  @validate(
352
+    notebook_id = Valid_id(),
353
+    user_id = Valid_id( none_okay = True ),
354
+  )
355
+  def download_html( self, notebook_id, user_id ):
356
+    self.check_access( notebook_id, user_id, self.__scheduler.thread )
357
+    if not ( yield Scheduler.SLEEP ):
358
+      raise Access_error()
359
+
360
+    self.__database.load( notebook_id, self.__scheduler.thread )
361
+    notebook = ( yield Scheduler.SLEEP )
362
+
363
+    if not notebook:
364
+      yield dict(
365
+        notebook_name = None,
366
+        entries = [],
367
+      )
368
+      return
369
+
370
+    normal_entries = list( set( notebook.entries ) - set( notebook.startup_entries ) )
371
+    normal_entries.sort( lambda a, b: -cmp( a.revision, b.revision ) )
372
+    
373
+    yield dict(
374
+      notebook_name = notebook.name,
375
+      entries = notebook.startup_entries + normal_entries,
376
+    )
377
+
378
+  @async
379
+  def check_access( self, notebook_id, user_id, callback ):
380
+    # check if the anonymous user has access to this notebook
381
+    self.__database.load( u"anonymous", self.__scheduler.thread )
382
+    anonymous = ( yield Scheduler.SLEEP )
383
+
384
+    access = False
385
+    if anonymous.has_access( notebook_id ):
386
+      access = True
387
+
388
+    if user_id:
389
+      # check if the currently logged in user has access to this notebook
390
+      self.__database.load( user_id, self.__scheduler.thread )
391
+      user = ( yield Scheduler.SLEEP )
392
+
393
+      if user.has_access( notebook_id ):
394
+        access = True
395
+
396
+    yield callback, access
397
+
398
+  scheduler = property( lambda self: self.__scheduler )

+ 60
- 0
controller/Root.py View File

@@ -0,0 +1,60 @@
1
+import cherrypy
2
+
3
+from Scheduler import Scheduler
4
+from Expose import expose
5
+from Validate import validate
6
+from Async import async
7
+from Notebooks import Notebooks
8
+from Users import Users
9
+from Updater import update_client, wait_for_update
10
+from view.Main_page import Main_page
11
+from view.Json import Json
12
+from view.Error_page import Error_page
13
+from view.Not_found_page import Not_found_page
14
+
15
+
16
+class Root( object ):
17
+  def __init__( self, scheduler, database ):
18
+    self.__scheduler = scheduler
19
+    self.__database = database
20
+    self.__notebooks = Notebooks( scheduler, database )
21
+    self.__users = Users( scheduler, database )
22
+
23
+  @expose( view = Main_page )
24
+  def index( self ):
25
+    """
26
+    Provide the information necessary to display the web site's front page.
27
+    """
28
+    return dict()
29
+
30
+  @expose( view = Json )
31
+  @wait_for_update
32
+  @async
33
+  @update_client
34
+  def next_id( self ):
35
+    self.__database.next_id( self.__scheduler.thread )
36
+    next_id = ( yield Scheduler.SLEEP )
37
+
38
+    yield dict(
39
+      next_id = next_id,
40
+    )
41
+
42
+  def _cp_on_http_error( self, status, message ):
43
+    """
44
+    CherryPy HTTP error handler, used to display page not found and generic error pages.
45
+    """
46
+    if status == 404:
47
+      cherrypy.response.headerMap[ u"Status" ] = u"404 Not Found"
48
+      cherrypy.response.status = status
49
+      cherrypy.response.body = [ unicode( Not_found_page() ) ]
50
+      return
51
+
52
+    import traceback
53
+    traceback.print_exc()
54
+
55
+    cherrypy.response.body = [ unicode( Error_page() ) ]
56
+
57
+  scheduler = property( lambda self: self.__scheduler )
58
+  database = property( lambda self: self.__database )
59
+  notebooks = property( lambda self: self.__notebooks )
60
+  users = property( lambda self: self.__users )

+ 123
- 0
controller/Scheduler.py View File

@@ -0,0 +1,123 @@
1
+from time import time, sleep
2
+from threading import Thread, Event
3
+
4
+
5
+class Scheduler( object ):
6
+  SLEEP = 0      # yielded by a generator to indicate that it should be put to sleep
7
+
8
+  def __init__( self ):
9
+    """
10
+    A scheduler for generator-based microthreads.
11
+    """
12
+    self.__running = []  # list of active microthreads
13
+    self.__sleeping = [] # list of sleeping microthreads
14
+    self.__messages = {} # map of thread to list of its incoming messages
15
+    self.__thread = None # currently executing microthread (if any)
16
+    self.__done = False  # whether it's time to exit
17
+    self.__no_longer_idle = Event()
18
+    self.__last_error = None # used for unit tests
19
+
20
+    self.add( self.__idle_thread() )
21
+
22
+    self.__scheduler_thread = Thread( target = self.run )
23
+    self.__scheduler_thread.setDaemon( True )
24
+    self.__scheduler_thread.start()
25
+
26
+  def run( self ):
27
+    """
28
+    Run all threads repeatedly.
29
+    """
30
+    while not self.__done:
31
+      self.__run_once()
32
+
33
+  def __run_once( self ):
34
+    """
35
+    Run all active threads once.
36
+    """
37
+    turn_start = time()
38
+
39
+    for thread in list( self.__running ):
40
+      try:
41
+        messages = self.__messages.get( thread )
42
+
43
+        self.__thread = thread
44
+        try:
45
+          if messages:
46
+            result = thread.send( *messages.pop( 0 ) )
47
+          else:
48
+            result = thread.next()
49
+        except StopIteration:
50
+          raise
51
+        except Exception, e:
52
+          self.__last_error = e
53
+          import traceback
54
+          traceback.print_exc()
55
+          raise StopIteration()
56
+
57
+        self__thread = None
58
+
59
+        if self.__done:
60
+          return True
61
+
62
+        if result is None:
63
+          continue
64
+
65
+        # a yielded result of SLEEP indicates to put the thread to sleep
66
+        if result == Scheduler.SLEEP:
67
+          self.sleep( thread )
68
+        # any other result indicates to run the yielded thread
69
+        elif isinstance( result, ( tuple, list ) ):
70
+          self.add( *result )
71
+        else:
72
+          self.add( result )
73
+        
74
+      except StopIteration:
75
+        self.__running.remove( thread )
76
+        self.__messages.pop( thread, None )
77
+
78
+  def __idle_thread( self ):
79
+    while not self.__done:
80
+      # if the idle thread is the only one running, block until there's another running thread
81
+      if len( self.__running ) == 1:
82
+        self.__no_longer_idle.wait()
83
+        self.__no_longer_idle.clear()
84
+
85
+      yield None
86
+
87
+  # used for unit tests
88
+  IDLE_SLEEP_SECONDS = 0.01
89
+  def wait_for( self, thread ):
90
+    while thread in self.__running or thread in self.__sleeping:
91
+      sleep( self.IDLE_SLEEP_SECONDS )
92
+
93
+    if self.__last_error:
94
+      raise self.__last_error
95
+
96
+  def wait_until_idle( self ):
97
+    while len( self.__running ) > 1 or len( self.__sleeping ) > 0:
98
+      sleep( self.IDLE_SLEEP_SECONDS )
99
+
100
+  def sleep( self, thread ):
101
+    self.__sleeping.append( thread )
102
+    self.__running.remove( thread )
103
+
104
+  def add( self, thread, *args ):
105
+    self.__no_longer_idle.set()
106
+
107
+    if thread in self.__sleeping:
108
+      self.__sleeping.remove( thread )
109
+    else:
110
+      self.__messages[ thread ] = [ ( None, ) ]
111
+
112
+    self.__running.append( thread )
113
+
114
+    if len( args ) > 0:
115
+      self.__messages[ thread ].append( args )
116
+
117
+  def shutdown( self ):
118
+    self.__done = True
119
+    self.__no_longer_idle.set()
120
+    self.__scheduler_thread.join()
121
+
122
+  # currently executing microthread (if any)
123
+  thread = property( lambda self: self.__thread )

+ 70
- 0
controller/Updater.py View File

@@ -0,0 +1,70 @@
1
+from Queue import Queue, Empty
2
+
3
+
4
+TIMEOUT_SECONDS = 10.0
5
+
6
+
7
+def wait_for_update( function ):
8
+  """
9
+  A decorator that passes a "queue" keyword arugment to its decorated function, calls the function,
10
+  and then blocks until an asynchronous response comes back via the Queue. When a response is
11
+  received, wait_for_update() returns it.
12
+
13
+  For this decorator to be useful, you should use it to decorate a function that fires off some
14
+  asynchronous action and then returns immediately. A typical way to accomplish this is by using
15
+  the @async decorator after the @wait_for_update decorator.
16
+  """
17
+  def get_message( *args, **kwargs ):
18
+    queue = Queue()
19
+
20
+    kwargs[ "queue" ] = queue
21
+    function( *args, **kwargs )
22
+
23
+    # wait until a response is available in the queue, and then return that response
24
+    try:
25
+      return queue.get( block = True, timeout = TIMEOUT_SECONDS )
26
+    except Empty:
27
+      return { "error": u"A timeout occurred when processing your request. Please try again." }
28
+
29
+  return get_message
30
+
31
+
32
+def update_client( function ):
33
+  """
34
+  A decorator used to wrap a generator function so that its yielded values can be issued as
35
+  updates to the client. For this to work, the generator function must be invoked with a keyword
36
+  argument "queue" containing a Queue where the result can be put().
37
+
38
+  Also supports catching Validation_error exceptions and sending appropriate errors to the client.
39
+
40
+  Note that this decorator itself is a generator function and works by passing along next()/send()
41
+  calls to its decorated generator. Only yielded values that are dictionaries are sent to the
42
+  client. All other yielded values are in turn yielded by this decorator itself.
43
+  """
44
+  def put_message( *args, **kwargs ):
45
+    # look in the called function's kwargs for the queue where results should be sent
46
+    queue = kwargs.pop( "queue" )
47
+
48
+    try:
49
+      generator = function( *args, **kwargs )
50
+      message = None
51
+
52
+      while True:
53
+        result = generator.send( message )
54
+
55
+        if isinstance( result, dict ):
56
+          queue.put( result )
57
+          message = ( yield None )
58
+        else:
59
+          message = ( yield result )
60
+    except StopIteration:
61
+      return
62
+    except Exception, error:
63
+      # TODO: might be better to use view.Json instead of calling to_dict() manually
64
+      if hasattr( error, "to_dict" ):
65
+        result = error.to_dict()
66
+        queue.put( result )
67
+      else:
68
+        raise
69
+  
70
+  return put_message

+ 232
- 0
controller/Users.py View File

@@ -0,0 +1,232 @@
1
+import re
2
+import cherrypy
3
+from model.User import User
4
+from model.Notebook import Notebook
5
+from model.Entry import Entry
6
+from Scheduler import Scheduler
7
+from Expose import expose
8
+from Validate import validate, Valid_string, Validation_error
9
+from Database import Valid_id
10
+from Updater import update_client, wait_for_update
11
+from Expire import strongly_expire
12
+from Async import async
13
+from view.Json import Json
14
+
15
+
16
+USERNAME_PATTERN = re.compile( "^[a-zA-Z0-9]+$" )
17
+EMAIL_ADDRESS_PATTERN = re.compile( "^[\w.+]+@\w+(\.\w+)+$" )
18
+
19
+
20
+def valid_username( username ):
21
+  if USERNAME_PATTERN.search( username ) is None:
22
+    raise ValueError()
23
+
24
+  return username
25
+
26
+valid_username.message = u"can only contain letters and digits"
27
+
28
+
29
+def valid_email_address( email_address ):
30
+  if email_address == "" or EMAIL_ADDRESS_PATTERN.search( email_address ) is None:
31
+    raise ValueError()
32
+
33
+  return email_address
34
+
35
+
36
+class Signup_error( Exception ):
37
+  def __init__( self, message ):
38
+    Exception.__init__( self, message )
39
+    self.__message = message
40
+
41
+  def to_dict( self ):
42
+    return dict(
43
+      error = self.__message
44
+    )
45
+
46
+
47
+class Authentication_error( Exception ):
48
+  def __init__( self, message ):
49
+    Exception.__init__( self, message )
50
+    self.__message = message
51
+
52
+  def to_dict( self ):
53
+    return dict(
54
+      error = self.__message
55
+    )
56
+
57
+
58
+def grab_user_id( function ):
59
+  """
60
+  A decorator to grab the current logged in user id from the cherrypy session and pass it as a
61
+  user_id argument to the decorated function. This decorator must be used from within the main
62
+  cherrypy request thread.
63
+  """
64
+  def get_id( *args, **kwargs ):
65
+    arg_names = list( function.func_code.co_varnames )
66
+    if "user_id" in arg_names:
67
+      arg_index = arg_names.index( "user_id" )
68
+      args[ arg_index ] = cherrypy.session.get( "user_id" )
69
+    else:
70
+      kwargs[ "user_id" ] = cherrypy.session.get( "user_id" )
71
+
72
+    return function( *args, **kwargs )
73
+  
74
+  return get_id
75
+
76
+
77
+def update_auth( function ):
78
+  """
79
+  Based on the return value of the decorated function, update the current session's authentication
80
+  status. This decorator must be used from within the main cherrypy request thread.
81
+
82
+  If the return value of the decorated function (which is expected to be a dictionary) contains an
83
+  "authenticated" key with a User value, then mark the user as logged in. If the return value of the
84
+  decorated function contains a "deauthenticated" key with any value, then mark the user as logged
85
+  out.
86
+  """
87
+  def handle_result( *args, **kwargs ):
88
+    result = function( *args, **kwargs )
89
+
90
+    # peek in the function's return value to see if we should tweak authentication status
91
+    user = result.get( "authenticated" )
92
+    if user:
93
+      cherrypy.session[ u"user_id" ] = user.object_id
94
+      cherrypy.session[ u"username" ] = user.username
95
+
96
+    if result.get( "deauthenticated" ):
97
+      cherrypy.session.pop( u"user_id", None )
98
+      cherrypy.session.pop( u"username", None )
99
+
100
+    return result
101
+
102
+  return handle_result
103
+
104
+
105
+class Users( object ):
106
+  def __init__( self, scheduler, database ):
107
+    self.__scheduler = scheduler
108
+    self.__database = database
109
+
110
+  @expose( view = Json )
111
+  @update_auth
112
+  @wait_for_update
113
+  @async
114
+  @update_client
115
+  @validate(
116
+    username = ( Valid_string( min = 1, max = 30 ), valid_username ),
117
+    password = Valid_string( min = 1, max = 30 ),
118
+    password_repeat = Valid_string( min = 1, max = 30 ),
119
+    email_address = ( Valid_string( min = 1, max = 60 ), valid_email_address ),
120
+    signup_button = unicode,
121
+  )
122
+  def signup( self, username, password, password_repeat, email_address, signup_button ):
123
+    if password != password_repeat:
124
+      raise Signup_error( u"The passwords you entered do not match. Please try again." )
125
+
126
+    self.__database.load( username, self.__scheduler.thread )
127
+    user = ( yield Scheduler.SLEEP )
128
+
129
+    if user is not None:
130
+      raise Signup_error( u"Sorry, that username is not available. Please try something else." )
131
+
132
+    # create a notebook for this user
133
+    self.__database.next_id( self.__scheduler.thread )
134
+    notebook_id = ( yield Scheduler.SLEEP )
135
+    notebook = Notebook( notebook_id, u"my notebook" )
136
+
137
+    # create a startup entry for this user's notebook
138
+    self.__database.next_id( self.__scheduler.thread )
139
+    entry_id = ( yield Scheduler.SLEEP )
140
+    entry = Entry( entry_id, file( u"static/html/welcome to your wiki.html" ).read() )
141
+    notebook.add_entry( entry )
142
+    notebook.add_startup_entry( entry )
143
+
144
+    # actually create the new user
145
+    self.__database.next_id( self.__scheduler.thread )
146
+    user_id = ( yield Scheduler.SLEEP )
147
+
148
+    user = User( user_id, username, password, email_address, notebooks = [ notebook ] )
149
+    self.__database.save( user )
150
+
151
+    redirect = u"/notebooks/%s" % notebook.object_id
152
+
153
+    yield dict(
154
+      redirect = redirect,
155
+      authenticated = user,
156
+    )
157
+
158
+  @expose( view = Json )
159
+  @update_auth
160
+  @wait_for_update
161
+  @async
162
+  @update_client
163
+  @validate(
164
+    username = ( Valid_string( min = 1, max = 30 ), valid_username ),
165
+    password = Valid_string( min = 1, max = 30 ),
166
+    login_button = unicode,
167
+  )
168
+  def login( self, username, password, login_button ):
169
+    self.__database.load( username, self.__scheduler.thread )
170
+    user = ( yield Scheduler.SLEEP )
171
+
172
+    if user is None or user.check_password( password ) is False:
173
+      raise Authentication_error( u"Invalid username or password." )
174
+
175
+    # redirect to the user's first notebook (if any)
176
+    if len( user.notebooks ) > 0:
177
+      redirect = u"/notebooks/%s" % user.notebooks[ 0 ].object_id
178
+    else:
179
+      redirect = u"/"
180
+
181
+    yield dict(
182
+      redirect = redirect,
183
+      authenticated = user,
184
+    )
185
+
186
+  @expose( view = Json )
187
+  @update_auth
188
+  @wait_for_update
189
+  @async
190
+  @update_client
191
+  def logout( self ):
192
+    yield dict(
193
+      redirect = u"/",
194
+      deauthenticated = True,
195
+    )
196
+
197
+  @expose( view = Json )
198
+  @strongly_expire
199
+  @grab_user_id
200
+  @wait_for_update
201
+  @async
202
+  @update_client
203
+  @validate(
204
+    user_id = Valid_id( none_okay = True ),
205
+  )
206
+  def current( self, user_id ):
207
+    # if there's no logged-in user, default to the anonymous user
208
+    self.__database.load( user_id or u"anonymous", self.__scheduler.thread )
209
+    user = ( yield Scheduler.SLEEP )
210
+
211
+    if not user:
212
+      yield dict(
213
+        user = None,
214
+        notebooks = None,
215
+      )
216
+      return
217
+
218
+    # in addition to this user's own notebooks, add to that list the anonymous user's notebooks
219
+    if user_id:
220
+      self.__database.load( u"anonymous", self.__scheduler.thread )
221
+      anonymous = ( yield Scheduler.SLEEP )
222
+      notebooks = anonymous.notebooks
223
+    else:
224
+      notebooks = []
225
+    notebooks += user.notebooks
226
+
227
+    yield dict(
228
+      user = user,
229
+      notebooks = notebooks,
230
+    )
231
+
232
+  scheduler = property( lambda self: self.__scheduler )

+ 244
- 0
controller/Validate.py View File

@@ -0,0 +1,244 @@
1
+import cherrypy
2
+from cgi import escape
3
+from Html_cleaner import Html_cleaner
4
+
5
+
6
+class Validation_error( Exception ):
7
+  """
8
+  An exception raised when form validation fails for some reason.
9
+  """
10
+
11
+  MESSAGE_MAP = {
12
+    int: u"can only contain digits",
13
+  }
14
+
15
+  def __init__( self, name, value, value_type, message = None ):
16
+    Exception.__init__( self )
17
+    self.__name = name
18
+    self.__value = value
19
+    self.__value_type = value_type
20
+
21
+    if message is None:
22
+      # if the value's type has a message member, use that. otherwise, look up the type in a map
23
+      if hasattr( value_type, u"message" ):
24
+        self.__message = value_type.message
25
+      else:
26
+        self.__message = self.MESSAGE_MAP.get( value_type, u"is invalid" )
27
+    else:
28
+      self.__message = message
29
+
30
+  def __str__( self ):
31
+    return self.__message
32
+
33
+  def to_dict( self ):
34
+    return dict(
35
+      error = u"The %s %s." % ( self.__name, self.__message ),
36
+      name = self.__name,
37
+      value = self.__value,
38
+    )
39
+
40
+  name = property( lambda self: self.__name )
41
+  value = property( lambda self: self.__value )
42
+  value_type = property( lambda self: self.__value_type )
43
+  message = property( lambda self: self.__message )
44
+
45
+
46
+class Valid_string( object ):
47
+  """
48
+  Validator for a string of certain minimum and maximum lengths.
49
+  """
50
+  moron_map = {
51
+    u"\xa0": u" ",
52
+    u"\xa9": u"(c)",
53
+    u"\xae": u"(r)",
54
+    u"\xb7": u"*",
55
+    u"\u2002": u" ",
56
+    u"\u2003": u" ",
57
+    u"\u2009": u" ",
58
+    u"\u2010": u"-",
59
+    u"\u2011": u"-",
60
+    u"\u2013": u"-",
61
+    u"\u2014": u"--",
62
+    u"\u2015": u"--",
63
+    u"\u2016": u"--",
64
+    u"\u2017": u"||",
65
+    u"\u2018": u"'",
66
+    u"\u2019": u"'",
67
+    u"\u201a": u",",
68
+    u"\u201b": u"'",
69
+    u"\u201c": u'"',
70
+    u"\u201d": u'"',
71
+    u"\u201e": u",,",
72
+    u"\u201f": u'"',
73
+    u"\u2022": u"*",
74
+    u"\u2023": u"*",
75
+    u"\u2024": u".",
76
+    u"\u2025": u"..",
77
+    u"\u2026": u"...",
78
+    u"\u2027": u".",
79
+    u"\u2122": u"(tm)",
80
+  }
81
+
82
+  def __init__( self, min = None, max = None, escape_html = True ):
83
+    self.min = min
84
+    self.max = max
85
+    self.escape_html = escape_html
86
+    self.message = None
87
+
88
+  def __call__( self, value ):
89
+    value = self.__demoronize( value.strip() )
90
+
91
+    if self.min is not None and len( value ) < self.min:
92
+      if self.min == 1:
93
+        self.message = u"is missing"
94
+      else:
95
+        self.message = u"must be at least %s characters long" % self.min
96
+      raise ValueError()
97
+    elif self.max is not None and len( value ) > self.max:
98
+      self.message = u"must be no longer than %s characters" % self.max
99
+      raise ValueError()
100
+
101
+    # either escape all html completely or just clean up the html, stripping out everything that's
102
+    # not on a tag/attribute whitelist
103
+    if self.escape_html:
104
+      return escape( value, quote = True )
105
+    else:
106
+      cleaner = Html_cleaner()
107
+      return cleaner.strip( value )
108
+
109
+  def __demoronize( self, value ):
110
+    """
111
+    Convert stupid Microsoft unicode symbols to saner, cross-platform equivalents.
112
+    """
113
+    try:
114
+      for ( moron_symbol, replacement ) in self.moron_map.items():
115
+        value = value.replace( moron_symbol, replacement )
116
+    except:
117
+      import traceback
118
+      traceback.print_exc()
119
+      raise
120
+
121
+    return value
122
+
123
+
124
+class Valid_bool( object ):
125
+  """
126
+  Validator for a boolean value.
127
+  """
128
+  def __call__( self, value ):
129
+    value = value.strip()
130
+
131
+    if value in ( u"True", u"true" ): return True
132
+    if value in ( u"False", u"false" ): return False
133
+
134
+    raise ValueError()
135
+
136
+
137
+def validate( **kwarg_types ):
138
+  """
139
+  validate() can be used to require that the arguments of the decorated method successfully pass
140
+  through particular validators. The validate() method itself is evaluated where it is used as a
141
+  decorator, which just returns decorate() to be used as the actual decorator.
142
+
143
+  Example usage:
144
+
145
+    @validate(
146
+      foo = Valid_string( min = 5, max = 10 ),
147
+      bar = int
148
+    )
149
+    def method( self, foo, bar ): pass
150
+
151
+  Note that validate() currently only works for instance methods (methods that take self as the
152
+  first argument). Also note that you can use multiple validators for a single argument.
153
+
154
+  Example usage:
155
+
156
+    @validate(
157
+      foo = Valid_string( min = 5, max = 10 ),
158
+      bar = ( int, valid_bar )
159
+    )
160
+    def method( self, foo, bar ): pass
161
+
162
+  """
163
+  def decorate( function ):
164
+    """
165
+    When the method being decorated is invoked, its decorator gets invoked instead and is supposed
166
+    to return a new function to use in place of the method being decorated (or a modified version
167
+    of that function). In this case, the decorator is our decorate() function, and the function it
168
+    returns is the check() function. decorate()'s first argument is the method being decorated.
169
+    """
170
+    def check( *args, **kwargs ):
171
+      """
172
+      check() pretends that it's the method being decorated. It takes the same arguments and then
173
+      invokes the actual method being decorated, passing in those arguments, but only after first
174
+      validating all of those arguments to that function. If validation fails, a Validation_error
175
+      is raised. Note that in Python, keyword argument names have to be str, not unicode.
176
+      """
177
+      args = list( args )
178
+      args_index = 1 # skip the self argument
179
+
180
+      for ( arg_name, arg_type ) in kwarg_types.items():
181
+        if arg_name == u"kwargs":
182
+          key_type = kwarg_types[ u"kwargs" ].keys()[ 0 ]
183
+          value_type = kwarg_types[ u"kwargs" ].values()[ 0 ]
184
+
185
+          for ( key, value ) in kwargs.items():
186
+            if key not in kwarg_types:
187
+              del( kwargs[ key ] )
188
+              try:
189
+                kwargs[ str( key_type( key ) ) ] = value_type( value )
190
+              except ( ValueError, TypeError ):
191
+                raise Validation_error( key, value, value_type )
192
+
193
+          continue
194
+
195
+        # look for arg_name in kwargs and store the validated value there
196
+        if arg_name in kwargs:
197
+          value = kwargs.get( arg_name )
198
+          # if there's a tuple of multiple validators for this arg_name, use all of them
199
+          if isinstance( arg_type, tuple ):
200
+            for validator in arg_type:
201
+              try:
202
+                value = validator( value )
203
+              except ( ValueError, TypeError ):
204
+                raise Validation_error( arg_name, value, validator )
205
+            kwargs[ str( arg_name ) ] = value
206
+          # otherwise, there's just a single validator
207
+          else:
208
+            try:
209
+              kwargs[ str( arg_name ) ] = arg_type( value )
210
+            except ( ValueError, TypeError ):
211
+              raise Validation_error( arg_name, value, arg_type )
212
+          continue
213
+
214
+        # arg_name wasn't found in kwargs, so use args instead
215
+        if args_index >= len( args ):
216
+          raise Validation_error( arg_name, None, arg_type, message = u"is required" )
217
+        value = args[ args_index ]
218
+
219
+        # if there's a tuple of multiple validators for this arg_name, use all of them
220
+        if isinstance( arg_type, tuple ):
221
+          for validator in arg_type:
222
+            try:
223
+              value = validator( value )
224
+            except ( ValueError, TypeError ):
225
+              raise Validation_error( arg_name, value, validator )
226
+          args[ args_index ] = value
227
+        # otherwise, there's just a single validator
228
+        else:
229
+          try:
230
+            args[ args_index ] = arg_type( value )
231
+          except ( ValueError, TypeError ):
232
+            raise Validation_error( arg_name, value, arg_type )
233
+        args_index += 1
234
+
235
+      for ( arg_name, arg_value ) in kwargs.items():
236
+        if not arg_name in kwarg_types:
237
+          print arg_name, kwarg_types
238
+          raise Validation_error( arg_name, arg_value, None, message = u"is an unknown argument" )
239
+
240
+      return function( *args, **kwargs )
241
+
242
+    return check
243
+
244
+  return decorate

+ 0
- 0
controller/__init__.py View File


+ 8
- 0
controller/test/Stub_view.py View File

@@ -0,0 +1,8 @@
1
+class Stub_view( object ):
2
+  result = None
3
+
4
+  def __init__( self, **kwargs ):
5
+    Stub_view.result = kwargs