-
Notifications
You must be signed in to change notification settings - Fork 33
/
wiki.py
359 lines (292 loc) · 12.1 KB
/
wiki.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
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
from flask import Flask, render_template, request, redirect, url_for, send_from_directory
import logging
from werkzeug.utils import secure_filename
from random import randint
import datetime
import time
import git
import pypandoc
import os
import re
import uuid
import knowledge_graph
HOST = os.getenv('WIKI_HOST', "0.0.0.0")
PORT = os.getenv('WIKI_PORT', 5000)
HOMEPAGE = os.getenv('HOMEPAGE', "homepage.md")
HOMEPAGE_TITLE = os.getenv('HOMEPAGE_TITLE', "homepage")
WIKI_DATA = os.getenv('WIKI_DATA', "wiki")
IMAGES_ROUTE = os.getenv('IMAGES_ROUTE', 'img')
WIKMD_LOGGING = os.getenv('WIKMD_LOGGING', 1)
WIKMD_LOGGING_FILE = os.getenv('WIKMD_LOGGING_FILE', "wikmd.log")
UPLOAD_FOLDER = WIKI_DATA + '/' + IMAGES_ROUTE
ALLOWED_EXTENSIONS = {'png', 'jpg', 'jpeg', 'gif'}
SYSTEM_SETTINGS = {
"darktheme": False,
"listsortMTime": False,
}
app = Flask(__name__)
app.config['UPLOAD_FOLDER'] = UPLOAD_FOLDER
logger = logging.getLogger('werkzeug')
logger.setLevel(logging.ERROR)
def save(page_name):
"""
Function that saves a *.md page and commits the changes.
:param page_name: name of the page
"""
content = request.form['CT']
app.logger.info(f"saving {page_name}")
try:
filename = os.path.join(WIKI_DATA, page_name + '.md')
dirname = os.path.dirname(filename)
if not os.path.exists(dirname):
os.makedirs(dirname)
with open(filename, 'w') as f:
f.write(content)
except Exception as e:
app.logger.error(f"Error while saving {page_name}: {str(e)}")
def search():
"""
Function that searches for a term.
:return:
"""
search_term = request.form['ss']
escaped_search_term = re.escape(search_term)
found = []
app.logger.info(f"searching for {search_term} ...")
for root, subfolder, files in os.walk(WIKI_DATA):
for item in files:
path = os.path.join(root, item)
if os.path.join(WIKI_DATA, '.git') in str(path):
# We don't want to search there
app.logger.debug(f"skipping {path} is git file")
continue
if os.path.join(WIKI_DATA, IMAGES_ROUTE) in str(path):
# Nothing interesting there too
continue
with open(root + '/' + item, encoding="utf8") as f:
fin = f.read()
try:
if (re.search(escaped_search_term, root + '/' + item, re.IGNORECASE) or
re.search(escaped_search_term, fin, re.IGNORECASE) != None):
# Stripping 'wiki/' part of path before serving as a search result
folder = root[len(WIKI_DATA + "/"):]
if folder == "":
url = os.path.splitext(
root[len(WIKI_DATA + "/"):] + "/" + item)[0]
else:
url = "/" + \
os.path.splitext(
root[len(WIKI_DATA + "/"):] + "/" + item)[0]
info = {'doc': item,
'url': url,
'folder': folder,
'folder_url': root[len(WIKI_DATA + "/"):]}
found.append(info)
app.logger.info(f"found {search_term} in {item}")
except Exception as e:
app.logger.error(f"There was an error: {str(e)}")
return render_template('search.html', zoekterm=found, system=SYSTEM_SETTINGS)
@app.route('/list/', methods=['GET'])
def list_full_wiki():
return list_wiki("")
@app.route('/list/<path:folderpath>/', methods=['GET'])
def list_wiki(folderpath):
list = []
for root, subfolder, files in os.walk(os.path.join(WIKI_DATA, folderpath)):
if root[-1] == '/':
root = root[:-1]
for item in files:
path = os.path.join(root, item)
mtime = os.path.getmtime(os.path.join(root, item))
if os.path.join(WIKI_DATA, '.git') in str(path):
# We don't want to search there
app.logger.debug(f"skipping {path}: is git file")
continue
if os.path.join(WIKI_DATA, IMAGES_ROUTE) in str(path):
# Nothing interesting there too
continue
folder = root[len(WIKI_DATA + "/"):]
if folder == "":
if item == HOMEPAGE:
continue
url = os.path.splitext(
root[len(WIKI_DATA + "/"):] + "/" + item)[0]
else:
url = "/" + \
os.path.splitext(
root[len(WIKI_DATA + "/"):] + "/" + item)[0]
info = {'doc': item,
'url': url,
'folder': folder,
'folder_url': folder,
'mtime': mtime,
}
list.append(info)
if SYSTEM_SETTINGS['listsortMTime']:
list.sort(key=lambda x: x["mtime"], reverse=True)
else:
list.sort(key=lambda x: (str(x["url"]).casefold()))
return render_template('list_files.html', list=list, folder=folderpath, system=SYSTEM_SETTINGS)
def git_commit(pagename=""):
try:
repo = git.Repo.init(WIKI_DATA)
repo.git.checkout("-b", "master")
repo.config_writer().set_value("user", "name", "wikmd").release()
repo.config_writer().set_value("user", "email", "wikmd@no-mail.com").release()
app.logger.info("There doesn't seem to be a repo, creating one...")
except Exception as e:
app.logger.error(f"There was an error: {str(e)}")
try:
repo.git.add("--all")
date = datetime.datetime.now()
commit = f"Commit add {pagename} {str(date)}"
repo.git.git_commit('-m', commit)
app.logger.info(f"there was a new commit: {commit}")
except Exception as e:
app.logger.info(f"nothing commit: {str(e)}")
@app.route('/<path:file_page>', methods=['POST', 'GET'])
def file_page(file_page):
if request.method == 'POST':
return search()
else:
html = ""
mod = ""
folder = ""
try:
filename = os.path.join(WIKI_DATA, file_page + ".md")
# latex = pypandoc.convert_file("wiki/" + file_page + ".md", "tex", format="md")
# html = pypandoc.convert_text(latex,"html5",format='tex', extra_args=["--mathjax"])
html = pypandoc.convert_file(filename, "html5",
format='md', extra_args=["--mathjax"], filters=['pandoc-xnos'])
mod = "Last modified: %s" % time.ctime(os.path.getmtime(filename))
folder = file_page.split("/")
file_page = folder[-1:][0]
folder = folder[:-1]
folder = "/".join(folder)
app.logger.info(f"showing html page of {file_page}")
except Exception as a:
app.logger.info(a)
return render_template('content.html', title=file_page, folder=folder, info=html, modif=mod,
system=SYSTEM_SETTINGS)
@app.route('/', methods=['POST', 'GET'])
def index():
if request.method == 'POST':
return search()
else:
html = ""
app.logger.info("homepage displaying")
try:
html = pypandoc.convert_file(
os.path.join(WIKI_DATA, HOMEPAGE), "html5", format='md', extra_args=["--mathjax"],
filters=['pandoc-xnos'])
except Exception as e:
app.logger.error(e)
git_commit()
return render_template('index.html', homepage=html, system=SYSTEM_SETTINGS)
@app.route('/add_new', methods=['POST', 'GET'])
def add_new():
if request.method == 'POST':
page_name = fetch_page_name()
save(page_name)
git_commit(page_name)
return redirect(url_for("file_page", file_page=page_name))
else:
return render_template('new.html', upload_path=IMAGES_ROUTE, system=SYSTEM_SETTINGS)
@app.route('/edit/homepage', methods=['POST', 'GET'])
def edit_homepage():
if request.method == 'POST':
page_name = fetch_page_name()
save(page_name)
git_commit(page_name)
return redirect(url_for("file_page", file_page=page_name))
else:
with open(os.path.join(WIKI_DATA, HOMEPAGE), 'r', encoding="utf-8") as f:
content = f.read()
return render_template("new.html", content=content, title=HOMEPAGE_TITLE, upload_path=IMAGES_ROUTE,
system=SYSTEM_SETTINGS)
def fetch_page_name() -> str:
page_name = request.form['PN']
if page_name[-4:] == "{id}":
page_name = f"{page_name[:-4]}{uuid.uuid4().hex}"
return page_name
@app.route('/remove/<path:page>', methods=['GET'])
def remove(page):
filename = os.path.join(WIKI_DATA, page + '.md')
os.remove(filename)
return redirect("/")
@app.route('/edit/<path:page>', methods=['POST', 'GET'])
def edit(page):
filename = os.path.join(WIKI_DATA, page + '.md')
if request.method == 'POST':
page_name = fetch_page_name()
if page_name != page:
os.remove(filename)
save(page_name)
git_commit(page_name)
return redirect(url_for("file_page", file_page=page_name))
else:
with open(filename, 'r', encoding="utf-8") as f:
content = f.read()
return render_template("new.html", content=content, title=page, upload_path=IMAGES_ROUTE,
system=SYSTEM_SETTINGS)
@app.route('/' + IMAGES_ROUTE, methods=['POST', 'DELETE'])
def upload_file():
app.logger.info("uploading image...")
# Upload image when POST
if request.method == "POST":
file_names = []
for key in request.files:
file = request.files[key]
filename = secure_filename(file.filename)
# bug found by cat-0
while filename in os.listdir(os.path.join(WIKI_DATA, IMAGES_ROUTE)):
app.logger.info(
"There is a duplicate, solving this by extending the filename...")
filename, file_extension = os.path.splitext(filename)
filename = filename + str(randint(1, 9999999)) + file_extension
file_names.append(filename)
try:
app.logger.info(f"Saving {filename}")
file.save(os.path.join(app.config['UPLOAD_FOLDER'], filename))
except Exception as e:
app.logger.error(f"Error while saving image: {str(e)}")
return filename
# DELETE when DELETE
if request.method == "DELETE":
# request data is in format "b'nameoffile.png" decode by utf-8
filename = request.data.decode("utf-8")
try:
app.logger.info(f"removing {str(filename)}")
os.remove((os.path.join(app.config['UPLOAD_FOLDER'], filename)))
except Exception as e:
app.logger.error(f"Could not remove {str(filename)}")
return 'OK'
@app.route('/knowledge-graph', methods=['GET'])
def graph():
global links
links = knowledge_graph.find_links()
return render_template("knowledge-graph.html", links=links, system=SYSTEM_SETTINGS)
# Translate id to page path
@app.route('/nav/<path:id>/', methods=['GET'])
def nav_id_to_page(id):
for i in links:
if i["id"] == int(id):
return redirect("/"+i["path"])
return redirect("/")
@app.route('/' + IMAGES_ROUTE + '/<path:filename>')
def display_image(filename):
# print('display_image filename: ' + filename)
return send_from_directory(UPLOAD_FOLDER, filename, as_attachment=False)
@app.route('/toggle-darktheme/', methods=['GET'])
def toggle_darktheme():
SYSTEM_SETTINGS['darktheme'] = not SYSTEM_SETTINGS['darktheme']
return redirect(request.referrer) # redirect to the same page URL
@app.route('/toggle-sorting/', methods=['GET'])
def toggle_sort():
SYSTEM_SETTINGS['listsortMTime'] = not SYSTEM_SETTINGS['listsortMTime']
return redirect("/list")
if __name__ == '__main__':
if int(WIKMD_LOGGING) == 1:
logging.basicConfig(filename=WIKMD_LOGGING_FILE, level=logging.INFO)
git_commit()
app.run(debug=True, host=HOST, port=PORT)