-
Notifications
You must be signed in to change notification settings - Fork 1
/
nothon.py
178 lines (147 loc) · 5.58 KB
/
nothon.py
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
import web
import os
import shutil
import urllib
import base64
import simplejson
import traceback
import tempfile
import time
import datetime
import sys
from bs4 import BeautifulSoup
from python.resource import NothonResource
from python.fileutils import *
from python.jsutils import *
from python.cell_utils import *
from python.new_notebook import *
from python.notebook import Notebook
from python.bibliography import Bibliography
from python.arxiv import Arxiv
from python.template_helpers import *
nothon_resource = NothonResource()
# We have to check for non-standard packages, so that we can run on android
try:
from pylab import *
nothon_resource.has_matplotlib = True
except ImportError:
nothon_resource.has_matplotlib = False
urls = ('/', 'Index')
render = web.template.render('templates/')
web.template.Template.globals['safe_content'] = safe_content
web.template.Template.globals['safe_props'] = safe_props
app = web.application(urls, globals())
def image_handler(message, resource):
ID = message['id'].split('_')[-1]
fn = message['filename']
directory = message['directory'].strip('\n')
return simplejson.dumps({message['id'] : fetch_image(ID, fn, message)})
def write_to_temp(string):
_, tmp = tempfile.mkstemp()
with open(tmp, 'w') as fout:
fout.write(string)
return tmp
def maxima_execute(max_string):
if not max_string.endswith(';'): max_string += ';'
tmp = write_to_temp(max_string + '\ntex(%);')
os.system('maxima -b %s > %s.out'%(tmp, tmp))
result = open(tmp + '.out', 'r').read()
os.remove(tmp)
os.remove(tmp + '.out')
return result
def list_handler_functions():
return [file.split('.')[0] for file in os.listdir('static/js/') if file.startswith('_')]
def list_create_functions():
return [file.split('.')[0] for file in os.listdir('static/js/') if file.endswith('_html.js')]
class Index(object):
update_js()
def GET(self):
aside = {"tree" : unwrap_tree(dir_tree('.', nothon_resource.listed), '.', nothon_resource.dirlisting_style)}
link = web.input(keyword=[], includeonly=[])
if 'file' in link:
return get_file_from_disc(link.file)
if 'arxiv' in link:
arxiv = Arxiv(nothon_resource, render)
if len(link.arxiv) == 0:
return render.arxiv_all(nothon_resource.server, aside)
return render.arxiv('arxiv', aside, arxiv.parse(link.arxiv, keyword=link.keyword, includeonly=link.includeonly))
if 'bibnote' in link:
bib = Bibliography(nothon_resource, render)
bibnote = link.bibnote
if len(bibnote) > 0:
return render.bibliography(bibnote, bibnote, aside,
bib.parse_bibliography(bibnote),
list_handler_functions(), list_create_functions())
else: return render.welcome(None)
if link.name == '':
return render.welcome(None)
if link.name.endswith('.html'):
with open(link.name, 'r') as fin:
html = fin.read()
return html
if link.name == '__timeline':
return render.timeline(link.name, aside, make_timeline())
elif link.name == '__toc':
return render.toc(link.name, aside, make_toc())
elif link.name == '__bibliography':
return render.bib_list(link.name, aside, make_bibliography())
elif link.name.endswith('.note'):
nb = Notebook(nothon_resource, render)
sp = link.name.split('#')
link.name = sp[0]
if not os.path.exists(link.name):
nb.new_notebook(link.name)
aside = {"tree" : unwrap_tree(dir_tree('.', nothon_resource.listed), '.', nothon_resource.dirlisting_style)}
return render.notebook(link.name, link.name, aside, nb.parse_note(link.name), list_handler_functions(), list_create_functions())
else:
return render.welcome('Could not process requested URL!')
def POST(self):
message = simplejson.loads(web.data())
print message
doc_type = message.get('type')
if doc_type in ('notebook', 'bibliography', 'arxiv'):
exec('obj = %s(nothon_resource, render)'%(doc_type.title()))
result = obj.handler(message)
if(message.get('aux')):
aux = message.get('aux')
if aux.get('command') in ('new_notebook'):
nb = Notebook(nothon_resource, render)
nb.new_notebook(aux.get('file'), aux=aux)
result['aux'] = aux
return simplejson.dumps(result)
if message['command'] in ('text', 'paragraph', 'savehtml', 'docmain_render', 'image', 'paste_cell', 'remove_cell'):
exec('result = %s_handler(message, nothon_resource)'%(message['command']))
return result
else:
return simplejson.dumps({'success': 'Could not parse command'})
if __name__ == "__main__": app.run()
#class StaticMiddleware:
#"""WSGI middleware for serving static files."""
#def __init__(self, app, prefix='/static/', root_path='/photo/'):
#self.app = app
#self.prefix = prefix
#self.root_path = root_path
#def __call__(self, environ, start_response):
#path = environ.get('PATH_INFO', '')
#path = self.normpath(path)
#if path.startswith(self.prefix):
#environ["PATH_INFO"] = os.path.join(self.root_path, web.lstrips(path, self.prefix))
#return web.httpserver.StaticApp(environ, start_response)
#else:
#return self.app(environ, start_response)
#def normpath(self, path):
#path2 = posixpath.normpath(urllib.unquote(path))
#if path.endswith("/"):
#path2 += "/"
#return path2
#if __name__ == "__main__":
#wsgifunc = app.wsgifunc()
#wsgifunc = StaticMiddleware(wsgifunc)
#print wsgifunc.root_path
#wsgifunc = web.httpserver.LogMiddleware(wsgifunc)
#server = web.httpserver.WSGIServer(("0.0.0.0", 8080), wsgifunc)
#print "http://%s:%d/" % ("0.0.0.0", 8080)
#try:
#server.start()
#except KeyboardInterrupt:
#server.stop()