routes.py 16 KB

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