-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathflaskapp.py
2194 lines (2026 loc) · 93.2 KB
/
flaskapp.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
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
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# coding: utf-8
from flask import Flask, send_from_directory, request, redirect, \
render_template, session, make_response, url_for, flash
import random
import math
import os
# init.py 為自行建立的起始物件
import init
# 利用 nocache.py 建立 @nocache decorator, 讓頁面不會留下 cache
from nocache import nocache
# the followings are for cmsimfly
import re
import os
import math
import hashlib
# use quote_plus() to generate URL
import urllib.parse
# use cgi.escape() to resemble php htmlspecialchars()
# use cgi.escape() or html.escape to generate data for textarea tag, otherwise Editor can not deal with some Javascript code.
import cgi
import sys
# for new parse_content function
#from bs4 import BeautifulSoup
# 為了使用 bs4.element, 改為 import bs4
import bs4
# for ssavePage and savePage
import shutil
# get the current directory of the file
_curdir = os.path.join(os.getcwd(), os.path.dirname(__file__))
sys.path.append(_curdir)
# 由 init.py 中的 uwsgi = False 或 True 決定在 uwsgi 模式或近端模式執行
#ends for cmsimfly
# 假如隨後要利用 blueprint 架構時, 可以將程式放在子目錄中
# 然後利用 register 方式導入
# 導入 g1 目錄下的 user1.py
#import users.g1.user1
# 確定程式檔案所在目錄, 在 Windows 有最後的反斜線
_curdir = os.path.join(os.getcwd(), os.path.dirname(__file__))
# 表示程式在近端執行, 最後必須決定是由 init.py 或此地決定目錄設定
config_dir = _curdir + "/config/"
static_dir = _curdir + "/static"
download_dir = _curdir + "/downloads/"
image_dir = _curdir + "/images/"
# 利用 init.py 啟動, 建立所需的相關檔案
initobj = init.Init()
# 取 init.py 中 Init 類別中的 class uwsgi 變數 (static variable) 設定
uwsgi = init.Init.uwsgi
# 必須先將 download_dir 設為 static_folder, 然後才可以用於 download 方法中的 app.static_folder 的呼叫
app = Flask(__name__)
# 設置隨後要在 blueprint 應用程式中引用的 global 變數
app.config['config_dir'] = config_dir
app.config['static_dir'] = static_dir
app.config['download_dir'] = download_dir
# 使用 session 必須要設定 secret_key
# In order to use sessions you have to set a secret key
# set the secret key. keep this really secret:
app.secret_key = 'A0Zr9@8j/3yX R~XHH!jmN]LWX/,?R@T'
# 子目錄中註冊藍圖位置
#app.register_blueprint(users.g1.user1.g1app)
@app.route('/checkLogin', methods=['POST'])
def checkLogin():
"""Check user login process."""
password = request.form["password"]
site_title, saved_password = parse_config()
hashed_password = hashlib.sha512(password.encode('utf-8')).hexdigest()
if hashed_password == saved_password:
session['admin'] = 1
return redirect('/edit_page')
return redirect('/')
@app.route('/delete_file', methods=['POST'])
def delete_file():
"""Delete user uploaded files."""
if not isAdmin():
return redirect("/login")
head, level, page = parse_content()
directory = render_menu(head, level, page)
filename = request.form['filename']
if filename is None:
outstring = "no file selected!"
return set_css() + "<div class='container'><nav>" + \
directory + "</nav><section><h1>Delete Error</h1>" + \
outstring + "<br/><br /></body></html>"
outstring = "delete all these files?<br /><br />"
outstring += "<form method='post' action='doDelete'>"
# only one file is selected
if isinstance(filename, str):
outstring += filename + "<input type='hidden' name='filename' value='" + \
filename + "'><br />"
else:
# multiple files selected
for index in range(len(filename)):
outstring += filename[index] + "<input type='hidden' name='filename' value='" + \
filename[index]+"'><br />"
outstring += "<br /><input type='submit' value='delete'></form>"
return set_css() + "<div class='container'><nav>" + \
directory + "</nav><section><h1>Download List</h1>" + \
outstring + "<br/><br /></body></html>"
@app.route('/doDelete', methods=['POST'])
def doDelete():
"""Action to delete user uploaded files."""
if not isAdmin():
return redirect("/login")
# delete files
filename = request.form['filename']
outstring = "all these files will be deleted:<br /><br />"
# only select one file
if isinstance(filename, str):
try:
os.remove(download_dir + "/" + filename)
outstring += filename + " deleted!"
except:
outstring += filename + "Error, can not delete files!<br />"
else:
# multiple files selected
for index in range(len(filename)):
try:
os.remove(download_dir + "/" + filename[index])
outstring += filename[index] + " deleted!<br />"
except:
outstring += filename[index] + "Error, can not delete files!<br />"
head, level, page = parse_content()
directory = render_menu(head, level, page)
return set_css() + "<div class='container'><nav>" + \
directory + "</nav><section><h1>Download List</h1>" + \
outstring + "<br/><br /></body></html>"
@app.route('/doSearch', methods=['POST'])
def doSearch():
"""Action to search content.htm using keyword"""
if not isAdmin():
return redirect("/login")
else:
keyword = request.form['keyword']
head, level, page = parse_content()
directory = render_menu(head, level, page)
match = ""
for index in range(len(head)):
if (keyword != "" or None) and (keyword.lower() in page[index].lower() or \
keyword.lower() in head[index].lower()): \
match += "<a href='/get_page/" + head[index] + "'>" + \
head[index] + "</a><br />"
return set_css() + "<div class='container'><nav>"+ \
directory + "</nav><section><h1>Search Result</h1>keyword: " + \
keyword.lower() + "<br /><br />in the following pages:<br /><br />" + \
match + "</section></div></body></html>"
@app.route('/download/', methods=['GET'])
def download():
"""Download file using URL."""
filename = request.args.get('filename')
type = request.args.get('type')
if type == "files":
return send_from_directory(download_dir, filename=filename)
else:
# for image files
return send_from_directory(image_dir, filename=filename)
@app.route('/download_list', methods=['GET'])
def download_list():
"""List files in downloads directory."""
if not isAdmin():
return redirect("/login")
else:
if not request.args.get('edit'):
edit= 1
else:
edit = request.args.get('edit')
if not request.args.get('page'):
page = 1
else:
page = request.args.get('page')
if not request.args.get('item_per_page'):
item_per_page = 10
else:
item_per_page = request.args.get('item_per_page')
if not request.args.get('keyword'):
keyword = ""
else:
keyword = request.args.get('keyword')
session['download_keyword'] = keyword
files = os.listdir(download_dir)
if keyword is not "":
files = [elem for elem in files if str(keyword) in elem]
files.sort()
total_rows = len(files)
totalpage = math.ceil(total_rows/int(item_per_page))
starti = int(item_per_page) * (int(page) - 1) + 1
endi = starti + int(item_per_page) - 1
outstring = "<form method='post' action='delete_file'>"
notlast = False
if total_rows > 0:
outstring += "<br />"
if (int(page) * int(item_per_page)) < total_rows:
notlast = True
if int(page) > 1:
outstring += "<a href='"
outstring += "download_list?&page=1&item_per_page=" + str(item_per_page) + \
"&keyword=" + str(session.get('download_keyword'))
outstring += "'><<</a> "
page_num = int(page) - 1
outstring += "<a href='"
outstring += "download_list?&page=" + str(page_num) + "&item_per_page=" + \
str(item_per_page) + "&keyword=" + str(session.get('download_keyword'))
outstring += "'>Previous</a> "
span = 10
for index in range(int(page)-span, int(page)+span):
if index>= 0 and index< totalpage:
page_now = index + 1
if page_now == int(page):
outstring += "<font size='+1' color='red'>" + str(page) + " </font>"
else:
outstring += "<a href='"
outstring += "download_list?&page=" + str(page_now) + "&item_per_page=" + \
str(item_per_page) + "&keyword=" + str(session.get('download_keyword'))
outstring += "'>"+str(page_now) + "</a> "
if notlast == True:
nextpage = int(page) + 1
outstring += " <a href='"
outstring += "download_list?&page=" + str(nextpage) + "&item_per_page=" + \
str(item_per_page) + "&keyword=" + str(session.get('download_keyword'))
outstring += "'>Next</a>"
outstring += " <a href='"
outstring += "download_list?&page=" + str(totalpage) + "&item_per_page=" + \
str(item_per_page) + "&keyword=" + str(session.get('download_keyword'))
outstring += "'>>></a><br /><br />"
if (int(page) * int(item_per_page)) < total_rows:
notlast = True
outstring += downloadlist_access_list(files, starti, endi) + "<br />"
else:
outstring += "<br /><br />"
outstring += downloadlist_access_list(files, starti, total_rows) + "<br />"
if int(page) > 1:
outstring += "<a href='"
outstring += "download_list?&page=1&item_per_page=" + str(item_per_page) + \
"&keyword=" + str(session.get('download_keyword'))
outstring += "'><<</a> "
page_num = int(page) - 1
outstring += "<a href='"
outstring += "download_list?&page=" + str(page_num) + "&item_per_page=" + \
str(item_per_page) + "&keyword=" + str(session.get('download_keyword'))
outstring += "'>Previous</a> "
span = 10
for index in range(int(page)-span, int(page)+span):
#for ($j=$page-$range;$j<$page+$range;$j++)
if index >=0 and index < totalpage:
page_now = index + 1
if page_now == int(page):
outstring += "<font size='+1' color='red'>" + str(page)+" </font>"
else:
outstring += "<a href='"
outstring += "download_list?&page=" + str(page_now) + \
"&item_per_page=" + str(item_per_page) + \
"&keyword=" + str(session.get('download_keyword'))
outstring += "'>" + str(page_now)+"</a> "
if notlast == True:
nextpage = int(page) + 1
outstring += " <a href='"
outstring += "download_list?&page=" + str(nextpage) + "&item_per_page=" + \
str(item_per_page) + "&keyword=" + str(session.get('download_keyword'))
outstring += "'>Next</a>"
outstring += " <a href='"
outstring += "download_list?&page=" + str(totalpage) + "&item_per_page=" + \
str(item_per_page) + "&keyword=" + str(session.get('download_keyword'))
outstring += "'>>></a>"
else:
outstring += "no data!"
outstring += "<br /><br /><input type='submit' value='delete'><input type='reset' value='reset'></form>"
head, level, page = parse_content()
directory = render_menu(head, level, page)
return set_css() + "<div class='container'><nav>" + \
directory + "</nav><section><h1>Download List</h1>" + outstring + "<br/><br /></body></html>"
def downloadlist_access_list(files, starti, endi):
"""List files function for download_list."""
# different extension files, associated links were provided
# popup window to view images, video or STL files, other files can be downloaded directly
# files are all the data to list, from starti to endi
# add file size
outstring = ""
for index in range(int(starti)-1, int(endi)):
fileName, fileExtension = os.path.splitext(files[index])
fileExtension = fileExtension.lower()
fileSize = sizeof_fmt(os.path.getsize(download_dir+"/"+files[index]))
# images files
if fileExtension == ".png" or fileExtension == ".jpg" or fileExtension == ".gif":
outstring += '<input type="checkbox" name="filename" value="' + \
files[index] + '"><a href="javascript:;" onClick="window.open(\'/images/'+ \
files[index] + '\',\'images\', \'catalogmode\',\'scrollbars\')">' + \
files[index] + '</a> (' + str(fileSize) + ')<br />'
# stl files
elif fileExtension == ".stl":
outstring += '<input type="checkbox" name="filename" value="' + \
files[index] + '"><a href="javascript:;" onClick="window.open(\'/static/viewstl.html?src=/downloads/' + \
files[index] + '\',\'images\', \'catalogmode\',\'scrollbars\')">' + \
files[index] + '</a> (' + str(fileSize) + ')<br />'
# flv files
elif fileExtension == ".flv":
outstring += '<input type="checkbox" name="filename" value="' + \
files[index] + '"><a href="javascript:;" onClick="window.open(\'/flvplayer?filepath=/downloads/' + \
files[index] + '\',\'images\', \'catalogmode\',\'scrollbars\')">' + files[index] + '</a> (' + str(fileSize) + ')<br />'
# direct download files
else:
outstring += "<input type='checkbox' name='filename' value='" + files[index] + \
"'><a href='/downloads/" + files[index] + "'>" + files[index] + \
"</a> (" + str(fileSize) + ")<br />"
return outstring
# downloads 方法主要將位於 downloads 目錄下的檔案送回瀏覽器
@app.route('/downloads/<path:path>')
def downloads(path):
"""Send files in downloads directory."""
return send_from_directory(_curdir+"/downloads/", path)
# 與 file_selector 搭配的取檔程式
def downloadselect_access_list(files, starti, endi):
"""Accompanied with file_selector."""
outstring = ""
for index in range(int(starti)-1, int(endi)):
fileName, fileExtension = os.path.splitext(files[index])
fileSize = os.path.getsize(download_dir + "/" + files[index])
outstring += '''<input type="checkbox" name="filename" value="''' + \
files[index] + '''"><a href="#" onclick='window.setLink("/downloads/''' + \
files[index] + '''",0); return false;'>''' + files[index] + \
'''</a> (''' + str(sizeof_fmt(fileSize)) + ''')<br />'''
return outstring
@app.route('/edit_config', defaults={'edit': 1})
@app.route('/edit_config/<path:edit>')
def edit_config(edit):
"""Config edit html form."""
head, level, page = parse_content()
directory = render_menu(head, level, page)
if not isAdmin():
return set_css() + "<div class='container'><nav>" + \
directory + "</nav><section><h1>Login</h1><form method='post' action='checkLogin'> \
Password:<input type='password' name='password'> \
<input type='submit' value='login'></form> \
</section></div></body></html>"
else:
site_title, password = parse_config()
# edit config file
return set_css() + "<div class='container'><nav>" + \
directory + "</nav><section><h1>Edit Config</h1><form method='post' action='saveConfig'> \
Site Title:<input type='text' name='site_title' value='"+site_title+"' size='50'><br /> \
Password:<input type='text' name='password' value='"+password+"' size='50'><br /> \
<input type='hidden' name='password2' value='"+password+"'> \
<input type='submit' value='send'></form> \
</section></div></body></html>"
# edit all page content
@app.route('/edit_page', defaults={'edit': 1})
@app.route('/edit_page/<path:edit>')
def edit_page(edit):
"""Page edit html form."""
# check if administrator
if not isAdmin():
return redirect('/login')
else:
head, level, page = parse_content()
directory = render_menu(head, level, page)
pagedata =file_get_contents(config_dir + "content.htm")
outstring = tinymce_editor(directory, cgi.escape(pagedata))
return outstring
def editorfoot():
return '''<body>'''
def editorhead():
return '''
<br />
<!--<script src="//cdn.tinymce.com/4/tinymce.min.js"></script>-->
<script src="/static/tinymce4/tinymce/tinymce.min.js"></script>
<script src="/static/tinymce4/tinymce/plugins/sh4tinymce/plugin.min.js"></script>
<link rel = "stylesheet" href = "/static/tinymce4/tinymce/plugins/sh4tinymce/style/style.css">
<script>
tinymce.init({
selector: "textarea",
height: 500,
element_format : "html",
language : "en",
valid_elements : '*[*]',
extended_valid_elements: "script[language|type|src]",
plugins: [
'advlist autolink lists link image charmap print preview hr anchor pagebreak',
'searchreplace wordcount visualblocks visualchars code fullscreen',
'insertdatetime media nonbreaking save table contextmenu directionality',
'emoticons template paste textcolor colorpicker textpattern imagetools sh4tinymce'
],
toolbar1: 'insertfile save undo redo | styleselect | bold italic | alignleft aligncenter alignright alignjustify | bullist numlist outdent indent',
toolbar2: 'link image | print preview media | forecolor backcolor emoticons | code sh4tinymce',
relative_urls: false,
toolbar_items_size: 'small',
file_picker_callback: function(callback, value, meta) {
cmsFilePicker(callback, value, meta);
},
templates: [
{ title: 'Test template 1', content: 'Test 1' },
{ title: 'Test template 2', content: 'Test 2' }
],
content_css: [
'//fonts.googleapis.com/css?family=Lato:300,300i,400,400i',
'//www.tinymce.com/css/codepen.min.css'
]
});
function cmsFilePicker(callback, value, meta) {
tinymce.activeEditor.windowManager.open({
title: 'Uploaded File Browser',
url: '/file_selector?type=' + meta.filetype,
width: 800,
height: 550,
}, {
oninsert: function (url, objVals) {
callback(url, objVals);
}
});
};
</script>
'''
@app.route('/error_log')
def error_log(self, info="Error"):
head, level, page = parse_content()
directory = render_menu(head, level, page)
return set_css() + "<div class='container'><nav>" + \
directory + "</nav><section><h1>ERROR</h1>" + info + "</section></div></body></html>"
def file_get_contents(filename):
# open file in utf-8 and return file content
with open(filename, encoding="utf-8") as file:
return file.read()
# 與 file_selector 配合, 用於 Tinymce4 編輯器的檔案選擇
def file_lister(directory, type=None, page=1, item_per_page=10):
files = os.listdir(directory)
total_rows = len(files)
totalpage = math.ceil(total_rows/int(item_per_page))
starti = int(item_per_page) * (int(page) - 1) + 1
endi = starti + int(item_per_page) - 1
outstring = file_selector_script()
notlast = False
if total_rows > 0:
outstring += "<br />"
if (int(page) * int(item_per_page)) < total_rows:
notlast = True
if int(page) > 1:
outstring += "<a href='"
outstring += "file_selector?type=" + type + \
"&page=1&item_per_page=" + \
str(item_per_page) + "&keyword=" + str(session.get('download_keyword'))
outstring += "'><<</a> "
page_num = int(page) - 1
outstring += "<a href='"
outstring += "file_selector?type=" + type + \
"&page=" + str(page_num) + \
"&item_per_page=" +str(item_per_page) + \
"&keyword=" + str(session.get('download_keyword'))
outstring += "'>Previous</a> "
span = 10
for index in range(int(page)-span, int(page)+span):
if index>= 0 and index< totalpage:
page_now = index + 1
if page_now == int(page):
outstring += "<font size='+1' color='red'>" + str(page) + " </font>"
else:
outstring += "<a href='"
outstring += "file_selector?type=" + type + "&page=" + \
str(page_now) + "&item_per_page=" + \
str(item_per_page) + "&keyword=" + \
str(session.get('download_keyword'))
outstring += "'>" + str(page_now)+"</a> "
if notlast == True:
nextpage = int(page) + 1
outstring += " <a href='"
outstring += "file_selector?type=" + type + "&page=" + \
str(nextpage) + "&item_per_page=" + \
str(item_per_page) + "&keyword=" + \
str(session.get('download_keyword'))
outstring += "'>Next</a>"
outstring += " <a href='"
outstring += "file_selector?type=" + type + "&page=" + \
str(totalpage) + "&item_per_page=" + \
str(item_per_page) + "&keyword=" + \
str(session.get('download_keyword'))
outstring += "'>>></a><br /><br />"
if (int(page) * int(item_per_page)) < total_rows:
notlast = True
if type == "file":
outstring += downloadselect_access_list(files, starti, endi) + "<br />"
else:
outstring += imageselect_access_list(files, starti, endi) + "<br />"
else:
outstring += "<br /><br />"
if type == "file":
outstring += downloadselect_access_list(files, starti, total_rows) + "<br />"
else:
outstring += imageselect_access_list(files, starti, total_rows) + "<br />"
if int(page) > 1:
outstring += "<a href='"
outstring += "file_selector?type=" + type + \
"&page=1&item_per_page=" + str(item_per_page) + \
"&keyword=" + str(session.get('download_keyword'))
outstring += "'><<</a> "
page_num = int(page) - 1
outstring += "<a href='"
outstring += "file_selector?type=" + type + "&page=" + \
str(page_num) + "&item_per_page=" + \
str(item_per_page) + "&keyword=" + \
str(session.get('download_keyword'))
outstring += "'>Previous</a>"
span = 10
for index in range(int(page)-span, int(page)+span):
if index >=0 and index < totalpage:
page_now = index + 1
if page_now == int(page):
outstring += "<font size='+1' color='red'>"+str(page)+" </font>"
else:
outstring += "<a href='"
outstring += "file_selector?type=" + type + "&page=" + \
str(page_now) + "&item_per_page=" + \
str(item_per_page) + "&keyword=" + \
str(session.get('download_keyword'))
outstring += "'>" + str(page_now) + "</a> "
if notlast == True:
nextpage = int(page) + 1
outstring += " <a href='"
outstring += "file_selector?type=" + type + "&page=" + \
str(nextpage) + "&item_per_page=" + \
str(item_per_page) + "&keyword=" + \
str(session.get('download_keyword'))
outstring += "'>Next</a>"
outstring += " <a href='"
outstring += "file_selector?type=" + type + "&page=" + \
str(totalpage) + "&item_per_page=" + \
str(item_per_page) + "&keyword=" + str(session.get('download_keyword'))
outstring += "'>>></a>"
else:
outstring += "no data!"
if type == "file":
return outstring+"<br /><br /><a href='fileuploadform'>file upload</a>"
else:
return outstring+"<br /><br /><a href='imageuploadform'>image upload</a>"
# 配合 Tinymce4 讓使用者透過 html editor 引用所上傳的 files 與 images
@app.route('/file_selector', methods=['GET'])
def file_selector():
if not isAdmin():
return redirect("/login")
else:
if not request.args.get('type'):
type= "file"
else:
type = request.args.get('type')
if not request.args.get('page'):
page = 1
else:
page = request.args.get('page')
if not request.args.get('item_per_page'):
item_per_page = 10
else:
item_per_page = request.args.get('item_per_page')
if not request.args.get('keyword'):
keyword = None
else:
keyword = request.args.get('keyword')
if type == "file":
return file_lister(download_dir, type, page, item_per_page)
elif type == "image":
return file_lister(image_dir, type, page, item_per_page)
def file_selector_script():
return '''
<script language="javascript" type="text/javascript">
$(function(){
$('.a').on('click', function(event){
setLink();
});
});
function setLink (url, objVals) {
top.tinymce.activeEditor.windowManager.getParams().oninsert(url, objVals);
top.tinymce.activeEditor.windowManager.close();
return false;
}
</script>
'''
@app.route('/fileaxupload', methods=['POST'])
# ajax jquery chunked file upload for flask
def fileaxupload():
if isAdmin():
# need to consider if the uploaded filename already existed.
# right now all existed files will be replaced with the new files
filename = request.args.get("ax-file-name")
flag = request.args.get("start")
if flag == "0":
file = open(_curdir + "/downloads/" + filename, "wb")
else:
file = open(_curdir + "/downloads/" + filename, "ab")
file.write(request.stream.read())
file.close()
return "files uploaded!"
else:
return redirect("/login")
@app.route('/fileuploadform', defaults={'edit':1})
@app.route('/fileuploadform/<path:edit>')
def fileuploadform(edit):
if isAdmin():
head, level, page = parse_content()
directory = render_menu(head, level, page)
return set_css() + "<div class='container'><nav>"+ \
directory + "</nav><section><h1>file upload</h1>" + \
'''<script src="/static/jquery.js" type="text/javascript"></script>
<script src="/static/axuploader.js" type="text/javascript"></script>
<script>
$(document).ready(function(){
$('.prova').axuploader({url:'fileaxupload', allowExt:['jpg','png','gif','7z','pdf','zip','flv','stl','swf'],
finish:function(x,files)
{
alert('All files have been uploaded: '+files);
},
enable:true,
remotePath:function(){
return 'downloads/';
}
});
});
</script>
<div class="prova"></div>
<input type="button" onclick="$('.prova').axuploader('disable')" value="asd" />
<input type="button" onclick="$('.prova').axuploader('enable')" value="ok" />
</section></body></html>
'''
else:
return redirect("/login")
@app.route('/flvplayer')
# 需要檢視能否取得 filepath 變數
def flvplayer(filepath=None):
outstring = '''
<object type="application/x-shockwave-flash" data="/static/player_flv_multi.swf" width="320" height="240">
<param name="movie" value="player_flv_multi.swf" />
<param name="allowFullScreen" value="true" />
<param name="FlashVars" value="flv=''' + filepath + '''&width=320&height=240&showstop=1&showvolume=1&showtime=1
&startimage=/static/startimage_en.jpg&showfullscreen=1&bgcolor1=189ca8&bgcolor2=085c68
&playercolor=085c68" />
</object>
'''
return outstring
@app.route('/generate_pages')
def generate_pages():
# 必須決定如何處理重複標題頁面的轉檔
import os
# 確定程式檔案所在目錄, 在 Windows 有最後的反斜線
_curdir = os.path.join(os.getcwd(), os.path.dirname(__file__))
# 根據 content.htm 內容, 逐一產生各頁面檔案
# 在此也要同時配合 render_menu2, 產生對應的 anchor 連結
head, level, page = parse_content()
# 處理重複標題 head 數列, 再重複標題按照次序加上 1, 2, 3...
newhead = []
for i, v in enumerate(head):
# 各重複標題總數
totalcount = head.count(v)
# 目前重複標題出現總數
count = head[:i].count(v)
# 針對重複標題者, 附加目前重複標題出現數 +1, 未重複採原標題
newhead.append(v + "-" + str(count + 1) if totalcount > 1 else v)
# 刪除 content 目錄中所有 html 檔案
filelist = [ f for f in os.listdir(_curdir + "\\content\\") if f.endswith(".html") ]
for f in filelist:
os.remove(os.path.join(_curdir + "\\content\\", f))
# 這裡需要建立專門寫出 html 的 write_page
# index.html
with open(_curdir + "\\content\\index.html", "w", encoding="utf-8") as f:
f.write(get_page2(None, newhead, 0))
# sitemap
with open(_curdir + "\\content\\sitemap.html", "w", encoding="utf-8") as f:
# sitemap2 需要 newhead
f.write(sitemap2(newhead))
# 以下轉檔, 改用 newhead 數列
def visible(element):
if element.parent.name in ['style', 'script', '[document]', 'head', 'title']:
return False
elif re.match('<!--.*-->', str(element.encode('utf-8'))):
return False
return True
search_content = []
for i in range(len(newhead)):
# 在此必須要將頁面中的 /images/ 字串換為 images/, /downloads/ 換為 downloads/
# 因為 Flask 中靠 /images/ 取檔案, 但是一般 html 則採相對目錄取檔案
# 此一字串置換在 get_page2 中進行
# 加入 tipue search 模式
get_page_content = []
html_doc = get_page2(newhead[i], newhead, 0, get_page_content)
soup = bs4.BeautifulSoup(" ".join(get_page_content), "lxml")
search_content.append({"title": newhead[i], "text": " ".join(filter(visible, soup.findAll(text=True))), "tags": "", "url": newhead[i] + ".html"})
with open(_curdir + "\\content\\" + newhead[i] + ".html", "w", encoding="utf-8") as f:
# 增加以 newhead 作為輸入
f.write(html_doc)
# GENERATE js file
with open(_curdir + "\\content\\tipuesearch_content.js", "w", encoding="utf-8") as f:
f.write("var tipuesearch = {\"pages\": " + str(search_content) + "};")
# generate each page html under content directory
return "已經將網站轉為靜態網頁. <a href='/'>Home</a>"
# seperate page need heading and edit variables, if edit=1, system will enter edit mode
# single page edit will use ssavePage to save content, it means seperate save page
@app.route('/get_page')
@app.route('/get_page/<heading>', defaults={'edit': 0})
@app.route('/get_page/<heading>/<int:edit>')
def get_page(heading, edit):
head, level, page = parse_content()
directory = render_menu(head, level, page)
if heading is None:
heading = head[0]
# 因為同一 heading 可能有多頁, 因此不可使用 head.index(heading) 搜尋 page_order
page_order_list, page_content_list = search_content(head, page, heading)
return_content = ""
pagedata = ""
outstring = ""
outstring_duplicate = ""
pagedata_duplicate = ""
outstring_list = []
for i in range(len(page_order_list)):
#page_order = head.index(heading)
page_order = page_order_list[i]
if page_order == 0:
last_page = ""
else:
last_page = head[page_order-1] + " << <a href='/get_page/" + \
head[page_order-1] + "'>Previous</a>"
if page_order == len(head) - 1:
# no next page
next_page = ""
else:
next_page = "<a href='/get_page/"+ head[page_order+1] + \
"'>Next</a> >> " + head[page_order+1]
if len(page_order_list) > 1:
return_content += last_page + " " + next_page + \
"<br /><h1>" + heading + "</h1>" + \
page_content_list[i] + "<br />"+ \
last_page + " " + next_page + "<br /><hr>"
pagedata_duplicate = "<h"+level[page_order] + ">" + heading + \
"</h"+level[page_order] + ">" + page_content_list[i]
outstring_list.append(last_page + " " + next_page + "<br />" + tinymce_editor(directory, cgi.escape(pagedata_duplicate), page_order))
else:
return_content += last_page + " " + next_page + "<br /><h1>" +\
heading + "</h1>" + page_content_list[i] + "<br />" + last_page + " " + next_page
pagedata += "<h"+level[page_order] + ">" + heading + "</h" + level[page_order] + ">" + page_content_list[i]
# 利用 cgi.escape() 將 specialchar 轉成只能顯示的格式
outstring += last_page + " " + next_page + "<br />" + tinymce_editor(directory, cgi.escape(pagedata), page_order)
# edit=0 for viewpage
if edit == 0:
return set_css() + "<div class='container'><nav>" + \
directory + "</nav><section>" + return_content + "</section></div></body></html>"
# enter edit mode
else:
# check if administrator
if not isAdmin():
redirect(url_for('login'))
else:
if len(page_order_list) > 1:
# 若碰到重複頁面頁印, 且要求編輯, 則導向 edit_page
#return redirect("/edit_page")
for i in range(len(page_order_list)):
outstring_duplicate += outstring_list[i] + "<br /><hr>"
return outstring_duplicate
else:
#pagedata = "<h"+level[page_order]+">"+heading+"</h"+level[page_order]+">"+search_content(head, page, heading)
#outstring = last_page+" "+next_page+"<br />"+ tinymce_editor(directory, cgi.escape(pagedata), page_order)
return outstring
# seperate page need heading and edit variables, if edit=1, system will enter edit mode
# single page edit will use ssavePage to save content, it means seperate save page
'''
@app.route('/get_page2')
@app.route('/get_page2/<heading>', defaults={'edit': 0})
@app.route('/get_page2/<heading>/<int:edit>')
'''
# before add tipue search function
#def get_page2(heading, head, edit):
def get_page2(heading, head, edit, get_page_content = None):
not_used_head, level, page = parse_content()
# 直接在此將 /images/ 換為 ./../images/, /downloads/ 換為 ./../downloads/, 以 content 為基準的相對目錄設定
page = [w.replace('/images/', './../images/') for w in page]
page = [w.replace('/downloads/', './../downloads/') for w in page]
# 假如有 src="/static/ace/則換為 src="./../static/ace/
page = [w.replace('src="/static/', 'src="./../static/') for w in page]
directory = render_menu2(head, level, page)
if heading is None:
heading = head[0]
# 因為同一 heading 可能有多頁, 因此不可使用 head.index(heading) 搜尋 page_order
page_order_list, page_content_list = search_content(head, page, heading)
if get_page_content is not None:
get_page_content.extend(page_content_list)
return_content = ""
pagedata = ""
outstring = ""
outstring_duplicate = ""
pagedata_duplicate = ""
outstring_list = []
for i in range(len(page_order_list)):
#page_order = head.index(heading)
page_order = page_order_list[i]
if page_order == 0:
last_page = ""
else:
#last_page = head[page_order-1]+ " << <a href='/get_page/" + head[page_order-1] + "'>Previous</a>"
last_page = head[page_order-1] + " << <a href='"+head[page_order-1] + ".html'>Previous</a>"
if page_order == len(head) - 1:
# no next page
next_page = ""
else:
#next_page = "<a href='/get_page/"+head[page_order+1] + "'>Next</a> >> " + head[page_order+1]
next_page = "<a href='" + head[page_order+1] + ".html'>Next</a> >> " + head[page_order+1]
if len(page_order_list) > 1:
return_content += last_page + " " + next_page + "<br /><h1>" + \
heading + "</h1>" + page_content_list[i] + \
"<br />" + last_page + " "+ next_page + "<br /><hr>"
pagedata_duplicate = "<h"+level[page_order] + ">" + heading + "</h" + level[page_order]+">"+page_content_list[i]
outstring_list.append(last_page + " " + next_page + "<br />" + tinymce_editor(directory, cgi.escape(pagedata_duplicate), page_order))
else:
return_content += last_page + " " + next_page + "<br /><h1>" + \
heading + "</h1>" + page_content_list[i] + \
"<br />" + last_page + " " + next_page
pagedata += "<h" + level[page_order] + ">" + heading + \
"</h" + level[page_order] + ">" + page_content_list[i]
# 利用 cgi.escape() 將 specialchar 轉成只能顯示的格式
outstring += last_page + " " + next_page + "<br />" + tinymce_editor(directory, cgi.escape(pagedata), page_order)
# edit=0 for viewpage
if edit == 0:
'''
# before add tipue search function
return set_css2() + "<div class='container'><nav>"+ \
directory + "</nav><section>" + return_content + "</section></div></body></html>"
'''
return set_css2() + "<div class='container'><nav>"+ \
directory + "</nav><section><div id=\"tipue_search_content\">" + return_content + "</div></section></div></body></html>"
# enter edit mode
else:
# check if administrator
if not isAdmin():
redirect(url_for('login'))
else:
if len(page_order_list) > 1:
# 若碰到重複頁面頁印, 且要求編輯, 則導向 edit_page
#return redirect("/edit_page")
for i in range(len(page_order_list)):
outstring_duplicate += outstring_list[i] + "<br /><hr>"
return outstring_duplicate
else:
#pagedata = "<h" + level[page_order]+">" + heading + "</h" + level[page_order] + ">" + search_content(head, page, heading)
#outstring = last_page + " " + next_page + "<br />" + tinymce_editor(directory, cgi.escape(pagedata), page_order)
return outstring
@app.route('/image_delete_file', methods=['POST'])
def image_delete_file():
if not isAdmin():
return redirect("/login")
filename = request.form['filename']
head, level, page = parse_content()
directory = render_menu(head, level, page)
if filename is None:
outstring = "no file selected!"
return set_css() + "<div class='container'><nav>" + \
directory + "</nav><section><h1>Delete Error</h1>" + \
outstring + "<br/><br /></body></html>"
outstring = "delete all these files?<br /><br />"
outstring += "<form method='post' action='image_doDelete'>"
# only one file is selected
if isinstance(filename, str):
outstring += filename + "<input type='hidden' name='filename' value='" + \
filename + "'><br />"
else:
# multiple files selected
for index in range(len(filename)):
outstring += filename[index] + "<input type='hidden' name='filename' value='" + \
filename[index] + "'><br />"
outstring += "<br /><input type='submit' value='delete'></form>"
return set_css() + "<div class='container'><nav>" + \
directory + "</nav><section><h1>Download List</h1>" + \
outstring + "<br/><br /></body></html>"
@app.route('/image_doDelete', methods=['POST'])
def image_doDelete():
if not isAdmin():
return redirect("/login")
# delete files
filename = request.form['filename']
outstring = "all these files will be deleted:<br /><br />"
# only select one file
if isinstance(filename, str):
try:
os.remove(image_dir + "/" + filename)
outstring += filename + " deleted!"
except:
outstring += filename + "Error, can not delete files!<br />"
else:
# multiple files selected
for index in range(len(filename)):
try:
os.remove(image_dir + "/" + filename[index])
outstring += filename[index] + " deleted!<br />"
except:
outstring += filename[index] + "Error, can not delete files!<br />"
head, level, page = parse_content()
directory = render_menu(head, level, page)
return set_css() + "<div class='container'><nav>" + \
directory + "</nav><section><h1>Image List</h1>" + \
outstring + "<br/><br /></body></html>"
@app.route('/image_list', methods=['GET'])
def image_list():
if not isAdmin():
return redirect("/login")
else:
if not request.args.get('edit'):
edit= 1
else:
edit = request.args.get('edit')
if not request.args.get('page'):
page = 1
else:
page = request.args.get('page')
if not request.args.get('item_per_page'):
item_per_page = 10
else:
item_per_page = request.args.get('item_per_page')
if not request.args.get('keyword'):
keyword = ""
else:
keyword = request.args.get('keyword')
session['image_keyword'] = keyword
files = os.listdir(image_dir)