from flask import flash, render_template, Blueprint, request, redirect, url_for from flask.wrappers import Response import requests import os import fnmatch import re import markdown import uuid from backstage.blogs.forms import BlogCreateForm from backstage.utils import get_now_time, translate from backstage.utils.routes import create_content, remove_content, get_trans_title_url_name from backstage.config import PORTAL_SERVER, UPLOAD_PATH_MAP blogs_app = Blueprint('blogs', __name__) SwfType = { "other_furniture": "其他", "master_bedroom": "臥室", "living_room": "客廳", "study_room": "書房", "dining_room": "餐廳", } furniturePath = UPLOAD_PATH_MAP[0][0] + '../設計家具' furnitureTypes = [] furnitureTypeFiles = [] furnitureFiles = [] furnitures = [] def refreshFur(): furnitureTypes.clear() furnitureTypeFiles.clear() furnitureFiles.clear() furnitures.clear() for dirname, dirnames, filenames in os.walk(furniturePath): # print path to all subdirectories first. for subdirname in dirnames: if subdirname.find('.') == -1: furnitureTypes.append(subdirname) # print path to all filenames. for filename in filenames: if filename.find('_index.md') >= 0: furnitureTypeFiles.append(os.path.join(dirname, filename)) if filename.find('index.md') >= 0: furnitureFiles.append(os.path.join(dirname, filename)) headerStart = False for files in furnitureFiles: tmpfurniture = {} with open(files, 'r', encoding="utf-8") as md: md_line_data = md.readlines() # print(md_line_data) for line in md_line_data: # print(line) if '---' in line: headerStart = not headerStart continue if headerStart: if 'title:' in line: tmpfurniture['title'] = re.split('"|\n', line)[1] if 'date:' in line: tmpfurniture['date'] = re.split(':"|\n', line)[0][6:] if 'draft:' in line: tmpfurniture['draft'] = re.split(':"|\n', line)[0][7:] if 'type:' in line: tmpfurniture['type'] = re.split('"|\n', line)[1] if 'url:' in line: tmpfurniture['url'] = re.split('"|\n', line)[1] if 'image:' in line: tmpfurniture['image'] = re.split('"|\n', line)[1] if 'tags:' in line: tmpfurniture['tags'] = re.split('"|\n', line)[1] # 避免加入類別項目 if tmpfurniture['type'] != tmpfurniture['url'][1:]: furnitures.append(tmpfurniture) def newFur(irequest): ename = get_trans_title_url_name(irequest.args['newSwfName']) front_matter = '''--- title: "{}" date: {} draft: true type: "{}" url: "/{}/{}" image: "" ---'''.format(irequest.args['newSwfName'], get_now_time(), irequest.args['newSwfDropdown'], irequest.args['newSwfDropdown'], ename) newPath = furniturePath + '/' + \ SwfType[irequest.args['newSwfDropdown']] + '/' + ename if not os.path.exists(newPath): os.mkdir(newPath) with open(os.path.join(newPath, 'index.md'), 'w', encoding="utf-8") as md: md.write(front_matter) # furniturePath # get_trans_title_url_name() return furniturePath @blogs_app.route('/backstage/blogs', methods=['GET']) def blog_list(): response = requests.get('{}contents?url=/blog'.format(PORTAL_SERVER)) if response.status_code == 200: sortedData = sorted(response.json(), key=lambda x: x['date'], reverse=True) #print(sortedData) return render_template('blogs.html', title='設計專欄', legend='設計專欄列表', blogs=sortedData, length=len(response.json()), form=BlogCreateForm()) @blogs_app.route('/backstage/new_solid_wood_furniture', methods=['GET']) def new_solid_wood_furniture(): # edit_solid_wood_furniture() return newFur(request) @blogs_app.route('/backstage/del_solid_wood_furniture', methods=['GET']) def del_solid_wood_furniture(): url = request.args.get('url', type=str) response = requests.delete('{}contents?url={}'.format(PORTAL_SERVER, url)) if response.status_code == 200: flash('刪除文章成功', 'success') else: flash('刪除文章失敗', 'danger') # edit_solid_wood_furniture() return url @blogs_app.route('/backstage/edit_solid_wood_furniture', methods=['GET']) def edit_solid_wood_furniture(): refreshFur() """ furniturePath = UPLOAD_PATH_MAP[0][0] + '../設計家具' furnitureTypes = [] furnitureTypeFiles = [] furnitureFiles = [] furnitures = [] for dirname, dirnames, filenames in os.walk(furniturePath): # print path to all subdirectories first. for subdirname in dirnames: if subdirname.find('.') == -1: furnitureTypes.append(subdirname) # print path to all filenames. for filename in filenames: if filename.find('_index.md') >= 0: furnitureTypeFiles.append(os.path.join(dirname, filename)) if filename.find('index.md') >= 0: furnitureFiles.append(os.path.join(dirname, filename)) headerStart = False for files in furnitureFiles: tmpfurniture = {} with open(files, 'r', encoding="utf-8") as md: md_line_data = md.readlines() # print(md_line_data) for line in md_line_data: # print(line) if '---' in line: headerStart = not headerStart continue if headerStart: if 'title:' in line: tmpfurniture['title'] = re.split('"|\n', line)[1] if 'date:' in line: tmpfurniture['date'] = re.split(':"|\n', line)[0].removeprefix('date: ') if 'draft:' in line: tmpfurniture['draft'] = re.split(':"|\n', line)[0].removeprefix('draft: ') if 'type:' in line: tmpfurniture['type'] = re.split('"|\n', line)[1] if 'url:' in line: tmpfurniture['url'] = re.split('"|\n', line)[1] if 'image:' in line: tmpfurniture['image'] = re.split('"|\n', line)[1] if 'tags:' in line: tmpfurniture['tags'] = re.split('"|\n', line)[1] #避免加入類別項目 if tmpfurniture['type'] != tmpfurniture['url'].removeprefix('/'): furnitures.append(tmpfurniture) """ #sortedData = sorted(furnitures, key=lambda x: x['date'], reverse=True) # print(furnitures) """ response = requests.get('{}contents?url=/blog'.format(PORTAL_SERVER)) if response.status_code == 200: """ sortedData = sorted(furnitures, key=lambda x: x['date'], reverse=True) sortedData = sorted(sortedData, key=lambda x: x['type']) return render_template('solid_wood_furniture.html', title='單品家具', legend='單品家具', furnitures=sortedData, length=len(furnitures), ) @blogs_app.route('/backstage/blog/create/', methods=['POST']) def create(): transcat = "" form = BlogCreateForm() if form.categories.data == "居家美學": transcat = "home_aesthetics" elif form.categories.data == "規劃師QA": transcat = "room_planner_expertise" elif form.categories.data == "驗屋知識": transcat = "home_inspection_knowledge" else: transcat = get_trans_title_url_name(form.categories.data) transtitle = get_trans_title_url_name(form.title.data) front_matter = '''--- title: "{}"\n\ date: {}\n\ draft: {}\n\ type: "{}"\n\ url: "{}"\n\ image: "/img/blog/{}"\n\ categories: ["{}"]\n\ col1: "{}"\n\ col2: "{}"\n\ ---'''.format(form.title.data, get_now_time(), 'false', 'blog', '/blog/{}'.format(transtitle), form.image.data.filename, form.categories.data, transcat, "") data = {'frontMatter': front_matter, 'name': transtitle, 'type': 'blog', 'categories': form.categories.data, # 'caturl': caturl } return create_content(data, form.image.data) @blogs_app.route('/backstage/blog/createCat/', methods=['GET']) def createCat(): #title = "" front_matter = '''--- title: "{}"\n\ date: {}\n\ draft: {}\n\ type: "{}"\n\ categories: ["{}"]\n\ ---'''.format(request.args["title"], get_now_time(), 'false', 'blog', get_trans_title_url_name(request.args["title"])) CatPath = UPLOAD_PATH_MAP[0][0]+"../blog/" + get_trans_title_url_name(request.args["title"]) # print(CatPath) if not os.path.exists(CatPath): os.mkdir(CatPath) with open(os.path.join(CatPath, 'category.md'), 'w', encoding="utf-8") as md: md.write(front_matter) print("11") return Response("你好", 200) @blogs_app.route('/backstage/blog/remove', methods=['POST']) def remove(): remove_content() return redirect(url_for('blogs.blog_list')) @blogs_app.route('/backstage/utils', methods=['GET']) def transService(): # print(request.args["trantext"]) return get_trans_title_url_name(request.args["trantext"]) """ def GetCategories(): GetCategories configfiles = [os.path.join(dirpath, f) for dirpath, dirnames, files in os.walk(UPLOAD_PATH_MAP+'../blog') for f in fnmatch.filter(files, 'category.md')] return configfiles """