routes.py 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339
  1. from flask import request, Blueprint
  2. from flask.wrappers import Response
  3. from flask_restful import Resource, Api
  4. from os import path, remove, walk, mkdir
  5. import logging
  6. import re
  7. from models.config import CONTENT_DIR, STATIC_DIR
  8. import shutil
  9. from backstage.utils.routes import get_trans_title_url_name
  10. contents_app = Blueprint('contents', __name__)
  11. api = Api(contents_app)
  12. logger = logging.getLogger(__name__)
  13. DATA_FIELD = ['title:', 'url:','tags:','image:','description:']
  14. def _get_data(file_dir):
  15. def load_data():
  16. if 'meta_title:' in line:
  17. s = line.split('"')
  18. result['meta_title'] = s[1]
  19. elif 'collection_title:' in line:
  20. s = line.split('"')
  21. result['collection_title'] = s[1]
  22. elif 'title:' in line:
  23. #print(line) # debug use
  24. #data_field.remove('title: ') #i have to remove this because you wont get the correct results
  25. s = line.split('"')
  26. result['title'] = s[1]
  27. elif 'date: ' in line:
  28. # data_field.remove('date: ')
  29. s = line.replace('date: ', '').strip()
  30. result['date'] = s
  31. elif 'draft: ' in line:
  32. # data_field.remove('draft: ')
  33. s = line.replace('draft: ', '').strip()
  34. result['draft'] = s
  35. elif 'display: ' in line:
  36. # data_field.remove('draft: ')
  37. s = line.replace('display: ', '').strip()
  38. result['display'] = s
  39. elif 'url: ' in line:
  40. data_field.remove('url:')
  41. s = line.split('"')
  42. result['url'] = s[1]
  43. elif 'tags: ' in line:
  44. data_field.remove('tags:')
  45. s = line.replace('tags: ', '').strip()
  46. """ if s != "":
  47. s = s + ","
  48. s = s + "全部屋型,全部坪數,全部預算,全部格局" """
  49. result['tags'] = s
  50. elif 'categories: ' in line:
  51. s = line.replace('categories: ', '').strip()
  52. result['categories'] = s
  53. elif 'blog_tag: ' in line:
  54. s = line.replace('blog_tag: ', '').strip()
  55. result['blog_tag'] = s
  56. # elif 'readmore_ttl: ' in line:
  57. # s = line.replace('readmore_ttl: ', '').strip()
  58. # result['readmore_ttl'] = s
  59. elif 'readmore_lnk: ' in line:
  60. s = line.replace('readmore_lnk: ', '').strip()
  61. result['readmore_lnk'] = s
  62. elif 'image: ' in line:
  63. s = line.replace('image: ', '').strip()
  64. s = s.replace('"', '').strip()
  65. result['image'] = s
  66. elif 'collection_description: ' in line:
  67. s = line.replace('collection_description: ', '').strip()
  68. s = s.replace('"', '').strip()
  69. result['collection_description'] = s
  70. elif 'banner_img_text: ' in line:
  71. s = line.replace('banner_img_text: ', '').strip()
  72. s = s.replace('"', '').strip()
  73. result['banner_img_text'] = s
  74. elif 'homeowner: ' in line:
  75. s = line.replace('homeowner: ', '').strip()
  76. s = s.replace('"', '').strip()
  77. result['homeowner'] = s
  78. elif 'room_count: ' in line:
  79. s = line.replace('room_count: ', '').strip()
  80. s = s.replace('"', '').strip()
  81. result['room_count'] = s
  82. elif 'house_size: ' in line:
  83. s = line.replace('house_size: ', '').strip()
  84. s = s.replace('"', '').strip()
  85. result['house_size'] = s
  86. elif 'description: ' in line:
  87. s = line.replace('description: ', '').strip()
  88. s = s.replace('"', '').strip()
  89. result['description'] = s
  90. data_field = list(DATA_FIELD)
  91. result = {}
  92. with open(file_dir, 'r', encoding="utf-8") as md:
  93. result['content'] = md.read()
  94. md.seek(0)
  95. md_line_data = md.readlines()
  96. for line in md_line_data:
  97. load_data()
  98. if not data_field:
  99. return result
  100. if not 'tags' in result:
  101. result['tags'] = "全部類型,全部坪數,全部預算,全部格局"
  102. else:
  103. if result['tags'] != "":
  104. result['tags'] = result['tags'] + ","
  105. result['tags'] = result['tags'].replace('"', '') + "全部類型,全部坪數,全部預算,全部格局"
  106. return result
  107. def _gen_content_files():
  108. for root, dirs, files in walk(CONTENT_DIR):
  109. for f in files:
  110. if '.md' not in f:
  111. continue
  112. yield path.join(root, f)
  113. def _search_dir(url):
  114. def _get_file_front_matter_url():
  115. with open(file_dir, 'r', encoding="utf-8") as md:
  116. md_line_data = md.readlines()
  117. for line in md_line_data:
  118. if 'url:' in line:
  119. return list(filter(None, re.split('"|\n', line)))[-1]
  120. for file_dir in _gen_content_files():
  121. if url == _get_file_front_matter_url():
  122. return path.dirname(file_dir)
  123. def _search_content_dir(type_, categories=None):
  124. target = categories or type_
  125. def _get_file_front_matter_type():
  126. with open(file_dir, 'r', encoding="utf-8") as md:
  127. md_line_data = md.readlines()
  128. for line in md_line_data:
  129. if categories:
  130. if 'categories' in line:
  131. return list(filter(None, re.split('"|\n|]', line)))[-1]
  132. else:
  133. if 'type:' in line:
  134. return list(filter(None, re.split('"|\n', line)))[-1]
  135. for file_dir in _gen_content_files():
  136. if target == _get_file_front_matter_type():
  137. return path.dirname(file_dir)
  138. class Content(Resource):
  139. DATA_FIELD = ['title:', 'url:']
  140. @property
  141. def url(self):
  142. return request.args.get('url', type=str)
  143. def _search_content(self):
  144. result = {}
  145. for file_dir in _gen_content_files():
  146. data = _get_data(file_dir)
  147. if self.url in data.get('url', ''):
  148. result = data
  149. result['path'] = file_dir
  150. #print(result['path'])
  151. yield result
  152. def _get_contents(self):
  153. for file_dir in _gen_content_files():
  154. yield _get_data(file_dir)
  155. def get(self):
  156. if self.url:
  157. results = self._search_content()
  158. else:
  159. results = self._get_contents()
  160. x = list(results)
  161. print(type(x), type(results))
  162. x.sort(key = lambda k: k["date"], reverse=True)
  163. return x
  164. def post(self):
  165. try:
  166. requrl = request.args.get('url', type=str)
  167. print(requrl)
  168. if "frequently_asked_questions" in requrl:
  169. file_dir = path.join(_search_dir(requrl), '_index.md')
  170. else:
  171. file_dir = path.join(_search_dir(requrl), 'index.md')
  172. md_content = request.json.get('content')
  173. with open(file_dir, 'w', encoding="utf-8") as md:
  174. md.write(md_content)
  175. return md_content
  176. except TypeError as err:
  177. logger.error(
  178. 'Content post failed with file_dir param contain None. error: {}'.format(err))
  179. except OSError as err:
  180. logger.error(
  181. 'Content post failed with: {} is not exist{}'.format(file_dir, err))
  182. except AttributeError as err:
  183. logger.error('Content post failed with AttributeError: {}'.format(err))
  184. except Exception as err:
  185. logger.error('Content post failed with: {}'.format(err))
  186. def delete(self):
  187. content_data = list(self._search_content())
  188. file_dir = content_data[0].get('path')
  189. if path.exists(file_dir):
  190. # remove(file_dir)
  191. shutil.rmtree(file_dir[0:file_dir.replace('\\', '/').rfind('/')+1])
  192. # print(file_dir[0:file_dir.replace('\\','/').rfind('/')+1])
  193. logger.info('delete dir: {}'.format(
  194. file_dir[0:file_dir.replace('\\', '/').rfind('/')+1]))
  195. else:
  196. logger.warning('delete fail with {} not exist'.format(file_dir))
  197. @contents_app.route('/api/upload/img', methods=['POST'])
  198. def upload_img():
  199. img_data = request.files['image']
  200. file_dir = _search_dir(request.args.get('url', type=str))
  201. #print("file_dir 1 is " + file_dir)
  202. img_dir = path.join(file_dir, 'img/{}'.format(img_data.filename))
  203. print("img_dir 1 is " + img_dir)
  204. img_data.save(img_dir)
  205. return {'filename': img_data.filename}
  206. @contents_app.route('/api/upload/img_to_dir', methods=['POST'])
  207. def upload_img_to_dir():
  208. img_data = request.files['image']
  209. file_dir = _search_dir(request.args.get('url', type=str))
  210. #print("file_dir 2 is " + file_dir)
  211. img_dir = path.join(file_dir, 'img/{}'.format(request.args.get('filename', type=str)))
  212. print("img_dir 2 is " + img_dir)
  213. img_data.save(img_dir)
  214. return {'filename': img_data.filename}
  215. @contents_app.route('/api/delete/img', methods=['DELETE'])
  216. def delete_img():
  217. try:
  218. file_dir = _search_dir(request.args.get('url', type=str))
  219. img_dir = path.join(file_dir, 'img/{}'.format(request.args.get('filename', type=str)))
  220. remove(img_dir)
  221. logger.info('delete img: {}'.format(img_dir))
  222. return {'filename': request.args.get('filename', type=str)}
  223. except TypeError as err:
  224. logger.error('delete img: {} failed with file_dir is None. error: {}'.format(
  225. request.args.get('filename', type=str), err))
  226. return {'filename': request.args.get('filename', type=str)}
  227. except OSError as err:
  228. logger.error('delete img: {} failed with img_dir is not exist. error: {}'.format(
  229. request.args.get('filename', type=str), err))
  230. return {'filename': request.args.get('filename', type=str)}
  231. except Exception as err:
  232. logger.error('delete img: {} failed with {}'.format(
  233. request.args.get('filename', type=str), err))
  234. return {'filename': request.args.get('filename', type=str)}
  235. @contents_app.route('/api/upload/static/img', methods=['POST'])
  236. def upload_static_img():
  237. img_data = request.files['image']
  238. img_dir = path.join(STATIC_DIR, 'img', 'title')
  239. print("static img directory is " + img_dir) #debug use
  240. if not path.exists(img_dir): # foolproofing, just in case
  241. mkdir(img_dir)
  242. img_file_dir = path.join(img_dir, request.args.get('filename', type=str))
  243. print("static img file directory is " + img_file_dir) #debug use
  244. img_data.save(img_file_dir)
  245. return {'filename': request.args.get('filename', type=str)}
  246. @contents_app.route('/api/new_content', methods=['POST'])
  247. def gen_content():
  248. print(request.json.get('type'))
  249. print(get_trans_title_url_name(request.json.get('type')))
  250. front_matter = request.json.get('frontMatter', '---\n---')
  251. name = request.json.get('name', 'Undefind')
  252. if request.json.get('type') == "blog":
  253. dir_ = CONTENT_DIR + "/"+ "blog" + "/" + name
  254. if not path.exists(dir_):
  255. mkdir(dir_)
  256. if not path.exists(path.join(dir_, 'img')):
  257. mkdir(path.join(dir_, 'img'))
  258. with open(path.join(dir_, 'index.md'), 'w', encoding="utf-8") as md:
  259. md.write(front_matter)
  260. # print(front_matter)
  261. else:
  262. dir_ = path.join(CONTENT_DIR, request.json.get('type'), name)
  263. print(dir_)
  264. if dir_:
  265. if not path.exists(dir_):
  266. mkdir(dir_)
  267. else:
  268. return Response({}, status=201)
  269. if not path.exists(path.join(dir_, 'img')):
  270. mkdir(path.join(dir_, 'img'))
  271. with open(path.join(dir_, 'index.md'), 'w', encoding="utf-8") as md:
  272. md.write(front_matter)
  273. return {'new_content': name}
  274. @contents_app.route('/api/get_cats', methods=['POST', 'GET'])
  275. def get_cats():
  276. """ front_matter = request.json.get('frontMatter', '---\n---')
  277. name = request.json.get('name', 'Undefind')
  278. dir_ = path.join(_search_content_dir(
  279. request.json.get('type'), request.json.get('categories')), name) """
  280. #print(_search_content_dir('blog', 'home_inspection_knowledge'))
  281. return {}
  282. @contents_app.route('/api/new_cat', methods=['POST'])
  283. def gen_cat():
  284. front_matter = request.json.get('frontMatter', '---\n---')
  285. name = request.json.get('name', 'Undefind')
  286. dir_ = path.join(_search_content_dir(
  287. request.json.get('type'), request.json.get('categories')), name)
  288. #print(request.json.get('type') + ',' + request.json.get('categories'))
  289. if dir_:
  290. if not path.exists(dir_):
  291. mkdir(dir_)
  292. else:
  293. return Response({}, status=201)
  294. if not path.exists(path.join(dir_, 'img')):
  295. mkdir(path.join(dir_, 'img'))
  296. with open(path.join(dir_, 'index.md'), 'w', encoding="utf-8") as md:
  297. md.write(front_matter)
  298. return {'new_content': name}
  299. api.add_resource(Content, '/api/contents')