routes.py 12 KB

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