routes.py 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366
  1. from flask import flash, render_template, Blueprint, request, redirect, url_for
  2. from flask.app import Flask
  3. from flask.wrappers import Response
  4. import requests
  5. import os
  6. import fnmatch
  7. import re
  8. import markdown
  9. import uuid
  10. from backstage.blogs.forms import BlogCreateForm
  11. from backstage.utils import get_now_time, translate
  12. from backstage.utils.routes import create_content, remove_content, get_trans_title_url_name
  13. from backstage.config import PORTAL_SERVER, UPLOAD_PATH_MAP
  14. blogs_app = Blueprint('blogs', __name__)
  15. SwfType = {
  16. "other_furniture": "其他",
  17. "master_bedroom": "臥室",
  18. "living_room": "客廳",
  19. "study_room": "書房",
  20. "dining_room": "餐廳",
  21. "custom_made_system_cabinet": "客製模組系統櫃",
  22. "system_cabinet": "模組系統櫃單品",
  23. }
  24. SfType = {
  25. "custom_made_system_cabinet": "客製模組系統櫃",
  26. "system_cabinet": "模組系統櫃單品",
  27. }
  28. furniturePath = UPLOAD_PATH_MAP[0][0] + '../設計家具'
  29. sfurniturePath = UPLOAD_PATH_MAP[0][0] + '../模組系統櫃'
  30. furnitureTypes = []
  31. furnitureTypeFiles = []
  32. furnitureFiles = []
  33. furnitures = []
  34. def refreshFur(itype):
  35. scanpath = ""
  36. furnitureTypes.clear()
  37. furnitureTypeFiles.clear()
  38. furnitureFiles.clear()
  39. furnitures.clear()
  40. if itype == '單品家具':
  41. scanpath = furniturePath
  42. else:
  43. scanpath = sfurniturePath
  44. for dirname, dirnames, filenames in os.walk(scanpath):
  45. # print path to all subdirectories first.
  46. for subdirname in dirnames:
  47. if subdirname.find('.') == -1:
  48. furnitureTypes.append(subdirname)
  49. # print path to all filenames.
  50. for filename in filenames:
  51. if filename.find('_index.md') >= 0:
  52. furnitureTypeFiles.append(os.path.join(dirname, filename))
  53. if filename.find('index.md') >= 0:
  54. furnitureFiles.append(os.path.join(dirname, filename))
  55. headerStart = False
  56. for files in furnitureFiles:
  57. tmpfurniture = {}
  58. with open(files, 'r', encoding="utf-8") as md:
  59. md_line_data = md.readlines()
  60. # print(md_line_data)
  61. for line in md_line_data:
  62. # print(line)
  63. if '---' in line:
  64. headerStart = not headerStart
  65. continue
  66. if headerStart:
  67. if 'title:' in line:
  68. tmpfurniture['title'] = re.split('"|\n', line)[1]
  69. if 'date:' in line:
  70. tmpfurniture['date'] = re.split(':"|\n', line)[0][6:]
  71. if 'draft:' in line:
  72. tmpfurniture['draft'] = re.split(':"|\n', line)[0][7:]
  73. if 'type:' in line:
  74. tmpfurniture['type'] = re.split('"|\n', line)[1]
  75. if 'url:' in line:
  76. tmpfurniture['url'] = re.split('"|\n', line)[1]
  77. if 'image:' in line:
  78. tmpfurniture['image'] = re.split('"|\n', line)[1]
  79. if 'tags:' in line:
  80. tmpfurniture['tags'] = re.split('"|\n', line)[1]
  81. # 避免加入類別項目
  82. if tmpfurniture['type'] != tmpfurniture['url'][1:]:
  83. furnitures.append(tmpfurniture)
  84. def newFur(irequest):
  85. # print(irequest.url)
  86. myType = {}
  87. myPath = ""
  88. # print(str(irequest.url).find("system_furniture"))
  89. if str(irequest.url).find("system_furniture") >= 0:
  90. myType = SfType
  91. myPath = sfurniturePath
  92. else:
  93. myType = SwfType
  94. myPath = furniturePath
  95. ename = get_trans_title_url_name(irequest.args['newSwfName'])
  96. front_matter = '''---
  97. title: "{}"
  98. date: {}
  99. draft: true
  100. type: "{}"
  101. url: "/{}/{}"
  102. image: ""
  103. ---'''.format(irequest.args['newSwfName'], get_now_time(), irequest.args['newSwfDropdown'], irequest.args['newSwfDropdown'], ename)
  104. newPath = myPath + '/' + \
  105. myType[irequest.args['newSwfDropdown']] + '/' + ename
  106. if not os.path.exists(newPath):
  107. os.mkdir(newPath)
  108. with open(os.path.join(newPath, 'index.md'), 'w', encoding="utf-8") as md:
  109. md.write(front_matter)
  110. # furniturePath
  111. # get_trans_title_url_name()
  112. return furniturePath
  113. @blogs_app.route('/backstage/blogs', methods=['GET'])
  114. def blog_list():
  115. response = requests.get('{}contents?url=/blog'.format(PORTAL_SERVER))
  116. if response.status_code == 200:
  117. #sortedData = sorted(response.json(), key=lambda x: x['date'], reverse=True)
  118. # print(sortedData)
  119. return render_template('blogs.html',
  120. title='設計專欄',
  121. legend='設計專欄列表',
  122. blogs=response.json(),
  123. length=len(response.json()),
  124. form=BlogCreateForm())
  125. @blogs_app.route('/backstage/new_solid_wood_furniture', methods=['GET'])
  126. def new_solid_wood_furniture():
  127. # edit_solid_wood_furniture()
  128. return newFur(request)
  129. @blogs_app.route('/backstage/new_system_furniture', methods=['GET'])
  130. def new_system_furniture():
  131. # edit_solid_wood_furniture()
  132. return newFur(request)
  133. @blogs_app.route('/backstage/del_solid_wood_furniture', methods=['GET'])
  134. def del_solid_wood_furniture():
  135. url = request.args.get('url', type=str)
  136. response = requests.delete('{}contents?url={}'.format(PORTAL_SERVER, url))
  137. if response.status_code == 200:
  138. flash('刪除文章成功', 'success')
  139. else:
  140. flash('刪除文章失敗', 'danger')
  141. # edit_solid_wood_furniture()
  142. return url
  143. @blogs_app.route('/backstage/edit_solid_wood_furniture', methods=['GET'])
  144. def edit_solid_wood_furniture():
  145. refreshFur('單品家具')
  146. sortedData = sorted(furnitures, key=lambda x: x['date'], reverse=True)
  147. sortedData = sorted(sortedData, key=lambda x: x['type'])
  148. return render_template('solid_wood_furniture.html',
  149. title='單品家具',
  150. legend='單品家具',
  151. furnitures=sortedData, length=len(furnitures),
  152. )
  153. @blogs_app.route('/backstage/edit_system_furniture', methods=['GET'])
  154. def edit_system_furniture():
  155. refreshFur('模組系統櫃')
  156. sortedData = sorted(furnitures, key=lambda x: x['date'], reverse=True)
  157. sortedData = sorted(sortedData, key=lambda x: x['type'])
  158. return render_template('system_furniture.html',
  159. title='模組系統櫃',
  160. legend='模組系統櫃',
  161. furnitures=sortedData, length=len(furnitures),
  162. )
  163. @blogs_app.route('/backstage/edit_news', methods=['GET'])
  164. def edit_news():
  165. response = requests.get('{}contents?url=/news'.format(PORTAL_SERVER))
  166. if response.status_code == 200:
  167. #sortedData = sorted(response.json(), key=lambda x: x['date'], reverse=True)
  168. return render_template('news.html',
  169. title='消息與報導',
  170. legend='消息與報導',
  171. news=response.json(), length=len(response.json()), form=BlogCreateForm()
  172. )
  173. @blogs_app.route('/backstage/edit_contact_us', methods=['GET'])
  174. def edit_contact_us():
  175. response = requests.get('{}contents?url=/contact'.format(PORTAL_SERVER))
  176. if response.status_code == 200:
  177. return render_template('contact_us.html',
  178. title='聯絡我們',
  179. )
  180. @blogs_app.route('/backstage/edit_faq', methods=['GET'])
  181. def edit_faq():
  182. return render_template('frequently_asked_questions.html',
  183. title='常見問題',
  184. )
  185. @blogs_app.route('/backstage/edit_contact_us_getemail', methods=['GET'])
  186. def edit_contact_us_getemail():
  187. txt = ""
  188. newEmail = request.args.get('newemail', type=str)
  189. footerpath = UPLOAD_PATH_MAP[0][0] + \
  190. "../../../bhouseWeb/themes/hugo-lamp/layouts/partials/footer.html"
  191. with open(footerpath, encoding="utf-8") as inf:
  192. txt = inf.read()
  193. result = txt[txt.find('"mailto:')+8:txt.find('"',txt.find('"mailto:')+1)]
  194. #sortedData = sorted(sortedData, key=lambda x: x['type'])
  195. return result
  196. @blogs_app.route('/backstage/edit_contact_us_editemail', methods=['GET'])
  197. def edit_contact_us_editemail():
  198. txt = ""
  199. newEmail = request.args.get('newemail', type=str)
  200. footerpath = UPLOAD_PATH_MAP[0][0] + \
  201. "../../../bhouseWeb/themes/hugo-lamp/layouts/partials/footer.html"
  202. with open(footerpath, encoding="utf-8") as inf:
  203. txt = inf.read()
  204. result = re.sub(r'"mailto:(\S*)"', '"mailto:' + newEmail + '"', txt)
  205. with open(footerpath, 'w' , encoding="utf-8") as inf:
  206. inf.write(result)
  207. #sortedData = sorted(sortedData, key=lambda x: x['type'])
  208. return "修改成功" + result
  209. @blogs_app.route('/backstage/blog/create/', methods=['POST'])
  210. def create():
  211. transcat = ""
  212. form = BlogCreateForm()
  213. if form.categories.data == "居家美學":
  214. transcat = "home_aesthetics"
  215. elif form.categories.data == "規劃師QA":
  216. transcat = "room_planner_expertise"
  217. elif form.categories.data == "驗屋知識":
  218. transcat = "home_inspection_knowledge"
  219. else:
  220. transcat = get_trans_title_url_name(form.categories.data)
  221. transtitle = get_trans_title_url_name(form.title.data)
  222. front_matter = '''---
  223. title: "{}"\n\
  224. date: {}\n\
  225. draft: {}\n\
  226. type: "{}"\n\
  227. url: "{}"\n\
  228. image: "/img/blog/{}"\n\
  229. categories: ["{}"]\n\
  230. col1: "{}"\n\
  231. col2: "{}"\n\
  232. ---'''.format(form.title.data,
  233. get_now_time(),
  234. 'true',
  235. 'blog',
  236. '/blog/{}'.format(transtitle),
  237. form.image.data.filename,
  238. form.categories.data,
  239. transcat, "")
  240. data = {'frontMatter': front_matter,
  241. 'name': transtitle,
  242. 'type': 'blog',
  243. 'categories': form.categories.data,
  244. # 'caturl': caturl
  245. }
  246. return create_content(data, form.image.data)
  247. @blogs_app.route('/backstage/blog/createCat/', methods=['GET'])
  248. def createCat():
  249. #title = ""
  250. front_matter = '''---
  251. title: "{}"\n\
  252. date: {}\n\
  253. draft: {}\n\
  254. type: "{}"\n\
  255. categories: ["{}"]\n\
  256. ---'''.format(request.args["title"],
  257. get_now_time(),
  258. 'false',
  259. 'blog',
  260. get_trans_title_url_name(request.args["title"]))
  261. CatPath = UPLOAD_PATH_MAP[0][0]+"../blog/" + get_trans_title_url_name(request.args["title"])
  262. # print(CatPath)
  263. if not os.path.exists(CatPath):
  264. os.mkdir(CatPath)
  265. with open(os.path.join(CatPath, 'category.md'), 'w', encoding="utf-8") as md:
  266. md.write(front_matter)
  267. print("11")
  268. return Response("你好", 200)
  269. @blogs_app.route('/backstage/news/create/', methods=['POST'])
  270. def createNews():
  271. form = BlogCreateForm()
  272. transtitle = get_trans_title_url_name(form.title.data)
  273. front_matter = '''---
  274. title: "{}"\n\
  275. date: {}\n\
  276. draft: {}\n\
  277. type: "{}"\n\
  278. url: "{}"\n\
  279. image: ""\n\
  280. ---'''.format(form.title.data,
  281. get_now_time(),
  282. 'true',
  283. 'news',
  284. '/news/{}'.format(transtitle))
  285. data = {'frontMatter': front_matter,
  286. 'name': transtitle,
  287. 'type': 'news',
  288. }
  289. return create_content(data, form.image.data)
  290. @blogs_app.route('/backstage/blog/remove', methods=['POST'])
  291. def remove():
  292. remove_content()
  293. return redirect(url_for('blogs.blog_list'))
  294. @blogs_app.route('/backstage/news/remove', methods=['POST'])
  295. def removeNews():
  296. remove_content()
  297. return redirect(url_for('blogs.edit_news'))
  298. @blogs_app.route('/backstage/utils', methods=['GET'])
  299. def transService():
  300. # print(request.args["trantext"])
  301. return get_trans_title_url_name(request.args["trantext"])
  302. """ def GetCategories():
  303. GetCategories
  304. configfiles = [os.path.join(dirpath, f)
  305. for dirpath, dirnames, files in os.walk(UPLOAD_PATH_MAP+'../blog')
  306. for f in fnmatch.filter(files, 'category.md')]
  307. return configfiles """