123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366 |
- from flask import flash, render_template, Blueprint, request, redirect, url_for
- from flask.app import Flask
- 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": "餐廳",
- "custom_made_system_cabinet": "客製模組系統櫃",
- "system_cabinet": "模組系統櫃單品",
- }
- SfType = {
- "custom_made_system_cabinet": "客製模組系統櫃",
- "system_cabinet": "模組系統櫃單品",
- }
- furniturePath = UPLOAD_PATH_MAP[0][0] + '../設計家具'
- sfurniturePath = UPLOAD_PATH_MAP[0][0] + '../模組系統櫃'
- furnitureTypes = []
- furnitureTypeFiles = []
- furnitureFiles = []
- furnitures = []
- def refreshFur(itype):
- scanpath = ""
- furnitureTypes.clear()
- furnitureTypeFiles.clear()
- furnitureFiles.clear()
- furnitures.clear()
- if itype == '單品家具':
- scanpath = furniturePath
- else:
- scanpath = sfurniturePath
- for dirname, dirnames, filenames in os.walk(scanpath):
- # 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):
- # print(irequest.url)
- myType = {}
- myPath = ""
- # print(str(irequest.url).find("system_furniture"))
- if str(irequest.url).find("system_furniture") >= 0:
- myType = SfType
- myPath = sfurniturePath
- else:
- myType = SwfType
- myPath = furniturePath
- 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 = myPath + '/' + \
- myType[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=response.json(),
- 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/new_system_furniture', methods=['GET'])
- def new_system_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('單品家具')
- 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/edit_system_furniture', methods=['GET'])
- def edit_system_furniture():
- refreshFur('模組系統櫃')
- sortedData = sorted(furnitures, key=lambda x: x['date'], reverse=True)
- sortedData = sorted(sortedData, key=lambda x: x['type'])
- return render_template('system_furniture.html',
- title='模組系統櫃',
- legend='模組系統櫃',
- furnitures=sortedData, length=len(furnitures),
- )
- @blogs_app.route('/backstage/edit_news', methods=['GET'])
- def edit_news():
- response = requests.get('{}contents?url=/news'.format(PORTAL_SERVER))
- if response.status_code == 200:
- #sortedData = sorted(response.json(), key=lambda x: x['date'], reverse=True)
- return render_template('news.html',
- title='消息與報導',
- legend='消息與報導',
- news=response.json(), length=len(response.json()), form=BlogCreateForm()
- )
- @blogs_app.route('/backstage/edit_contact_us', methods=['GET'])
- def edit_contact_us():
- response = requests.get('{}contents?url=/contact'.format(PORTAL_SERVER))
- if response.status_code == 200:
- return render_template('contact_us.html',
- title='聯絡我們',
- )
- @blogs_app.route('/backstage/edit_faq', methods=['GET'])
- def edit_faq():
- return render_template('frequently_asked_questions.html',
- title='常見問題',
- )
- @blogs_app.route('/backstage/edit_contact_us_getemail', methods=['GET'])
- def edit_contact_us_getemail():
- txt = ""
- newEmail = request.args.get('newemail', type=str)
- footerpath = UPLOAD_PATH_MAP[0][0] + \
- "../../../bhouseWeb/themes/hugo-lamp/layouts/partials/footer.html"
- with open(footerpath, encoding="utf-8") as inf:
- txt = inf.read()
- result = txt[txt.find('"mailto:')+8:txt.find('"',txt.find('"mailto:')+1)]
- #sortedData = sorted(sortedData, key=lambda x: x['type'])
- return result
- @blogs_app.route('/backstage/edit_contact_us_editemail', methods=['GET'])
- def edit_contact_us_editemail():
- txt = ""
- newEmail = request.args.get('newemail', type=str)
- footerpath = UPLOAD_PATH_MAP[0][0] + \
- "../../../bhouseWeb/themes/hugo-lamp/layouts/partials/footer.html"
- with open(footerpath, encoding="utf-8") as inf:
- txt = inf.read()
- result = re.sub(r'"mailto:(\S*)"', '"mailto:' + newEmail + '"', txt)
- with open(footerpath, 'w' , encoding="utf-8") as inf:
- inf.write(result)
- #sortedData = sorted(sortedData, key=lambda x: x['type'])
- return "修改成功" + result
- @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(),
- 'true',
- '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/news/create/', methods=['POST'])
- def createNews():
- form = BlogCreateForm()
- transtitle = get_trans_title_url_name(form.title.data)
- front_matter = '''---
- title: "{}"\n\
- date: {}\n\
- draft: {}\n\
- type: "{}"\n\
- url: "{}"\n\
- image: ""\n\
- ---'''.format(form.title.data,
- get_now_time(),
- 'true',
- 'news',
- '/news/{}'.format(transtitle))
- data = {'frontMatter': front_matter,
- 'name': transtitle,
- 'type': 'news',
- }
- return create_content(data, form.image.data)
- @blogs_app.route('/backstage/blog/remove', methods=['POST'])
- def remove():
- remove_content()
- return redirect(url_for('blogs.blog_list'))
- @blogs_app.route('/backstage/news/remove', methods=['POST'])
- def removeNews():
- remove_content()
- return redirect(url_for('blogs.edit_news'))
- @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 """
|