routes.py 11 KB

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