routes.py 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313
  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 'image: ' in line:
  54. s = line.replace('image: ', '').strip()
  55. s = s.replace('"', '').strip()
  56. result['image'] = s
  57. elif 'collection_description: ' in line:
  58. s = line.replace('collection_description: ', '').strip()
  59. s = s.replace('"', '').strip()
  60. result['collection_description'] = s
  61. elif 'description: ' in line:
  62. s = line.replace('description: ', '').strip()
  63. s = s.replace('"', '').strip()
  64. result['description'] = s
  65. data_field = list(DATA_FIELD)
  66. result = {}
  67. with open(file_dir, 'r', encoding="utf-8") as md:
  68. result['content'] = md.read()
  69. md.seek(0)
  70. md_line_data = md.readlines()
  71. for line in md_line_data:
  72. load_data()
  73. if not data_field:
  74. return result
  75. if not 'tags' in result:
  76. result['tags'] = "全部類型,全部坪數,全部預算,全部格局"
  77. else:
  78. if result['tags'] != "":
  79. result['tags'] = result['tags'] + ","
  80. result['tags'] = result['tags'].replace('"', '') + "全部類型,全部坪數,全部預算,全部格局"
  81. return result
  82. def _gen_content_files():
  83. for root, dirs, files in walk(CONTENT_DIR):
  84. for f in files:
  85. if '.md' not in f:
  86. continue
  87. yield path.join(root, f)
  88. def _search_dir(url):
  89. def _get_file_front_matter_url():
  90. with open(file_dir, 'r', encoding="utf-8") as md:
  91. md_line_data = md.readlines()
  92. for line in md_line_data:
  93. if 'url:' in line:
  94. return list(filter(None, re.split('"|\n', line)))[-1]
  95. for file_dir in _gen_content_files():
  96. if url == _get_file_front_matter_url():
  97. return path.dirname(file_dir)
  98. def _search_content_dir(type_, categories=None):
  99. target = categories or type_
  100. def _get_file_front_matter_type():
  101. with open(file_dir, 'r', encoding="utf-8") as md:
  102. md_line_data = md.readlines()
  103. for line in md_line_data:
  104. if categories:
  105. if 'categories' in line:
  106. return list(filter(None, re.split('"|\n|]', line)))[-1]
  107. else:
  108. if 'type:' in line:
  109. return list(filter(None, re.split('"|\n', line)))[-1]
  110. for file_dir in _gen_content_files():
  111. if target == _get_file_front_matter_type():
  112. return path.dirname(file_dir)
  113. class Content(Resource):
  114. DATA_FIELD = ['title:', 'url:']
  115. @property
  116. def url(self):
  117. return request.args.get('url', type=str)
  118. def _search_content(self):
  119. result = {}
  120. for file_dir in _gen_content_files():
  121. data = _get_data(file_dir)
  122. if self.url in data.get('url', ''):
  123. result = data
  124. result['path'] = file_dir
  125. #print(result['path'])
  126. yield result
  127. def _get_contents(self):
  128. for file_dir in _gen_content_files():
  129. yield _get_data(file_dir)
  130. def get(self):
  131. if self.url:
  132. results = self._search_content()
  133. else:
  134. results = self._get_contents()
  135. x = list(results)
  136. #sortedData = sorted(list(results()), key=lambda x:x['date'], reverse=True)
  137. return x
  138. def post(self):
  139. try:
  140. requrl = request.args.get('url', type=str)
  141. print(requrl)
  142. if "frequently_asked_questions" in requrl:
  143. file_dir = path.join(_search_dir(requrl), '_index.md')
  144. else:
  145. file_dir = path.join(_search_dir(requrl), 'index.md')
  146. md_content = request.json.get('content')
  147. with open(file_dir, 'w', encoding="utf-8") as md:
  148. md.write(md_content)
  149. return md_content
  150. except TypeError as err:
  151. logger.error(
  152. 'Content post failed with file_dir param contain None. error: {}'.format(err))
  153. except OSError as err:
  154. logger.error(
  155. 'Content post failed with: {} is not exist{}'.format(file_dir, err))
  156. except AttributeError as err:
  157. logger.error('Content post failed with AttributeError: {}'.format(err))
  158. except Exception as err:
  159. logger.error('Content post failed with: {}'.format(err))
  160. def delete(self):
  161. content_data = list(self._search_content())
  162. file_dir = content_data[0].get('path')
  163. if path.exists(file_dir):
  164. # remove(file_dir)
  165. shutil.rmtree(file_dir[0:file_dir.replace('\\', '/').rfind('/')+1])
  166. # print(file_dir[0:file_dir.replace('\\','/').rfind('/')+1])
  167. logger.info('delete dir: {}'.format(
  168. file_dir[0:file_dir.replace('\\', '/').rfind('/')+1]))
  169. else:
  170. logger.warning('delete fail with {} not exist'.format(file_dir))
  171. @contents_app.route('/api/upload/img', methods=['POST'])
  172. def upload_img():
  173. img_data = request.files['image']
  174. file_dir = _search_dir(request.args.get('url', type=str))
  175. #print("file_dir 1 is " + file_dir)
  176. img_dir = path.join(file_dir, 'img/{}'.format(img_data.filename))
  177. print("img_dir 1 is " + img_dir)
  178. img_data.save(img_dir)
  179. return {'filename': img_data.filename}
  180. @contents_app.route('/api/upload/img_to_dir', methods=['POST'])
  181. def upload_img_to_dir():
  182. img_data = request.files['image']
  183. file_dir = _search_dir(request.args.get('url', type=str))
  184. #print("file_dir 2 is " + file_dir)
  185. img_dir = path.join(file_dir, 'img/{}'.format(request.args.get('filename', type=str)))
  186. print("img_dir 2 is " + img_dir)
  187. img_data.save(img_dir)
  188. return {'filename': img_data.filename}
  189. @contents_app.route('/api/delete/img', methods=['DELETE'])
  190. def delete_img():
  191. try:
  192. file_dir = _search_dir(request.args.get('url', type=str))
  193. img_dir = path.join(file_dir, 'img/{}'.format(request.args.get('filename', type=str)))
  194. remove(img_dir)
  195. logger.info('delete img: {}'.format(img_dir))
  196. return {'filename': request.args.get('filename', type=str)}
  197. except TypeError as err:
  198. logger.error('delete img: {} failed with file_dir is None. error: {}'.format(
  199. request.args.get('filename', type=str), err))
  200. return {'filename': request.args.get('filename', type=str)}
  201. except OSError as err:
  202. logger.error('delete img: {} failed with img_dir is not exist. error: {}'.format(
  203. request.args.get('filename', type=str), err))
  204. return {'filename': request.args.get('filename', type=str)}
  205. except Exception as err:
  206. logger.error('delete img: {} failed with {}'.format(
  207. request.args.get('filename', type=str), err))
  208. return {'filename': request.args.get('filename', type=str)}
  209. @contents_app.route('/api/upload/static/img', methods=['POST'])
  210. def upload_static_img():
  211. img_data = request.files['image']
  212. img_dir = path.join(STATIC_DIR, 'img', 'title')
  213. print("static img directory is " + img_dir) #debug use
  214. if not path.exists(img_dir): # foolproofing, just in case
  215. mkdir(img_dir)
  216. img_file_dir = path.join(img_dir, request.args.get('filename', type=str))
  217. print("static img file directory is " + img_file_dir) #debug use
  218. img_data.save(img_file_dir)
  219. return {'filename': request.args.get('filename', type=str)}
  220. @contents_app.route('/api/new_content', methods=['POST'])
  221. def gen_content():
  222. print(request.json.get('type'))
  223. print(get_trans_title_url_name(request.json.get('type')))
  224. front_matter = request.json.get('frontMatter', '---\n---')
  225. name = request.json.get('name', 'Undefind')
  226. if request.json.get('type') == "blog":
  227. dir_ = CONTENT_DIR + "/"+ "blog" + "/" + name
  228. if not path.exists(dir_):
  229. mkdir(dir_)
  230. if not path.exists(path.join(dir_, 'img')):
  231. mkdir(path.join(dir_, 'img'))
  232. with open(path.join(dir_, 'index.md'), 'w', encoding="utf-8") as md:
  233. md.write(front_matter)
  234. # print(front_matter)
  235. else:
  236. dir_ = path.join(CONTENT_DIR, request.json.get('type'), name)
  237. print(dir_)
  238. if dir_:
  239. if not path.exists(dir_):
  240. mkdir(dir_)
  241. else:
  242. return Response({}, status=201)
  243. if not path.exists(path.join(dir_, 'img')):
  244. mkdir(path.join(dir_, 'img'))
  245. with open(path.join(dir_, 'index.md'), 'w', encoding="utf-8") as md:
  246. md.write(front_matter)
  247. return {'new_content': name}
  248. @contents_app.route('/api/get_cats', methods=['POST', 'GET'])
  249. def get_cats():
  250. """ front_matter = request.json.get('frontMatter', '---\n---')
  251. name = request.json.get('name', 'Undefind')
  252. dir_ = path.join(_search_content_dir(
  253. request.json.get('type'), request.json.get('categories')), name) """
  254. #print(_search_content_dir('blog', 'home_inspection_knowledge'))
  255. return {}
  256. @contents_app.route('/api/new_cat', methods=['POST'])
  257. def gen_cat():
  258. front_matter = request.json.get('frontMatter', '---\n---')
  259. name = request.json.get('name', 'Undefind')
  260. dir_ = path.join(_search_content_dir(
  261. request.json.get('type'), request.json.get('categories')), name)
  262. #print(request.json.get('type') + ',' + request.json.get('categories'))
  263. if dir_:
  264. if not path.exists(dir_):
  265. mkdir(dir_)
  266. else:
  267. return Response({}, status=201)
  268. if not path.exists(path.join(dir_, 'img')):
  269. mkdir(path.join(dir_, 'img'))
  270. with open(path.join(dir_, 'index.md'), 'w', encoding="utf-8") as md:
  271. md.write(front_matter)
  272. return {'new_content': name}
  273. api.add_resource(Content, '/api/contents')