routes.py 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443
  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. import subprocess
  11. from backstage.blogs.forms import BlogCreateForm
  12. from backstage.utils import get_now_time, translate
  13. from backstage.utils.routes import create_content, remove_content, get_trans_title_url_name
  14. from backstage.config import PORTAL_SERVER, UPLOAD_PATH_MAP, BHOUSE_WEB_DIR
  15. from bs4 import BeautifulSoup
  16. blogs_app = Blueprint('blogs', __name__)
  17. SwfType = {
  18. "other_furniture": "other_furniture",
  19. "sofa":"sofa",
  20. "cabinet":"cabinet",
  21. "desk":"desk",
  22. "dining_chair":"dining_chair",
  23. "dining_table":"dining_table",
  24. "mattress":"mattress",
  25. "side_cabinet":"side_cabinet",
  26. "side_table":"side_table",
  27. "wardrobe":"wardrobe",
  28. }
  29. SfType = {
  30. "custom_made_system_cabinet": "客製模組系統櫃",
  31. "system_cabinet": "模組系統櫃單品",
  32. }
  33. #furniturePath = UPLOAD_PATH_MAP[0][0] + '../設計家具'
  34. furniturePath = BHOUSE_WEB_DIR + '/content/furniture_design_list'
  35. sfurniturePath = UPLOAD_PATH_MAP[0][0] + '../模組系統櫃'
  36. furnitureTypes = []
  37. furnitureTypeFiles = []
  38. furnitureFiles = []
  39. furnitures = []
  40. def refreshFur(itype):
  41. scanpath = ""
  42. furnitureTypes.clear()
  43. furnitureTypeFiles.clear()
  44. furnitureFiles.clear()
  45. furnitures.clear()
  46. if itype == '單品家具':
  47. scanpath = furniturePath
  48. else:
  49. scanpath = sfurniturePath
  50. print(scanpath)
  51. for dirname, dirnames, filenames in os.walk(scanpath):
  52. # print path to all subdirectories first.
  53. for subdirname in dirnames:
  54. if subdirname.find('.') == -1:
  55. furnitureTypes.append(subdirname)
  56. # print path to all filenames.
  57. for filename in filenames:
  58. if filename.find('_index.md') >= 0:
  59. furnitureTypeFiles.append(os.path.join(dirname, filename))
  60. if filename.find('index.md') >= 0:
  61. furnitureFiles.append(os.path.join(dirname, filename))
  62. headerStart = False
  63. for files in furnitureFiles:
  64. tmpfurniture = {}
  65. typeFlag = 0 #if type does not exist flag will not be triggered
  66. with open(files, 'r', encoding="utf-8") as md:
  67. md_line_data = md.readlines()
  68. # print(md_line_data)
  69. for line in md_line_data:
  70. # print(line)
  71. if '---' in line:
  72. headerStart = not headerStart
  73. continue
  74. if headerStart:
  75. if 'title:' in line:
  76. tmpfurniture['title'] = re.split('"|\n', line)[1]
  77. if 'date:' in line:
  78. tmpfurniture['date'] = re.split(':"|\n', line)[0][6:]
  79. if 'draft:' in line:
  80. tmpfurniture['draft'] = re.split(':"|\n', line)[0][7:]
  81. if 'type:' in line:
  82. typeFlag = 1
  83. tmpfurniture['type'] = re.split('"|\n', line)[1]
  84. if 'url:' in line:
  85. tmpfurniture['url'] = re.split('"|\n', line)[1]
  86. if 'image:' in line:
  87. tmpfurniture['image'] = re.split('"|\n', line)[1]
  88. if 'tags:' in line:
  89. tmpfurniture['tags'] = re.split('"|\n', line)[1]
  90. # 避免加入類別項目
  91. if typeFlag == 0:
  92. furnitures.append(tmpfurniture)
  93. elif tmpfurniture['type'] != tmpfurniture['url'][1:]:
  94. furnitures.append(tmpfurniture)
  95. def newFur(irequest):
  96. # print(irequest.url)
  97. myType = {}
  98. myPath = ""
  99. # print(str(irequest.url).find("system_furniture"))
  100. if str(irequest.url).find("system_furniture") >= 0:
  101. myType = SfType
  102. myPath = sfurniturePath
  103. else:
  104. myType = SwfType
  105. myPath = furniturePath
  106. ename = get_trans_title_url_name(irequest.args['newSwfName'])
  107. front_matter = '''---
  108. meta_title: "{}"\n
  109. meta_description: "{}"\n
  110. title: "{}"\n
  111. date: {}\n
  112. draft: true\n
  113. type: "{}"\n
  114. url: "/furniture_design/{}/{}"\n
  115. image: ""\n
  116. ---'''.format(irequest.args['newSwfName'], '', irequest.args['newSwfName'], get_now_time(), irequest.args['newSwfDropdown'], irequest.args['newSwfDropdown'], ename)
  117. newPath = myPath + '/' + myType[irequest.args['newSwfDropdown']] + '/' + ename
  118. if not os.path.exists(newPath):
  119. os.mkdir(newPath)
  120. newPath = newPath
  121. with open(os.path.join(newPath, 'index.md'), 'w', encoding="utf-8") as md:
  122. md.write(front_matter)
  123. # furniturePath
  124. # get_trans_title_url_name()
  125. return furniturePath
  126. @blogs_app.route('/backstage/update', methods=['GET'])
  127. def update():
  128. #subprocess.run(["cp", "-r", "/var/www/bhouse2", "/var/www/bhousebackup"], shell=True)
  129. subprocess.run(["cd /var/www/bhouse2/New-Bhouse-Web; hugo"], shell=True)
  130. subprocess.run(["rsync", "-azn", "-e", "ssh", "/var/www/bhouse2/New-Bhouse-Web/public", "root@172.105.241.163:/var/www/New-Bhouse-Web"], shell=True) # remove n before handing to customer
  131. return redirect(url_for('blogs.blog_list'))
  132. @blogs_app.route('/backstage/blogs', methods=['GET'])
  133. def blog_list():
  134. response = requests.get('{}contents?url=/blog'.format(PORTAL_SERVER))
  135. #print('{}contents?url=/blog'.format(PORTAL_SERVER))
  136. if response.status_code == 200:
  137. sortedData = sorted(response.json(), key=lambda x: x['date'], reverse=True)
  138. return render_template('blogs.html',
  139. title='設計專欄',
  140. legend='設計專欄列表',
  141. blogs=sortedData,
  142. length=len(response.json()),
  143. form=BlogCreateForm())
  144. @blogs_app.route('/backstage/new_solid_wood_furniture', methods=['GET'])
  145. def new_solid_wood_furniture():
  146. # edit_solid_wood_furniture()
  147. return newFur(request)
  148. @blogs_app.route('/backstage/new_system_furniture', methods=['GET'])
  149. def new_system_furniture():
  150. # edit_solid_wood_furniture()
  151. return newFur(request)
  152. @blogs_app.route('/backstage/del_solid_wood_furniture', methods=['GET'])
  153. def del_solid_wood_furniture():
  154. url = request.args.get('url', type=str)
  155. response = requests.delete('{}contents?url={}'.format(PORTAL_SERVER, url))
  156. if response.status_code == 200:
  157. flash('刪除文章成功', 'success')
  158. else:
  159. flash('刪除文章失敗', 'danger')
  160. # edit_solid_wood_furniture()
  161. return url
  162. @blogs_app.route('/backstage/edit_solid_wood_furniture', methods=['GET'])
  163. def edit_solid_wood_furniture():
  164. response = requests.get('{}contents?url=/furniture_design'.format(PORTAL_SERVER))
  165. #print('{}contents?url=/maincategories'.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('solid_wood_furniture.html',
  169. title='單品家具',
  170. legend='單品家具',
  171. furnitures=response.json(),
  172. length=len(response.json()))
  173. '''
  174. def edit_solid_wood_furniture():
  175. refreshFur('單品家具')
  176. sortedData = sorted(furnitures, key=lambda x: x['date'], reverse=True)
  177. sortedData = sorted(sortedData, key=lambda x: x['type'])
  178. sortedData = furnitures
  179. return render_template('solid_wood_furniture.html',
  180. title='單品家具',
  181. legend='單品家具',
  182. furnitures=sortedData, length=len(furnitures),
  183. )
  184. '''
  185. @blogs_app.route('/backstage/edit_system_furniture', methods=['GET'])
  186. def edit_system_furniture():
  187. refreshFur('模組系統櫃')
  188. sortedData = sorted(furnitures, key=lambda x: x['date'], reverse=True)
  189. sortedData = sorted(sortedData, key=lambda x: x['type'])
  190. return render_template('system_furniture.html',
  191. title='模組系統櫃',
  192. legend='模組系統櫃',
  193. furnitures=sortedData, length=len(furnitures),
  194. )
  195. @blogs_app.route('/backstage/edit_news', methods=['GET'])
  196. def edit_news():
  197. response = requests.get('{}contents?url=/news'.format(PORTAL_SERVER))
  198. if response.status_code == 200:
  199. #sortedData = sorted(response.json(), key=lambda x: x['date'], reverse=True)
  200. return render_template('news.html',
  201. title='消息與報導',
  202. legend='消息與報導',
  203. news=response.json(), length=len(response.json()), form=BlogCreateForm()
  204. )
  205. @blogs_app.route('/backstage/edit_contact_us', methods=['GET'])
  206. def edit_contact_us():
  207. return render_template('contact_us.html',
  208. title='聯絡我們',
  209. )
  210. @blogs_app.route('/backstage/edit_further', methods=['GET'])
  211. def edit_further():
  212. return render_template('further.html',
  213. title='編輯延伸閱讀',
  214. )
  215. @blogs_app.route('/backstage/edit_faq', methods=['GET'])
  216. def edit_faq():
  217. return render_template('frequently_asked_questions.html',
  218. title='常見問題',
  219. )
  220. @blogs_app.route('/backstage/edit_contact_us_getemail', methods=['GET'])
  221. def edit_contact_us_getemail():
  222. txt = ""
  223. newEmail = request.args.get('newemail', type=str)
  224. footerpath = BHOUSE_WEB_DIR + "/themes/hugo-universal-theme-master/layouts/partials/footer.html"
  225. with open(footerpath, encoding="utf-8") as inf:
  226. txt = inf.read()
  227. result = txt[txt.find('"mailto:')+8:txt.find('"',txt.find('"mailto:')+1)]
  228. #sortedData = sorted(sortedData, key=lambda x: x['type'])
  229. return result
  230. @blogs_app.route('/backstage/edit_contact_us_editemail', methods=['GET'])
  231. def edit_contact_us_editemail():
  232. txt = ""
  233. newEmail = request.args.get('newemail', type=str)
  234. footerpath = BHOUSE_WEB_DIR + "/themes/hugo-universal-theme-master/layouts/partials/footer.html"
  235. with open(footerpath, encoding="utf-8") as inf:
  236. txt = inf.read()
  237. result = re.sub(r'"mailto:(\S*)"', '"mailto:' + newEmail + '"', txt)
  238. with open(footerpath, 'w' , encoding="utf-8") as inf:
  239. inf.write(result)
  240. #sortedData = sorted(sortedData, key=lambda x: x['type'])
  241. return "修改成功" + result
  242. @blogs_app.route('/backstage/blog/create/', methods=['POST'])
  243. def create():
  244. transcat = ""
  245. form = BlogCreateForm()
  246. if form.categories.data == "居家美學":
  247. transcat = "home_aesthetics"
  248. elif form.categories.data == "規劃師QA":
  249. transcat = "room_planner_expertise"
  250. elif form.categories.data == "驗屋知識":
  251. transcat = "home_inspection_knowledge"
  252. else:
  253. transcat = get_trans_title_url_name(form.categories.data)
  254. transtitle = get_trans_title_url_name(form.title.data)
  255. form.image.data.filename = str(uuid.uuid4()).replace('-','') + ".webp"
  256. front_matter = '''---
  257. meta_title: "{}"\n\
  258. meta_description: "{}"\n\
  259. title: "{}"\n\
  260. date: {}\n\
  261. draft: {}\n\
  262. type: "{}"\n\
  263. url: "{}"\n\
  264. image: "/img/title/{}"\n\
  265. categories: "{}"\n\
  266. col1: "{}"\n\
  267. col2: "{}"\n\
  268. introduction: "{}"\n\
  269. question_box_intro: "{}"\n\
  270. ---'''.format(form.title.data, "", form.title.data,
  271. get_now_time(),
  272. 'true',
  273. 'blog',
  274. '/blog/{}'.format(transtitle),
  275. form.image.data.filename,
  276. form.categories.data,
  277. transcat, "", "", "")
  278. data = {'frontMatter': front_matter,
  279. 'name': transtitle,
  280. 'type': 'blog',
  281. 'categories': form.categories.data,
  282. # 'caturl': caturl
  283. }
  284. return create_content(data, form.image.data)
  285. @blogs_app.route('/backstage/edit_blog_getfurther', methods=['GET'])
  286. def edit_blog_getfurther():
  287. txt = ""
  288. datapath = BHOUSE_WEB_DIR + "/themes/hugo-universal-theme-master/layouts/partials/further.html"
  289. data=[]
  290. with open(datapath, encoding="utf-8") as inf:
  291. obj=BeautifulSoup(inf, 'html.parser', from_encoding="utf+8").find_all("a")
  292. for item in obj:
  293. data.append([item.get('href'), item.text])
  294. #sortedData = sorted(sortedData, key=lambda x: x['type'])
  295. return {"data": data}
  296. @blogs_app.route('/backstage/edit_blog_editfurther', methods=['GET'])
  297. def edit_blog_editfurther():
  298. txt = ""
  299. data=[]
  300. data.append([request.args.get('data00', type=str), request.args.get('data01', type=str)])
  301. data.append([request.args.get('data10', type=str), request.args.get('data11', type=str)])
  302. data.append([request.args.get('data20', type=str), request.args.get('data21', type=str)])
  303. data.append([request.args.get('data30', type=str), request.args.get('data31', type=str)])
  304. data.append([request.args.get('data40', type=str), request.args.get('data41', type=str)])
  305. print(data)
  306. datapath = BHOUSE_WEB_DIR + "/themes/hugo-universal-theme-master/layouts/partials/further.html"
  307. with open(datapath, 'w' , encoding="utf-8") as inf:
  308. for d in data:
  309. if d[1]!='':
  310. inf.write('<li><a href="' + d[0] + '">' + d[1] + '</a></li>\n')
  311. #sortedData = sorted(sortedData, key=lambda x: x['type'])
  312. return "修改成功"
  313. @blogs_app.route('/backstage/blog/createCat/', methods=['GET'])
  314. def createCat():
  315. #title = ""
  316. front_matter = '''---
  317. title: "{}"\n\
  318. date: {}\n\
  319. draft: {}\n\
  320. type: "{}"\n\
  321. categories: "{}"\n\
  322. ---'''.format(request.args["title"],
  323. get_now_time(),
  324. 'false',
  325. 'blog',
  326. get_trans_title_url_name(request.args["title"]))
  327. CatPath = UPLOAD_PATH_MAP[0][0]+"../blog/" + get_trans_title_url_name(request.args["title"])
  328. # print(CatPath)
  329. if not os.path.exists(CatPath):
  330. os.mkdir(CatPath)
  331. with open(os.path.join(CatPath, 'category.md'), 'w', encoding="utf-8") as md:
  332. md.write(front_matter)
  333. print("11")
  334. return Response("你好", 200)
  335. @blogs_app.route('/backstage/news/create/', methods=['POST'])
  336. def createNews():
  337. form = BlogCreateForm()
  338. transtitle = get_trans_title_url_name(form.title.data)
  339. front_matter = '''---
  340. meta_title: "{}"\n
  341. meta_description: "{}"\n
  342. title: "{}"\n\
  343. date: {}\n\
  344. draft: {}\n\
  345. display: {}\n\
  346. type: "{}"\n\
  347. url: "{}"\n\
  348. image: ""\n\
  349. ---'''.format(form.title.data, '', form.title.data,
  350. get_now_time(),
  351. 'true',
  352. 'false',
  353. 'news',
  354. '/news/{}'.format(transtitle))
  355. data = {'frontMatter': front_matter,
  356. 'name': transtitle,
  357. 'type': 'news',
  358. }
  359. return create_content(data, form.image.data)
  360. @blogs_app.route('/backstage/blog/remove', methods=['POST'])
  361. def remove():
  362. remove_content()
  363. return redirect(url_for('blogs.blog_list'))
  364. @blogs_app.route('/backstage/news/remove', methods=['POST'])
  365. def removeNews():
  366. remove_content()
  367. return redirect(url_for('blogs.edit_news'))
  368. @blogs_app.route('/backstage/utils', methods=['GET'])
  369. def transService():
  370. # print(request.args["trantext"])
  371. return get_trans_title_url_name(request.args["trantext"])
  372. """ def GetCategories():
  373. GetCategories
  374. configfiles = [os.path.join(dirpath, f)
  375. for dirpath, dirnames, files in os.walk(UPLOAD_PATH_MAP+'../blog')
  376. for f in fnmatch.filter(files, 'category.md')]
  377. return configfiles """