Source

gae-wiki / page.py

Full commit
  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
#!/usr/bin/python
# -*- coding: utf-8 -*-

import webapp2
import logging
import jinja2
import os
import urllib
import zlib

from google.appengine.ext import db
from google.appengine.ext import blobstore
from google.appengine.ext.webapp import blobstore_handlers
from google.appengine.api import taskqueue
from google.appengine.api import memcache
from google.appengine.ext import deferred
from google.appengine.api import mail

from creole import Parser
from creole.html_emitter import HtmlEmitter

from user import User, get_user, auth


##################
###   Models   ###
##################

# Enum to describe access policy
class Access():
	ALL = 'ALL'
	PRIVATE = 'PRIVATE'
	PARENT = 'PARENT'

# Main class to store wiki-page
class Page(db.Model):
	path = db.StringProperty(required=True)
	updated = db.DateTimeProperty(auto_now=True)
	html = db.TextProperty() #required=True
	user_id = db.IntegerProperty()
	# title = db.StringProperty()
	
	access = db.StringProperty(default=Access.PARENT)

	# url path
	# for root return empty string to avoid //.edit urls
	def upath(self):
		p = self.path
		return p if p != '/' else ''

class PageHistory(db.Model):
	page = db.ReferenceProperty(reference_class=Page, collection_name='history', required=True)
	zipp = db.BlobProperty(required=True)
	updated = db.DateTimeProperty(auto_now_add=True)
	user_id = db.IntegerProperty()

	def html(self):
		return zlib.decompress(self.zipp).decode('utf-8')

class PageFile(db.Model):
	page = db.ReferenceProperty(reference_class=Page, collection_name='files', required=True)
	user_id = db.IntegerProperty()
	name = db.StringProperty(required=True)
	size = db.IntegerProperty()
	date = db.DateTimeProperty()
	blob = blobstore.BlobReferenceProperty(required=True)
	# url = db.StringProperty()

class PageIndex(db.Model):
	''' Usefull to move page clusters and show subpages '''
	path = db.StringListProperty(required=True)
	# store random mark to determine 
	# we have already moved page in case of failure

class Subscribe(db.Model):
	page = db.ListProperty(item_type=int, default=[])
	cluster = db.ListProperty(item_type=int, default=[])

	def subscribe(self, page_id, t):
		if t == 'page':
			self.page.append(page_id)
		if t == 'cluster':
			self.cluster.append(page_id)
		if t == 'none':
			if page_id in self.page: 
				self.page.remove(page_id)
			if page_id in self.cluster:
				self.cluster.remove(page_id)


CACHE_PAGE = 'page:'
CACHE_FILES = 'files:'

def get_page(path):
	if not isinstance(path, unicode):
		path = unicode(path, 'utf-8')
	path = path.lower()

	key = CACHE_PAGE + path
	page = memcache.get(key)
	if page is None:
		log.info('Load page from DB')
		found = Page.all().filter('path', path).fetch(1)
		if found:
			page = found[0]
			memcache.set(key, page)
	return page

def set_page(path, page):
	if not isinstance(path, unicode):
		path = unicode(path, 'utf-8')
	path = path.lower()

	key = CACHE_PAGE + path
	memcache.set(key, page)

def get_files(page):
	key = CACHE_FILES + page.path
	files = memcache.get(key)
	if files is None:
		log.info('load files from DB')
		files = page.files.fetch(1000)
		memcache.set(key, files)
	return files

def breadcrumbs(path):
	result = []
	full = ''
	for step in path.split('/'):
		if not step: continue
		full += '/'+step
		result.append((step, full))
	return result

def index_path(path):
	if path[0] != '/':
		raise Exception('path should start from slash: '+path)
	result = ['/']
	current = ''
	for step in path[1:].split('/'):
		# add non empty, maybe throw exception
		if not step: continue 

		current += '/'+step
		result.append(current)
	return result

def add_page_index(page_id, path):
	index = PageIndex(key=db.Key.from_path('PageIndex', page_id), path=index_path(path))
	index.put()

def notify(page_id, from_email):
	page = Page.get_by_id(page_id)
	users = Subscribe.all(keys_only=True).filter('page', page_id)
	for user in users:
		u = User.get_by_id(user.id())
		log.info('Notify user %s about page %s updated', u.name, page.path)
		mail.send_mail(sender=from_email,
              to=u.email,
              subject='Page "%s" updated' % page.path,
              body='''
              Page %s updated
              ''' % page.path)


##################
###   Server   ###
##################

def convert(text):
	document = Parser(text).parse()
	return HtmlEmitter(document).emit()

def dateformat(value, format='%d.%m.%Y %H:%M'):
    return value.strftime(format)

def size(n):
	if n is None: n = 0

	if n < 10**3:
		return '%d B' % n 
	if n < 10**6:
		if n < 10**4:
			return '%.1f KB' % (n/1000.0)
		else:
			return '%d KB' % (n/1000)
	if n < 10**9:
		if n < 10**7:
			return '%.1f MB' % (n/10.0**6)
		else:
			return '%d MB' % (n/10**6)

def user_name(user_id):
	return get_user(user_id).name

def encode(url):
	return urllib.quote(url.encode('utf-8'))

def not_empty(l):
	return len(l) > 0

def check_access(page):
	if page is None:
		return True

	if page.access == Access.PARENT:
		user = get_user()
		parents = index_path(page.path)
		if len(parents) == 1: 
			return True
		parents.reverse()
		for path in parents[1:]:
			page = get_page(path)
			if page is not None:
				if page.access == Access.PARENT:
					continue
				if page.access == Access.PRIVATE:
					if user.key().id() != page.user_id:
						log.info('No access to "%s"', page.path)
						return False
				if page.access == Access.ALL:
					return True
		
		return True

	if page.access == Access.PRIVATE:
		user = get_user()
		# TODO: store private user list in separate entity
		if user.key().id() == page.user_id:
			return True
		else:
			log.info('No access to "%s"', page.path)
			return False

	if page.access == Access.ALL:
		return True

	# Return false for unsupported access policies
	return False



jinja_environment = jinja2.Environment(
    loader=jinja2.FileSystemLoader(os.path.dirname(__file__) + '/template/page'))
jinja_environment.filters['format'] = dateformat
jinja_environment.filters['size'] = size
jinja_environment.filters['user_name'] = user_name
jinja_environment.filters['urlencode'] = encode
jinja_environment.tests['not_empty'] = not_empty
jinja_environment.tests['access'] = check_access


log = logging.getLogger('page')


class PreviewPage(webapp2.RequestHandler):
	def post(self):
		text = self.request.get('text')
		html = convert(text)
		self.response.out.write(html)


class GetPage(webapp2.RequestHandler):
	''' Get formated wiki page '''
	@auth
	def get(self, path):
		if not path: path = '/'
		page = get_page(path)

		values = {'page': page, 'breadcrumbs': breadcrumbs(path)}
		if page:
			values['files'] = get_files(page)
			# TODO: lazy load
			values['upload'] = blobstore.create_upload_url(encode(page.upath()+'/.files'))
			
		template = jinja_environment.get_template('get.html')
		self.response.out.write(template.render(values))


class EditPage(webapp2.RequestHandler):
	''' Edit wiki page '''
	@auth
	def get(self, path):
		if not path: path = '/'
		page = get_page(path)

		values = {'page': page, 'breadcrumbs': breadcrumbs(path)}
		if page:
			# TODO: lazy load
			values['files'] = get_files(page)
			values['upload'] = blobstore.create_upload_url(encode(page.upath()+'/.files'))

			history = page.history.order('-updated').fetch(1)[0]
			values['text'] = history.html()
			
		template = jinja_environment.get_template('edit.html')
		self.response.out.write(template.render(values))

	def post(self, path):
		if not path: path = '/'
		path = path.lower()
		page = get_page(path)
		new = False
		if not page:
			page = Page(path=unicode(path, 'utf-8'))
			new = True

		user = get_user()

		# save page
		text = self.request.get('text')
		page.html = convert(text)
		page.user_id = user.key().id()
		page.put()

		# update cache
		set_page(path, page)

		# update revision history
		zipp = zlib.compress(text.encode('utf-8'), 9)
		history = PageHistory(page=page.key(), zipp=zipp, user_id=user.key().id())
		history.put()

		# add path index
		if new:
			deferred.defer(add_page_index, page.key().id(), path)

		# add to search index
		deferred.defer(add_page, page.key().id())

		# notify subscribers
		deferred.defer(notify, page.key().id(), user.email)
		
		self.redirect(encode(page.path))


class DeletePage(webapp2.RequestHandler):
	''' Delete page '''
	@auth
	def get(self, path):
		if not path: path = '/'
		page = get_page(path)

		values = {'page': page, 'breadcrumbs': breadcrumbs(path)}
		if page:
			# TODO: lazy load
			values['files'] = get_files(page)
			values['upload'] = blobstore.create_upload_url(encode(page.upath()+'/.files'))
			
		template = jinja_environment.get_template('delete.html')
		self.response.out.write(template.render(values))

	def post(self, path):
		if not path: path = '/'
		page = get_page(path)
		index = PageIndex.get_by_id(page.key().id())
		page.delete()
		index.delete()

		memcache.delete(CACHE_PAGE+path)

		# TODO: Delete files?

		self.redirect('/')


class HistoryPage(webapp2.RequestHandler):
	''' Show page revision history '''
	@auth
	def get(self, path):
		if not path: path = '/'
		page = get_page(path)
		history = page.history.order('-updated')

		values = {
			'page': page, 
			'history': history, 
			'breadcrumbs': breadcrumbs(path),
		}
		template = jinja_environment.get_template('history.html')
		self.response.out.write(template.render(values))


class ShowHistoryPage(webapp2.RequestHandler):
	''' Show page revision '''
	@auth
	def get(self, path):
		if not path: path = '/'
		page = get_page(path)
		history = PageHistory.get_by_id(int(self.request.get('id')))
		if history.page.key().id() != page.key().id(): return

		values = {
			'page': page, 
			'history': history, 
			'html': convert(history.html()),
			'breadcrumbs': breadcrumbs(path),
			'user': get_user(history.user_id)
		}
		template = jinja_environment.get_template('show.html')
		self.response.out.write(template.render(values))


class MovePage(webapp2.RequestHandler):
	''' Move to another path either single page or the whole cluster '''
	@auth
	def get(self, path):
		if not path: path = '/'
		page = get_page(path)

		template = jinja_environment.get_template('move.html')
		self.response.out.write(template.render({'page': page, 'breadcrumbs': breadcrumbs(path)}))

	def post(self, path):
		if not path: path = '/'
		page = get_page(path)
		new_path = self.request.get('new_path')

		# move page
		page.path = new_path
		page.put()
		# update index
		index = PageIndex.get_by_id(page.key().id())
		index.path = index_path(new_path)
		index.put()

		# clear page cache
		memcache.delete(CACHE_PAGE+path)

		# move whole cluster
		if self.request.get('cluster'):
			taskqueue.add(url=URL_MOVE_PAGE, params={'from': path, 'to': new_path})

		self.redirect(encode(page.path))


URL_MOVE_PAGE = '/.task/move'

class MovePageCluster(webapp2.RequestHandler):
	''' Move cluster pages to new path '''

	def post(self):
		from_path = self.request.get('from')
		to_path = self.request.get('to')
		if from_path and to_path:
			log.info('move cluster from "%s" to "%s"', from_path, to_path)
			indexes = PageIndex.all().filter('path', from_path)
			for index in indexes:
				page_id = index.key().id()
				page = Page.get_by_id(page_id)

				# clear page cache
				memcache.delete(CACHE_PAGE+page.path)

				# update path
				relative = page.path[len(from_path):]
				path = to_path + relative
				page.path = path 
				index.path = index_path(path)
				page.put()
				index.put()


class TreePage(webapp2.RequestHandler):
	''' View subpages '''
	@auth
	def get(self, path):
		if not path: path = '/'
		page = get_page(path)
		
		cluster = []
		for index in PageIndex.all().filter('path', page.path):
			cluster.append(Page.get_by_id(index.key().id()))

		def sort_by_path(page):
			return page.path
		
		cluster.sort(key=sort_by_path)

		values = {
			'page': page, 
			'cluster': cluster, 
			'breadcrumbs': breadcrumbs(path),
		}
		template = jinja_environment.get_template('cluster.html')
		self.response.out.write(template.render(values))


class SubscribePage(webapp2.RequestHandler):
	''' Subscribe to get notifications about page updates '''
	@auth
	def get(self, path):
		if not path: path = '/'
		page = get_page(path)

		values = {'page': page, 'breadcrumbs': breadcrumbs(path)}
		if page:
			# TODO: lazy load
			values['files'] = get_files(page)
			values['upload'] = blobstore.create_upload_url(encode(page.upath()+'/.files'))

			subscribers = []
			user_ids = Subscribe.all(keys_only=True).filter('page', page.key().id())
			for user in user_ids:
				subscribers.append(get_user(user.id()))
			values['subscribers'] = subscribers

			user = get_user()
			s = Subscribe.get_by_id(user.key().id())
			if s is not None:
				if page.key().id() in s.cluster:
					values['type'] = 'cluster'
				elif page.key().id() in s.page:
					values['type'] = 'page'
				else:
					values['type'] = 'none'


		template = jinja_environment.get_template('subscribe.html')
		self.response.out.write(template.render(values))

	def post(self, path):
		if not path: path = '/'
		page = get_page(path)
		if not page: return

		
		user = get_user()
		user_id = user.key().id()
		s = Subscribe.get_by_id(user_id)
		if not s:
			s = Subscribe(key=db.Key.from_path('Subscribe', user_id))

		page_id = page.key().id()
		t = self.request.get('type')
		s.subscribe(page_id, t)
		s.put()

		self.redirect(path)


class AccessPage(webapp2.RequestHandler):
	def get(self, path):
		if not path: path = '/'
		page = get_page(path)

		values = {'page': page, 'breadcrumbs': breadcrumbs(path)}
		if page:
			# TODO: lazy load
			values['files'] = get_files(page)
			values['upload'] = blobstore.create_upload_url(encode(page.upath()+'/.files'))

		template = jinja_environment.get_template('access.html')
		self.response.out.write(template.render(values))

	def post(self, path):
		if not path: path = '/'
		page = get_page(path)

		param = self.request.get('access')
		if param == 'all':
			access = Access.ALL
		if param == 'private':
			access = Access.PRIVATE
		if param == 'parent':
			access = Access.PARENT
		
		page.access = access
		page.user_id = get_user().key().id()
		page.put()

		# Update page cache
		set_page(path, page)

		self.redirect(path)


class EditPageFiles(blobstore_handlers.BlobstoreUploadHandler, blobstore_handlers.BlobstoreDownloadHandler):
	def post(self, path):
		if not path: path = '/'
		page = get_page(path)

		upload_files = self.get_uploads('data')  # 'file' is file upload field in the form
		blob_info = upload_files[0]

		user = get_user()

		name = unicode(blob_info.filename, 'utf-8')
		size = blob_info.size
		date = blob_info.creation
		data = PageFile(page=page.key(), blob=blob_info.key(), user_id=user.key().id(), name=name, size=size, date=date)
		data.put()

		memcache.delete(CACHE_FILES + path)

		self.redirect(path)

	@auth
	def get(self, path, name):
		if not path: path = '/'
		page = get_page(path)
		name = unicode(name, 'utf-8')

		files = page.files.filter('name', name).fetch(1)
		if files:
			self.send_blob(files[0].blob)

	def put(self, path, name):
		if not path: path = '/'
		# delete file
		page = get_page(path)
		name = unicode(name, 'utf-8')

		files = page.files.filter('name', name).fetch(1)
		if files:
			file = files[0]
			file.blob.delete()
			file.delete() # maybe just set flag removed
			memcache.delete(CACHE_FILES + path)



##################
###   Search   ###
##################

from google.appengine.api import search

_INDEX_NAME="page"

def add_page(page_id):
	page = Page.get_by_id(page_id)
	# add to search index
	doc = search.Document(doc_id=page.path, 
						fields=[search.HtmlField(name='html', value=page.html),])
	try:
	    search.Index(name=_INDEX_NAME).put(doc)
	except search.Error:
	    logging.exception('Put failed')

def search_page(text):
	docs = []
	if not text:
		return docs
	try:
	    results = search.Index(name=_INDEX_NAME).search(text)
	    for doc in results:
	    	docs.append(doc.doc_id)
	except search.Error:
	    logging.exception('Search failed')
	return docs


class SearchPage(webapp2.RequestHandler):
	@auth
	def get(self):
		text = self.request.get('text')
		docs = search_page(text)
		
		template = jinja_environment.get_template('search.html')
		self.response.out.write(template.render({'docs': docs, 'text': text}))



debug = os.environ.get('SERVER_SOFTWARE', '').startswith('Dev')

app = webapp2.WSGIApplication([('/.search', SearchPage),

							   (URL_MOVE_PAGE, MovePageCluster),

							   ('/\.preview', PreviewPage),
							   ('(.*)/\.edit', EditPage),
							   ('(.*)/\.delete', DeletePage),
							   ('(.*)/\.log', HistoryPage),
							   ('(.*)/\.show', ShowHistoryPage),
							   ('(.*)/\.move', MovePage),
							   ('(.*)/\.tree', TreePage),
							   ('(.*)/\.subscribe', SubscribePage),
							   ('(.*)/\.access', AccessPage),

							   ('(.*)/\.files', EditPageFiles),
							   ('(.*)/\.files/(.*)', EditPageFiles),
							   
							   ('(.*)', GetPage),
							   
							  ], debug=debug)