forked from xumingming/yash
-
Notifications
You must be signed in to change notification settings - Fork 0
/
yash.py
executable file
·395 lines (319 loc) · 11.4 KB
/
yash.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
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
#!/usr/bin/env python
#-*-encoding: utf-8 -*-
import os, sys, codecs, re
import markdown2 as markdown
import bottle
from bottle import route, run, template, static_file, get, post, view, request, response, TEMPLATE_PATH, Bottle, hook, redirect, abort
import beaker.middleware
from search import Search, SearchResult
import simpleyaml
import qrcode
import StringIO
import parser
import getopt
import json
YASH_HOME = None
TEMPLATE_PATH = [os.path.join(os.getcwd(), "views")]
YASH_DATA_HOME = os.path.expanduser("~/.yash")
SUPPORTED_PLAIN_FILE_TYPES = ["markdown", "md", "txt", "plan", "py"]
session_opts = {
'session.type': 'file',
'session.data_dir': YASH_DATA_HOME + '/session/',
'session.auto': True,
}
app = beaker.middleware.SessionMiddleware(bottle.app(), session_opts)
class User:
def __init__(self, username, role):
self.username = username
self.role = role
class Config:
def __init__(self):
config = simpleyaml.safe_load(open(YASH_DATA_HOME + "/config.yaml"))
self.roles = config["roles"]
self.users = config["users"]
def authenticate(self, username, password):
return username in self.users and self.users[username]['password'] == password
def get_role_by_username(self, username):
user = self.users[username]
if not user:
return "public"
else:
return user["role"]
def get_dirs_by_role(self, role):
return self.roles[role]
def has_right(self, role, folder):
return folder in self.roles[role]
def is_login_required(self, url):
staticFilePattren = '^/static/'
return (not url in ["/login", "/not-authorized", "/logout", "/"]) and not re.search(staticFilePattren, url)
config = Config()
def session_get(key):
session = bottle.request.environ.get('beaker.session')
return session.get(key)
def session_set(key, value):
session = bottle.request.environ.get('beaker.session')
session[key] = value
session.save()
def session_get_role():
user = session_get("user")
if not user:
return "public"
return user.role
def post_get(name, default=''):
return bottle.request.POST.get(name, default).strip()
def is_logined():
return not session_get("user") is None
@hook('before_request')
def auth_hook():
# role based authentication
if not config.is_login_required(request.path):
return
role = session_get_role()
# super user can access anything
if role == "super":
return
valid_paths = config.get_dirs_by_role(role)
for p in valid_paths:
if request.path.startswith("/" + p + "/") or request.path == "/" + p:
if role == "public" or is_logined():
return
else:
redirect("/login")
redirect("/not-authorized")
@get("/not-authorized")
def not_authorized():
return "Access Denied!"
def common_view_args():
return dict(request = request, is_logined = is_logined())
@get("/login")
@view("login")
def login():
return dict()
@post("/login")
def login_post():
username = request.forms.get("username")
password = request.forms.get("password")
if config.authenticate(username, password):
role = config.get_role_by_username(username)
user = User(username, role)
session_set("user", user)
redirect("/")
else:
redirect("/login")
@get("/logout")
def logout():
session_set("user", None)
redirect("/")
@get('/system/qr.png')
def serve_qrcode():
filename = request.GET.get("path")
actual_path = filename
qrcode_img = qrcode.make(actual_path)
response.content_type = 'image/png'
buf = StringIO.StringIO()
qrcode_img.save(buf, "PNG")
contents = buf.getvalue()
return contents
@get('/<filename:re:static\/.*\.(css|js|png|jpg|gif|ico|woff|woff2|ttf|map)>')
def static_files(filename):
return static_file(filename, root=YASH_HOME + "/")
@get('/<filename:re:.*\.(png|jpg|gif|ico|html|js|css)>')
def images(filename):
return static_file(filename, root = os.getcwd())
@route('/search')
@view('search')
def search_files():
keyword = request.GET.get('w')
if len(keyword) > 0:
keyword = keyword.strip()
s = Search(os.getcwd(), keyword.decode("utf-8"), ("*.markdown", "*.md"))
result = s.walk()
result = [x for x in result if x.items is not None]
newresult = []
for x in result:
x = SearchResult(x.fullpath[len(os.getcwd()):len(x.fullpath)], x.items)
x.name = extract_file_title_by_fullurl(x.fullpath)
newresult.append(x)
return dict(results = newresult, keyword = keyword, request = request, is_logined = is_logined())
def markdown_files_1(text, fullurl):
html = markdown.markdown(
text,
extras = ["tables", "code-friendly", "fenced-code-blocks"]
)
breadcrumbs = calculate_breadcrumbs(fullurl)
title = extract_file_title_by_fullurl(fullurl)
return dict(html = html,
request = request,
title = title,
is_logined = is_logined(),
breadcrumbs = breadcrumbs)
def read_file_from_disk(fullpath):
if not os.path.exists(fullpath):
abort(404, "Nothing to see here, honey!")
input_file = codecs.open(fullpath, mode="r", encoding="utf-8")
text = input_file.read()
return text
def extract_file_title(fullpath):
input_file = codecs.open(fullpath, mode="r", encoding="utf-8")
name = input_file.readline()
name = name.strip("#")
input_file.close()
return name
def extract_file_title_by_fullurl(fullurl):
physical_path = os.getcwd() + fullurl
name = os.path.basename(physical_path)
is_dir = os.path.isdir(physical_path)
if os.path.isdir(physical_path):
namepath = physical_path + "/.name"
if os.path.exists(namepath):
name = extract_file_title(namepath)
else:
extension_idx = name.rfind(".")
extension = name[extension_idx + 1:]
if extension in SUPPORTED_PLAIN_FILE_TYPES:
name = extract_file_title(physical_path)
name = name.strip()
if len(name) > 0:
return name
else:
return os.path.basename(fullurl)
@get('/<filename:re:.*\.plan\.(md|markdown)>')
@view('gantt')
def serve_plan(filename):
fullpath = os.getcwd() + "/" + filename
man = request.GET.get('man')
text = read_file_from_disk(fullpath)
project = parser.parse(text)
# make project info to json
texts = []
for idx, task in enumerate(project.tasks):
# if not man or man == task.man.encode("utf-8"):
taskjson = {}
taskjson["taskName"] = task.name.encode("utf-8")
taskjson["owner"] = task.man.encode("utf-8")
taskjson["cost"] = task.man_day
taskjson["start"] = str(project.task_start_date(task))
taskjson["end"] = str(project.task_end_date(task))
taskjson["isDelayed"] = str(project.is_delayed(task))
taskjson["progress"] = str(task.status)
texts.append(taskjson)
html = json.dumps(texts)
fullurl = "/" + filename
breadcrumbs = calculate_breadcrumbs(fullurl)
title = extract_file_title_by_fullurl(fullurl)
man_stats = pretty_print_man_stats(project.tasks)
return dict(html = html,
title = title,
project = project,
man_stats = man_stats,
selected_man = man,
breadcrumbs = breadcrumbs, request = request, is_logined = is_logined())
def pretty_print_man_stats(tasks):
man2days = {}
for task in tasks:
if not man2days.get(task.man):
man2days[task.man] = [0,0] # finished_man_days, total_man_days
task_status = task.status
man_days = task.man_day
finished_man_days = task_status * man_days / 100
man2days[task.man][0] = man2days[task.man][0] + finished_man_days
man2days[task.man][1] = man2days[task.man][1] + man_days
return man2days
@route('/<filename:re:.*\.xml>')
def xml_files(filename):
fullpath = os.getcwd() + "/" + filename
text = read_file_from_disk(fullpath)
response.content_type = "text/xml"
return text
@route('/<filename:re:.*\.sql>')
@view("code")
def sql_files(filename):
fullpath = os.getcwd() + "/" + filename
text = read_file_from_disk(fullpath)
mode = "text"
if filename.endswith(".sql"):
mode = "sql"
response.content_type = "text/html"
breadcrumbs = calculate_breadcrumbs("/" + filename)
title = extract_file_title_by_fullurl("/" + filename)
return dict(mode = mode,
code = text,
request = request,
title = title,
breadcrumbs = breadcrumbs,
is_logined = is_logined()
)
@route('/<filename:re:.*\.(txt|properties|py)>')
def plain_files(filename):
fullpath = os.getcwd() + "/" + filename
text = read_file_from_disk(fullpath)
response.content_type = "text/plain"
return text
@route('/<filename:re:.*\.(md|markdown)>')
@view('markdown')
def markdown_files(filename):
fullpath = os.getcwd() + "/" + filename
text = read_file_from_disk(fullpath)
return markdown_files_1(text, "/" + filename)
class FileItem:
def __init__(self, name, path, is_dir):
self.name = name
self.path = path
self.is_dir = is_dir
def __repr__(self):
return "{}[{}]".format(self.name.encode('UTF-8'), self.path)
def calculate_breadcrumbs(path):
path = path.strip("/")
if len(path) == 0:
paths = []
else:
paths = path.split("/")
ret = [FileItem("Yash", "/", False)]
totalpath = ""
for p in paths:
realpath = totalpath + "/" + p
name = extract_file_title_by_fullurl(realpath)
ret.append(FileItem(name, realpath, False))
totalpath = realpath
return ret
@route('/<filename:re:.*>')
@view('directory')
def directories(filename):
physical_path = os.getcwd() + "/" + filename
if len(filename) == 0:
fullurl = ""
else:
fullurl = "/" + filename
if not os.path.exists(physical_path):
abort(404, "Nothing to see here, Honey!")
files = os.listdir(physical_path)
files = [x for x in files if not x.startswith(".")]
role = session_get_role()
if fullurl == "" and not role == "super":
files = [x for x in files if config.has_right(role, x)]
filemap = []
for f in files:
newfullurl = fullurl + "/" + f
name = extract_file_title_by_fullurl(newfullurl)
is_dir = os.path.isdir(physical_path + "/" + f)
filemap.append(FileItem(name, newfullurl, is_dir))
breadcrumbs = calculate_breadcrumbs(fullurl)
title = extract_file_title_by_fullurl(fullurl)
return dict(files = filemap,
fullurl = fullurl,
title = title,
breadcrumbs = breadcrumbs,
request = request,
is_logined = is_logined())
if __name__ == '__main__':
opts, args = getopt.getopt(sys.argv[1:], 'p:h')
port = 80
for opt_name, opt_value in opts:
opt_value = opt_value.strip()
if opt_name == '-p':
port = int(opt_value)
if opt_name == '-h':
print """Usage: yash.py -p <port>"""
YASH_HOME = sys.path[0]
bottle.TEMPLATE_PATH = [os.path.join(YASH_HOME, "views")]
bottle.run(app = app, host='0.0.0.0', port=port)