/
app.py
executable file
·284 lines (207 loc) · 8.7 KB
/
app.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
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
#!/usr/bin/python2
import os
from urlparse import urlparse
from flask import Flask, render_template, render_template_string, Markup, request, json, redirect, url_for, jsonify, make_response
from flask_flatpages import FlatPages, pygmented_markdown
import datetime
#import html2text
import markdown2
import imghdr
## TODO ##
# add proper path handling with combinining paths and things.
# add source control (git repo) upon every save
DEBUG = True
FLATPAGES_AUTO_RELOAD = DEBUG
FLATPAGES_EXTENSION = '.html'
# right now, since we have shitty path handling, include the
# ending slash.
FLATPAGES_ROOT = "/home/rosiec/Dropbox/Science/Projects/LabNotebooksRepository/"
app = Flask(__name__)
app.config.from_object(__name__)
pages = FlatPages(app)
#h = html2text.HTML2Text()
##h.ignore_links = True
##h.ignore_images = True
#h.body_width = False
#md = markdown2.Markdown()
# This is a thin wrapper that pretty much does zero rendering
# on the input text, which we've decided is html.
def prerender_jinja(text):
#print "HI"
#print text
prerendered_body = render_template_string(Markup(text))
# print prerendered_body
return pygmented_markdown(prerendered_body)
# This route will troll the flat pages directory
# and list what's available to look at.
@app.route('/')
def index():
sortedpages = reversed(sorted(pages, key=lambda page: page.path))
return render_template('index.html', pages=sortedpages)
# TODO, add a rename link
# this route removes a page. don't use lightly, or you'll probably be sad.
# TODO - add version control!
@app.route('/_del/<path:path>')
def delete(path):
os.remove( FLATPAGES_ROOT + path + ".html")
return redirect("/")
# this route figures out what the proper name and title of this week's
# lab notebook is supposed to be, and routes you there.
@app.route('/_thisweek')
def thisweek():
now = datetime.datetime.now()
delta = datetime.timedelta(days=now.weekday())
thisweekdatetime = now - delta
thisweekname = thisweekdatetime.strftime("%y.%j._ - Notes - Week of %B %d %Y")
return redirect("/"+thisweekname)
# this route will display a static page in the pages directory
# generally, this means a journal file
# if you pass it a file that doesn't exist, it will start up
# a new file, but you ahve to save it
@app.route('/<path:path>')
def page(path):
newpath = path.replace(" ", "_");
#print path
#print newpath
if newpath != path:
return redirect(newpath)
page = pages.get(path)
if page == None:
now = datetime.datetime.now()
delta = datetime.timedelta(days=now.weekday())
thisweekdatetime = now - delta
weekstring = thisweekdatetime.strftime("%B %d, %Y")
currdatestring = now.strftime("%A, %b %d, %Y")
currtimestring = now.strftime("%I:%M%p")
return render_template('newjournal.html', week=weekstring, date=currdatestring, time=currtimestring, title=path)
### IN ORDER TO FIX AN ISSUE WITH FLASK FLATPAGES WHERE IT ASSUMES
### THAT ALL FILES HAVE YAML AND WILL EAT ITSELF IF THEY DON'T
### Essentially, the only way to detect it pre-render is that it
### chokes when you try to *ACCESS* page.meta. Fucking shit for brains.
### So, since page.meta is a dict, if it throws an exception, I'm going
### to supply it with a blank dict.
### Then, this dict, which render_template assumes will always be there,
### is helpfully supplied, thus breaking the cycle of code fucking itself
### and me pulling my hair out.
try:
print dir(page.meta)
except:
page.meta = {}
# try:
# print "~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~"
# print dir(page)
# print "~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~"
# print page.html
# print "~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~"
# print dir(page.meta)
# print "~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~"
# print page.meta
# print "~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~"
#
# except:
# print "WTF STOPPED HERE"
try:
return render_template('existingjournal.html', page=page, title=path)
except ValueError:
return render_template('error.html', page=page, title=path)
return render_template('error.html', page=page, title=path)
# Route that will process the AJAX request (_save)
# saves to the filename from the referrer.
@app.route('/_save', methods=["GET","POST"])
def save():
print dir(request.args.values)
#data = request.args.get('data', 0, type=str)
data = request.form['data']
#for some reason, sometimes a unicode zero width space (\u200) sneaks in
data = data.replace(u'\u200b','')
print "Saving..."
print "--------------------------------------------------------------------------------"
print data[:100] + "..."
#print " ..."
print "..." + data[-100:]
print "--------------------------------------------------------------------------------"
referrer = request.referrer
completefile = render_template("existingjournal.html", page=data)
filename = urlparse(referrer).path.translate(None, '/') + ".html"
#print "HELLO"
#print data
#print "FUC"
#mdfilename = urlparse(referrer).path.translate(None, '/') + ".md"
#htmlmdfilename = mdfilename + ".html"
### IN ORDER TO FIX AN ISSUE WITH FLASK FLATPAGES WHERE IT ASSUMES
### THAT ALL FILES HAVE YAML AND IT WILL EAT IT IF IT ISN'T
### I'm pre-pending a blank line here
### This blank line will ALWAYS get eaten by flask-flatpages
### It won't accumulate because the display dosen't re-fetch saved
### data when it saves. It just shoves over what it has
### This \n will be stripped off if you do a reload, and we begin
### the merry-go-round again.
data = '\n' + data
f = open( FLATPAGES_ROOT + filename, 'w')
f.write(data)
f.close()
#f = open( FLATPAGES_ROOT + mdfilename, 'w')
#f.write( h.handle(data) )
#f.close()
#f = open( FLATPAGES_ROOT + htmlmdfilename, 'w')
#f.write( md.convert(h.handle(data)) )
#f.close()
return jsonify(result=referrer)
# this route will serve a static image from a subdirectory
# in the pages directory (no static images may be served
# from directly in the pages directory).
@app.route('/<path:path>/<path:imgpath>')
def page_bleh(path,imgpath):
fullpath = (FLATPAGES_ROOT + path + "/" + imgpath)
resp = make_response(open(fullpath).read())
if imghdr.what(fullpath) != None:
resp.content_type = "image/jpeg"
return resp
# This route will process the AJAX request from the imagebrowser plugin,
# and troll the FLATPAGES_ROOT subdirectories for images,
# and return what's available to look at in JSON format
@app.route('/_browse_images')
def browse_images():
# nothing in there
if not os.path.exists(FLATPAGES_ROOT):
return "[]"
started = 0
jsons = []
for (dirpath, dirnames, filenames) in os.walk(FLATPAGES_ROOT):
dirnames.sort(reverse=True)
if started == 0:
started = 1
continue
shortdirpath = dirpath[len(FLATPAGES_ROOT):]
for filename in filenames:
if filename[-5] == ".html" or filename == ".DS_Store":
continue
url = "./" + dirpath[len(FLATPAGES_ROOT):] + "/" + filename
thumb = "/" + dirpath[len(FLATPAGES_ROOT):] + "/" + filename
jsons.append( jsonify(image=url,thumb=thumb,folder=shortdirpath) )
# return the jasonified stuff
output = "[" + ",".join([item.get_data() for item in jsons]) + "]"
return output
# Route that will process a POST ajax request (_upload), pull out the
# uploaded file, save it to a directory based on the referrer
# which is the name of our journal file,
# then, responds with a call to the CKEDITOR callback, with the selected URL.
@app.route('/_upload', methods=['POST'])
def upload():
funcnum = request.args.get('CKEditorFuncNum', 0, type=str)
incomingfile = request.files.get('upload')
referrer = request.referrer
basedirectory = FLATPAGES_ROOT + urlparse(referrer).path.translate(None, '/')
if not os.path.exists(basedirectory):
os.makedirs(basedirectory)
targetfilename = basedirectory + "/" + incomingfile.filename
f = open(targetfilename, 'w')
incomingfile.save(f)
f.close()
url = "./" + urlparse(referrer).path.translate(None, '/') + "/" + incomingfile.filename
output = """<script type='text/javascript'> window.parent.CKEDITOR.tools.callFunction(""" + funcnum + ", " + "'" + url + "', '' )</script>"
return output
# Initialize the Flask application
if __name__ == '__main__':
app.config['FLATPAGES_HTML_RENDERER'] = prerender_jinja
app.run()