Ver Fonte

210917 家具單品新增/編輯/刪除

yukyo0821 há 3 anos atrás
pai
commit
83ae1e17ff

+ 179 - 5
backstage/blogs/routes.py

@@ -1,8 +1,11 @@
-from flask import render_template, Blueprint, request, redirect, url_for
+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
@@ -11,12 +14,101 @@ 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].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)
+
+
+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='設計專欄列表',
@@ -25,6 +117,88 @@ def blog_list():
                                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 = ""
@@ -56,12 +230,12 @@ col2: "{}"\n\
               '/blog/{}'.format(transtitle),
               form.image.data.filename,
               form.categories.data,
-              transcat,"")
+              transcat, "")
     data = {'frontMatter': front_matter,
             'name': transtitle,
             'type': 'blog',
             'categories': form.categories.data,
-            #'caturl': caturl
+            # 'caturl': caturl
             }
 
     return create_content(data, form.image.data)
@@ -84,7 +258,7 @@ categories: ["{}"]\n\
 
     CatPath = UPLOAD_PATH_MAP[0][0]+"../blog/" + get_trans_title_url_name(request.args["title"])
 
-    print(CatPath)
+    # 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:
@@ -102,7 +276,7 @@ def remove():
 
 @blogs_app.route('/backstage/utils', methods=['GET'])
 def transService():
-    #print(request.args["trantext"])
+    # print(request.args["trantext"])
     return get_trans_title_url_name(request.args["trantext"])
 
 

+ 462 - 0
backstage/static/js/yo.js

@@ -1,3 +1,126 @@
+SwfType = {
+    "other_furniture": "其他",
+    "master_bedroom": "臥室",
+    "living_room": "客廳",
+    "study_room": "書房",
+    "dining_room": "餐廳",
+};
+
+//document.ready
+$(function () {
+
+    $("#dialog-form").hide();
+    editor = new EditorJS({
+        readOnly: false,
+        holder: 'editorjs',
+    });
+    editor1 = new EditorJS({
+        readOnly: false,
+        holder: 'editorjs1',
+    });
+
+});
+
+frontMatters = [];
+contentMatters = [];
+
+function getHeader(url) {
+    axios.get(contentApiUrl + url).then(({ data }) => {
+        frontMatters = [];
+        contentMatters = [];
+        editTarget = url;
+        mdType = url.split('/')[1];
+        aa = data[0]['content'];
+        const content = _.get(data, '0.content', '');
+        blocks = parseMd(aa);
+        oTitle = $("#ctitle").val();
+        // $("#dialog-form").dialog();
+        if ($("#ctype").val() == "collection") {
+            $("#scat").hide();
+        }
+        else if ($("#ctype").val() == "blog") {
+            $("#sdesc").hide();
+        }
+        else {
+            ParseProductSection(contentMatters.join(''));
+        }
+        $("#myModal").modal();
+
+        //console.log(frontMatters);
+        //alert($('#cimage').val());
+    });
+}
+
+function toggleDraft(obj, url) {
+    axios.get(contentApiUrl + url).then(({ data }) => {
+        frontMatters = [];
+        contentMatters = [];
+        aa = data[0]['content'];
+        const content = _.get(data, '0.content', '');
+        blocks = parseMd(aa);
+        editTarget = url;
+        $('#cdraft').removeAttr('checked');
+        $('#cdraft').prop('checked', obj.checked);
+        updateHeader();
+        oTitle = "";
+    });
+}
+
+function updateHeader() {
+    /* if (oTitle != $('#ctitle').val() && $('#ctitle').val() != "" && oTitle != "") {
+      axios.get('/backstage/modTitle/' + oTitle + '/' + $('#ctitle').val()).then(({ data }) => {
+        if (data.success == "0") {
+          alert('已有重複的標題,請重新設定');
+          return;
+        }
+        else {
+          writeMd();
+        }
+      });
+    }
+    else {
+      writeMd();
+    } */
+    $("#uptbtn").attr('disabled', true);
+    writeMd();
+    // location.reload();
+}
+
+function writeMd() {
+
+    axios.get('/backstage/utils?trantext=' + $('#ccategories').val()).then(({ data }) => { $('#ccol1').val(data); })
+        .finally(() => {
+            mdContent = GetMdHeader();
+            mdContent += contentMatters.join("\n");
+            var formData = new FormData();
+            var imagefile = document.querySelector('#cfile');
+            if (imagefile != null)
+                formData.append("image", imagefile.files[0]);
+            axios.post('/backstage/upload/title', formData, {
+                headers: {
+                    'Content-Type': 'multipart/form-data'
+                }
+            }).then(({ data }) => {
+                $('#cfile').val("");
+                if (data.success == "1") {
+                    mdContent = mdContent.replace($('#cimage').val(), '/img/collection/' + data.file.url.substring(data.file.url.lastIndexOf('/') + 1));
+                    //alert(data.file.url.substring(data.file.url.lastIndexOf('/')+1));
+                }
+
+                postData = {
+                    content: mdContent,
+                    url: editTarget
+                };
+                //console.log(mdContent);
+                axios.post(contentApiUrl + editTarget, json = postData).then(({ data }) => {
+                });
+            }).finally(() => {
+                alert('資料已更新'); // test
+                location.reload();
+            });
+        });
+}
+
 function parseMd(content) {
     //var frontMatters = [];
     var blockCount;
@@ -229,6 +352,345 @@ function tableArrayToHtml(tableArray) {
     return tbl.outerHTML.toString();
 }
 
+function GenSwfDD(obj) {
+    Object.entries(SwfType).forEach(([key, value]) => {
+        op = document.createElement('option');
+        op.value = key;
+        op.text = value;
+        obj.appendChild(op);
+    });
+
+}
+
+function ReplaceSwfType(inContent) {
+    Object.entries(SwfType).forEach(([key, value]) => {
+        inContent = inContent.replaceAll('[' + key + ']', '[' + value + ']');
+    });
+    return inContent;
+}
+
+var editor;
+var editor1;
+editorBlocks = [];
+editorBlocks1 = [];
+function ParseProductSection(inContent) {
+    editorBlocks = [];
+    editorBlocks1 = [];
+
+    var aa = $.parseHTML(inContent.trim());
+    //處理圖片
+    if ($("[id='carousel-with-preview']", aa).length > 0) {
+        imgnodes = $("[id='carousel-with-preview']", aa)[0].childNodes;
+        for (i = 0; i < imgnodes.length; i++) {
+            var tmpsrc, tmpw, tmph, ampimg;
+            if (imgnodes[i].nodeName == "AMP-IMG") {
+                //alert(imgnodes[i].nodeName);
+                ampimg = imgnodes[i].outerHTML;
+                tmpsrc = ampimg.substr(ampimg.indexOf("src=\"") + 5, ampimg.indexOf("\"", ampimg.indexOf("src=\"") + 5) - ampimg.indexOf("src=\"") - 5);
+                //alert(tmpsrc);
+                tmpw = ampimg.substr(ampimg.indexOf("width=\"") + 7, ampimg.indexOf("\"", ampimg.indexOf("width=\"") + 7) - ampimg.indexOf("width=\"") - 7);
+                tmph = ampimg.substr(ampimg.indexOf("height=\"") + 8, ampimg.indexOf("\"", ampimg.indexOf("height=\"") + 8) - ampimg.indexOf("height=\"") - 8);
+                //tmph = ampimg.substr(ampimg.indexOf("width=\"") + 7, ampimg.indexOf("\"", ampimg.indexOf("width=\"") + 7) - ampimg.indexOf("width=\"") - 7);
+                editorBlocks.push({
+                    type: "image", data: {
+                        file: {
+                            url: BHOUSE_SERVER + editTarget + '/' + tmpsrc,
+                            width: parseInt(tmpw),
+                            height: parseInt(tmph),
+                        },
+                        caption: "小寶優居 | " + $('#ctitle').val(),
+                        stretched: false,
+                        withBorder: true,
+                        withBackground: false,
+                    }
+                });
+            }
+        }
+    }
+    else {
+        editorBlocks.push({
+            type: "image", data: {
+                file: {
+                    url: 'https://bhouse.com.tw/img/logo2.png',
+                    width: 300,
+                    height: 300,
+                },
+                caption: "小寶優居 | ",
+                stretched: false,
+                withBorder: true,
+                withBackground: false,
+            }
+        });
+    }
+    //editor.api.blocks.render(editorBlocks);
+    $('#editorjs')[0].innerHTML = "";
+    editor = new EditorJS({
+        readOnly: false,
+        holder: 'editorjs',
+        tools: {
+            paragraph: { inlineToolbar: false },
+            image: {
+                class: ImageTool,
+                config: {
+                    endpoints: {
+                        byFile: '/backstage/upload' + $('#curl').val(),
+                        byUrl: '/backstage/getimage' + $('#curl').val(),
+                    }
+                }
+            }
+        }
+        , data: { blocks: editorBlocks }
+        ,
+        onReady: function () {
+            //alert(editor.blocks.getBlocksCount());
+            //saveButton.click();
+        },
+        onChange: function (api, block) {
+            //$('#cimage')[0].val();
+            //console.log('something changed', block);
+        }
+    });
+
+    //類別
+    Object.entries(SwfType).forEach(([key, value]) => {
+        if ($("#ctype").val() == key) {
+            //alert($("#ctype").val());
+            $("#swfDropdown").val($("#ctype").val());
+        }
+    });
+
+    //敘述
+    if ($("[class='description']", aa).length > 0) {
+        $("#swfDesc").val($(".description", aa)[0].innerHTML.trim().replaceAll('<b>', '').replaceAll('</b>', ''));
+    }
+    //alert(editorBlocks);
+    //其他
+    if ($("[class='detail']", aa).length > 0) {
+        onodes = $("[class='detail']", aa)[0].childNodes;
+        for (i = 0; i < onodes.length; i++) {
+            if (onodes[i].nodeName != "#text") {
+                if (onodes[i].innerHTML.trim().indexOf("定價 : ") >= 0)
+                    $("#swfPrice").val(onodes[i].innerHTML.replace("定價 : ", "").trim());
+                if (onodes[i].innerHTML.trim().indexOf("顏色 : ") >= 0)
+                    $("#swfColor").val(onodes[i].innerHTML.replace("顏色 : ", "").trim());
+                if (onodes[i].innerHTML.trim().indexOf("尺寸(mm) : ") >= 0)
+                    $("#swfSize").val(onodes[i].innerHTML.replace("尺寸(mm) : ", "").trim());
+                if (onodes[i].innerHTML.trim().indexOf("材質 : ") >= 0)
+                    $("#swfMat").val(onodes[i].innerHTML.replace("材質 : ", "").trim());
+                if (onodes[i].innerHTML.trim().indexOf("備註 : ") >= 0)
+                    $("#swfMemo").val(onodes[i].innerHTML.replace("備註 : ", "").trim());
+                //alert(nodes[i].innerHTML);
+            }
+        }
+    }
+
+    //處理規格圖片
+    if ($("[class='spec']", aa).length > 0) {
+        snodes = $("[class='spec']", aa)[0].childNodes;
+        //alert(snodes[0].innerHTML);
+        for (i = 0; i < snodes.length; i++) {
+            var tmpsrc, tmpw, tmph, ampimg;
+            if (snodes[i].nodeName == "AMP-IMG") {
+                ampimg = snodes[i].outerHTML;
+                tmpsrc = ampimg.substr(ampimg.indexOf("src=\"") + 5, ampimg.indexOf("\"", ampimg.indexOf("src=\"") + 5) - ampimg.indexOf("src=\"") - 5);
+                tmpw = ampimg.substr(ampimg.indexOf("width=\"") + 7, ampimg.indexOf("\"", ampimg.indexOf("width=\"") + 7) - ampimg.indexOf("width=\"") - 7);
+                tmph = ampimg.substr(ampimg.indexOf("height=\"") + 8, ampimg.indexOf("\"", ampimg.indexOf("height=\"") + 8) - ampimg.indexOf("height=\"") - 8);
+                //tmph = ampimg.substr(ampimg.indexOf("width=\"") + 7, ampimg.indexOf("\"", ampimg.indexOf("width=\"") + 7) - ampimg.indexOf("width=\"") - 7);
+                editorBlocks1.push({
+                    type: "image", data: {
+                        file: {
+                            url: BHOUSE_SERVER + editTarget + '/' + tmpsrc,
+                            width: parseInt(tmpw),
+                            height: parseInt(tmph),
+                        },
+                        caption: "小寶優居 | " + $('#ctitle').val(),
+                        stretched: false,
+                        withBorder: true,
+                        withBackground: false,
+                    }
+                });
+            }
+        }
+    }
+    else {
+        editorBlocks1.push({
+            type: "image", data: {
+                file: {
+                    url: 'https://bhouse.com.tw/img/logo2.png',
+                    width: 300,
+                    height: 300,
+                },
+                caption: "小寶優居 | ",
+                stretched: false,
+                withBorder: true,
+                withBackground: false,
+            }
+        });
+    }
+    $('#editorjs1')[0].innerHTML = "";
+    editor1 = new EditorJS({
+        readOnly: false,
+        holder: 'editorjs1',
+        tools: {
+            paragraph: { inlineToolbar: false },
+            image: {
+                class: ImageTool,
+                config: {
+                    endpoints: {
+                        byFile: '/backstage/upload' + $('#curl').val(),
+                        byUrl: '/backstage/getimage' + $('#curl').val(),
+                    }
+                }
+            }
+        }
+        , data: { blocks: editorBlocks1 }
+        ,
+        onReady: function () {
+            //saveButton.click();
+        },
+        onChange: function (api, block) {
+            //console.log('something changed', block);
+        }
+    });
+}
+
+function GenProductSection(mimg, specimg) {
+
+    section = document.createElement('section')
+    tmpstr = `<section class="section44 mb-5">
+    <div class="container">
+      <div class="mb-5">
+        <a href="/solid_wood_furniture">關於設計家具</a> > <a href="/##ctype##">##ctypec##</a> > <a href="##curl##">##ctitle##</a>
+      </div>
+      <div class="row">
+        <div class="col-md-5 col-sm-12">
+          <div class="block">
+            <div class="section-title text-center">
+              <amp-carousel
+                id="carousel-with-preview"
+                width="300"
+                height="300"
+                layout="responsive"
+                type="slides"
+                autoplay
+                delay="2500"
+                role="region"
+                aria-label="小寶優居 | ##ctitle##"
+              >
+                ##AMP-IMG##
+              </amp-carousel>
+              <div class="mt-3 carousel-preview">
+                ##PREV-IMG##
+              </div>
+            </div>
+          </div>
+        </div>
+        <div class="col-md-7 col-sm-12">
+          <div class="block ms-md-5 mb-5">
+            <div class="title mb-4"><b>##ctitle##</b></div>
+            <div class="description">
+              <b>##swfDesc##</b>
+            </div>
+            <hr>
+            <div class="detail">
+                    ##swfPrice##
+                    ##swfColor##
+                    ##swfSize##
+                    ##swfMat##
+                    ##swfMemo##
+            </div>
+          </div>
+        </div>
+      </div>
+      <div class="card">
+        <div class="card-body text-center">
+          <div class="mb-2">1.商品顏色因拍攝、螢幕差異略有不同,實際顏色請依照門市實際顏色為主</div>
+          <div>2.部分商品因應空間大小,保有客製尺寸服務,詳細客製尺寸,請預約門市諮詢訂購</div>
+        </div>
+      </div>
+      <div class="spec">
+        <div class="mb-4"><b>尺寸規格</b></div>
+        ##SPEC-IMG##
+      </div>
+    </div>
+  </section>`;
+
+    tmpstr = tmpstr.replaceAll('##ctitle##', $("#ctitle").val());
+    tmpstr = tmpstr.replaceAll('##ctype##', $("#ctype").val());
+    tmpstr = tmpstr.replaceAll('##curl##', $("#curl").val());
+    Object.entries(SwfType).forEach(([key, value]) => {
+        if ($("#ctype").val() == key)
+            tmpstr = tmpstr.replaceAll('##ctypec##', value);
+    });
+    tmpstr = tmpstr.replaceAll('##swfDesc##', $("#swfDesc").val());
+    if ($("#swfPrice").val() != "")
+        tmpstr = tmpstr.replaceAll('##swfPrice##', "<div>定價 : " + $("#swfPrice").val() + "</div>");
+    if ($("#swfColor").val() != "")
+        tmpstr = tmpstr.replaceAll('##swfColor##', "<div>顏色 : " + $("#swfColor").val() + "</div>");
+    if ($("#swfSize").val() != "")
+        tmpstr = tmpstr.replaceAll('##swfSize##', "<div>尺寸(mm) : " + $("#swfSize").val() + "</div>");
+    if ($("#swfMat").val() != "")
+        tmpstr = tmpstr.replaceAll('##swfMat##', "<div>材質 : " + $("#swfMat").val() + "</div>");
+    if ($("#swfMemo").val() != "")
+        tmpstr = tmpstr.replaceAll('##swfMemo##', "<div>備註 : " + $("#swfMemo").val() + "</div>");
+
+    mimgstr = "";
+    firstimg = true;
+    for (i = 0; i < mimg.blocks.length; i++) {
+        //alert(block.type);
+        block = mimg.blocks[i];
+        if (block.type == "image") {
+            iurl = block.data.file.url.split('/');
+            if (firstimg) {
+                $("#cimage").val($("#curl").val() + '/' + iurl[iurl.length - 1]);
+                firstimg = false;
+            }
+            mimgstr += '<amp-img\n  alt="' + block.data.caption
+                + '"\n  src="' + iurl[iurl.length - 1]
+                + '"\n  height="' + block.data.file.height
+                + '"\n  width="' + block.data.file.width
+                + '"\n  layout="responsive">\n</amp-img>';
+        }
+    }
+    tmpstr = tmpstr.replaceAll('##AMP-IMG##', mimgstr);
+
+    previmgstr = "";
+    for (i = 0; i < mimg.blocks.length; i++) {
+        //alert(block.type);
+        block = mimg.blocks[i];
+        if (block.type == "image") {
+            iurl = block.data.file.url.split('/');
+            previmgstr += (previmgstr == "" ? "" : '\n') + `<button on="tap:carousel-with-preview.goToSlide(index=` + i + `)">
+            <amp-img
+              src="`+ iurl[iurl.length - 1] + `"
+              width="40"
+              height="40"
+              alt="`+ block.data.caption + `"
+            ></amp-img>
+          </button>`;
+        }
+    }
+    tmpstr = tmpstr.replaceAll('##PREV-IMG##', previmgstr);
+
+    specimgstr = "";
+    for (i = 0; i < specimg.blocks.length; i++) {
+        //alert(block.type);
+        block = specimg.blocks[i];
+        if (block.type == "image") {
+            iurl = block.data.file.url.split('/');
+            specimgstr += '<amp-img\n  alt="' + block.data.caption
+                + '"\n  src="' + iurl[iurl.length - 1]
+                + '"\n  height="' + block.data.file.height
+                + '"\n  width="' + block.data.file.width
+                + '"\n  layout="responsive">\n</amp-img>';
+        }
+    }
+    tmpstr = tmpstr.replaceAll('##SPEC-IMG##', specimgstr);
+
+    return tmpstr;
+
+}
+
 class MDParser {
 
     constructor(MDtext) {

+ 1 - 0
backstage/templates/blogs.html

@@ -1,5 +1,6 @@
 {% extends "tables/editor_table.html" %}
 {% block table_body %}
+<script type="text/javascript" src="/static/js/yo.js"></script>
 {% for idx in range(0, length) %}
 {% if blogs[idx].url != '/blogs' %}
 <tbody>

+ 42 - 34
backstage/templates/collections.html

@@ -1,45 +1,53 @@
 {% extends "tables/editor_table.html" %}
 {% block table_body %}
+<script type="text/javascript" src="/static/js/yo.js"></script>
 {% for idx in range(0, length) %}
-  {% if collections[idx].url != '/collection' %}
-    <tbody>
-      <tr>
-        <td class="table__data">{{ idx + 1 }}</td>
-        <td class="table__data">{{ collections[idx].title }}</td>
-        <td class="table__data">{{ collections[idx].date }}</td>
-        <!-- <td class="table__data">1</td> -->
-        <td class="table__data"><input type="checkbox" {{ 'checked' if (collections[idx].draft.lower()=='false') }} onclick="toggleDraft(this,'{{ collections[idx].url }}');" /></td>
-        <td>
-          <div class="d-flex justify-content-center">
-            <button class="btn btn_light mr-1" onclick="getHeader('{{ collections[idx].url }}');" ><b>主資訊</b> <i class="fas fa-pencil-alt"></i></button>
-            <a class="m-1 btn__edit" href="{{ url_for('editor.editor', url=collections[idx].url) }}"><i class="fas fa-edit"></i></a>
-            <form action="{{ url_for('collections.remove', url=collections[idx].url) }}" method="POST" method="POST" class="m-1 inline_block">
-              <button class="btn__delete" type="submit" value="delete" onclick=" return confirm('確定要刪除此作品?');"><i class="fas fa-trash-alt"></i></button>
-            </form>
-          </div>
-        </td>
-      </tr>
-    </tbody>
-  {% endif %}
+{% if collections[idx].url != '/collection' %}
+<tbody>
+  <tr>
+    <td class="table__data">{{ idx + 1 }}</td>
+    <td class="table__data">{{ collections[idx].title }}</td>
+    <td class="table__data">{{ collections[idx].date }}</td>
+    <!-- <td class="table__data">1</td> -->
+    <td class="table__data"><input type="checkbox" {{ 'checked' if (collections[idx].draft.lower()=='false' ) }}
+        onclick="toggleDraft(this,'{{ collections[idx].url }}');" /></td>
+    <td>
+      <div class="d-flex justify-content-center">
+        <button class="btn btn_light mr-1" onclick="getHeader('{{ collections[idx].url }}');"><b>主資訊</b> <i
+            class="fas fa-pencil-alt"></i></button>
+        <a class="m-1 btn__edit" href="{{ url_for('editor.editor', url=collections[idx].url) }}"><i
+            class="fas fa-edit"></i></a>
+        <form action="{{ url_for('collections.remove', url=collections[idx].url) }}" method="POST" method="POST"
+          class="m-1 inline_block">
+          <button class="btn__delete" type="submit" value="delete" onclick=" return confirm('確定要刪除此作品?');"><i
+              class="fas fa-trash-alt"></i></button>
+        </form>
+      </div>
+    </td>
+  </tr>
+</tbody>
+{% endif %}
 {% endfor %}
 {% endblock table_body %}
 
 <!-- Modal -->
 {% block modal_body %}
-  <form action="{{ url_for('collections.create') }}" method="POST" enctype="multipart/form-data">
-    <div class="form-group">
-      {{ form.title.label(class="form-control-label modal__label mb-1") }} <span class="text-danger">(建議字數: 15字內)</span>
-      {{ form.title(class="form-control form-control-lg") }}
-      {{ form.image.label(class="form-control-label modal__label mt-3 mb-1") }} <span class="text-danger">(建議尺寸/比例: 寬2048px * 高1365px)</span>
-      {{ form.image(class="form-control form-control-lg modal__file") }} 
-      {{ form.description.label(class="form-control-label modal__label mt-3 mb-1") }} <span class="text-danger">(建議字數: 50字內)</span>
-      {{ form.description(class="form-control form-control-lg textarea") }}
-    </div>
-    <div class="modal-footer  pb-0 border-0">
-      <button type="button" class="btn btn__cancel" data-dismiss="modal">取消</button>
-      <input class="btn btn__submitadd" type="submit" value="完成">
-    </div>
-  </form>
+<form action="{{ url_for('collections.create') }}" method="POST" enctype="multipart/form-data">
+  <div class="form-group">
+    {{ form.title.label(class="form-control-label modal__label mb-1") }} <span class="text-danger">(建議字數: 15字內)</span>
+    {{ form.title(class="form-control form-control-lg") }}
+    {{ form.image.label(class="form-control-label modal__label mt-3 mb-1") }} <span class="text-danger">(建議尺寸/比例:
+      寬2048px * 高1365px)</span>
+    {{ form.image(class="form-control form-control-lg modal__file") }}
+    {{ form.description.label(class="form-control-label modal__label mt-3 mb-1") }} <span class="text-danger">(建議字數:
+      50字內)</span>
+    {{ form.description(class="form-control form-control-lg textarea") }}
+  </div>
+  <div class="modal-footer  pb-0 border-0">
+    <button type="button" class="btn btn__cancel" data-dismiss="modal">取消</button>
+    <input class="btn btn__submitadd" type="submit" value="完成">
+  </div>
+</form>
 {% endblock modal_body %}
 
 {% block main_info_modal_body %}

+ 6 - 0
backstage/templates/layout.html

@@ -86,6 +86,12 @@
               <span class="menu-collapsed">設計專欄</span>    
             </div>
           </a>
+          <a href="{{ url_for('blogs.edit_solid_wood_furniture') }}" class="bg-dark list-group-item list-group-item-action">
+            <div class="d-flex w-100 justify-content-start align-items-center">
+              <i class="far fa-newspaper mr-3"></i>
+              <span class="menu-collapsed">單品家具</span>    
+            </div>
+          </a>
           <!-- Separator with title -->
           <a href="#" data-toggle="sidebar-colapse" class="bg-dark list-group-item list-group-item-action d-flex align-items-center">
             <div class="d-flex w-100 justify-content-start align-items-center">

+ 197 - 4
backstage/templates/solid_wood_furniture.html

@@ -1,4 +1,197 @@
-{% extends "layout.html" %}
-{% block main %}
-    <h1>solid_wood_furniture</h1>
-{% endblock main %}
+{% extends "tables/editor_table.html" %}
+{% block table_body %}
+<!-- <script type="text/javascript" src="/static/config.js"></script> -->
+<script src="https://cdn.jsdelivr.net/npm/@editorjs/editorjs@latest"></script>
+<script src="https://cdn.jsdelivr.net/npm/@editorjs/image@latest"></script><!-- Image -->
+<script type="text/javascript" src="/static/js/yo.js"></script>
+<tbody id='swfData'>
+    {% for idx in range(0, length) %}
+    <tr>
+        <td class="table__data">{{ idx + 1 }}</td>
+        <td class="table__data">{{ '[' + furnitures[idx].type + '] ' + furnitures[idx].title }}</td>
+        <td class="table__data">{{ furnitures[idx].date }}</td>
+        <!-- <td class="table__data">1</td> -->
+        <td class="table__data"><input type="checkbox" {{ 'checked' if (furnitures[idx].draft.lower()=='false' ) }}
+                onclick="toggleDraft(this,'{{ furnitures[idx].url }}');" /></td>
+        <td>
+            <div class="d-flex justify-content-center">
+                <button class="btn btn_light mr-1" onclick="getHeader('{{ furnitures[idx].url }}');"><b>修改</b> <i
+                        class="fas fa-pencil-alt"></i></button>
+                <button class="btn__delete" value="delete"
+                    onclick="if(confirm('確定要刪除?')) delfur('{{ furnitures[idx].url }}');"><i
+                        class="fas fa-trash-alt"></i></button>
+            </div>
+
+        </td>
+    </tr>
+    {% endfor %}
+</tbody>
+<script>$('#swfData')[0].innerHTML = ReplaceSwfType($('#swfData')[0].innerHTML);</script>
+{% endblock table_body %}
+
+
+{% block modal_body %}
+
+<div class="form-group">
+    類別:<select id="newSwfDropdown"></select><br />
+    名稱:<input id="newSwfName" type="text" /><br />
+    <!--     敘述:<input id="swfDesc" type="text" /><br />
+    <hr>
+    圖片:
+    <div id="editorjs" style='border:inset 1px;'></div>
+    <hr>
+    定價:<input id="swfPrice" type="text" /><br />
+    顏色:<input id="swfColor" type="text" /><br />
+    尺寸:<input id="swfSize" type="text" /><br />
+    材質:<input id="swfMet" type="text" /><br /> -->
+</div>
+<div class="modal-footer  pb-0 border-0">
+    <button type="button" class="btn btn__cancel" data-dismiss="modal">取消</button>
+    <button type="button" class="btn btn__submitadd" onclick="newfur();">完成</button>
+</div>
+<script>GenSwfDD($('#newSwfDropdown')[0]);</script>
+<script>
+    function newfur() {
+        //alert('/backstage/new_solid_wood_furniture?newSwfDropdown='+ $('#newSwfDropdown').val() +'&newSwfName='+$('#newSwfName').val());
+        axios.get('/backstage/new_solid_wood_furniture?newSwfDropdown=' + $('#newSwfDropdown').val() + '&newSwfName=' + $('#newSwfName').val()).then((data) => { location.reload() });
+    }
+    function delfur(iurl) {
+        //alert('/backstage/new_solid_wood_furniture?newSwfDropdown='+ $('#newSwfDropdown').val() +'&newSwfName='+$('#newSwfName').val());
+        axios.get('/backstage/del_solid_wood_furniture?url=' + iurl).then((data) => { location.reload() });
+    }
+</script>
+{% endblock modal_body %}
+
+{% block main_info_modal_body %}
+<div class="modal fade" id="myModal">
+    <div class="modal-dialog">
+        <div class="modal-content">
+
+            <div class="modal-header">
+                <h4 class="modal-title">修改</h4>
+                <button type="button" class="close" data-dismiss="modal">×</button>
+            </div>
+
+            <div class="modal-body">
+                <table class="table table-bordered">
+                    <tbody>
+                        <tr>
+                            <td>
+                                <h4>名稱</h4>
+                            </td>
+                            <td><input class="form-control" id="ctitle" type="text" />
+                                <div class="mt-1 text-danger">(建議字數: 15字內)</div>
+                            </td>
+                        </tr>
+                        <tr>
+                            <td>
+                                <h4>日期</h4>
+                            </td>
+                            <td><input class="form-control" id="cdate" type="text" /></td>
+                        </tr>
+                        <tr>
+                            <td>
+                                <h4>是否顯示</h4>
+                            </td>
+                            <td><input id="cdraft" type="checkbox" checked="true" /></td>
+                        </tr>
+                        <tr>
+                            <td>
+                                類別</td>
+                            <td><select id="swfDropdown" onchange="$('#ctype')[0].val(this.value);"></select></td>
+                        </tr>
+                        <tr>
+                            <td colspan="2"> </td>
+                        </tr>
+                        <tr>
+                            <td> 敘述</td>
+                            <td><input id="swfDesc" type="text" style="width: 100%;" /></td>
+                        </tr>
+                        <tr>
+                            <td> 圖片</td>
+                            <td>
+                                <div id="editorjs" style='border:inset 1px;'></div>
+                            </td>
+                        </tr>
+                        <tr>
+                            <td> 定價</td>
+                            <td><input id="swfPrice" type="text" style="width: 100%;" /></td>
+                        </tr>
+                        <tr>
+                            <td> 顏色</td>
+                            <td><input id="swfColor" type="text" style="width: 100%;" /></td>
+                        </tr>
+                        <tr>
+                            <td> 尺寸(mm)</td>
+                            <td><input id="swfSize" type="text" style="width: 100%;" /></td>
+                        </tr>
+                        <tr>
+                            <td> 材質</td>
+                            <td><input id="swfMat" type="text" style="width: 100%;" /></td>
+                        </tr>
+                        <tr>
+                            <td> 備註</td>
+                            <td><input id="swfMemo" type="text" style="width: 100%;" /></td>
+                        </tr>
+                        <tr>
+                            <td> 規格</td>
+                            <td>
+                                <div id="editorjs1" style='border:inset 1px;'></div>
+                            </td>
+                        </tr>
+                    </tbody>
+                </table>
+                <div class="d-none">
+                    <input id="ctype" type="text" /><br />
+                    <input id="curl" type="text" /><br />
+                    <input id="cimage" type="text" /><br />
+                    <input id="cweight" type="text" /><br />
+                    <input id="ctag" type="text" /><br />
+                    <input id="ccategories" type="text" /><br />
+                    <input id="ccol1" type="text" /><br />
+                    <input id="ccol2" type="text" /><br />
+                </div>
+            </div>
+
+            <div class="modal-footer">
+                <button type="button" class="btn btn__cancel" data-dismiss="modal">取消</button>
+                <button type="button" class="btn btn__submitadd" id='addNewButton'
+                    onclick="UpdateProduct();">完成</button>
+                <!-- <button type="button" id="uptbtn" class="btn btn-danger" onclick="updateHeader();">完成修改</button> -->
+            </div>
+
+        </div>
+    </div>
+</div>
+<script>GenSwfDD($('#swfDropdown')[0]);</script>
+<script>
+
+    function UpdateProduct() {
+        editor.save().then((mimg) => {
+            sectionContent = "";
+            editor1.save().then((specimg) => {
+                sectionContent = GenProductSection(mimg, specimg);
+
+                var mdContent = GetMdHeader();
+                mdContent = mdContent.replace('draft: ' + (!$('#cdraft').is(':checked')), 'draft: ' + $('#cdraft').val())
+
+                mdContent += '\n' + sectionContent;
+                //GenProductSection(outputData);
+                postData = {
+                    content: mdContent,
+                    url: editTarget
+                };
+
+                /* alert(contentApiUrl);
+                alert(editTarget); */
+                //alert(mdContent);
+                axios.post(contentApiUrl + editTarget, json = postData).then(({ data }) => {
+                    alert('作品資料已儲存');
+                }).finally((data) => { location.reload(); });
+            });
+        }).catch((error) => {
+            console.log('Saving failed: ', error)
+        })
+    };
+</script>
+{% endblock %}

+ 7 - 150
backstage/templates/tables/editor_table.html

@@ -1,5 +1,10 @@
 {% extends "layout.html" %}
 {% block main %}
+<link rel="stylesheet" href="https://code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">
+<link rel="stylesheet" href="https://jqueryui.com/resources/demos/style.css">
+<script src="https://code.jquery.com/jquery-1.12.4.js"></script>
+<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
+<script type="text/javascript" src="{{url_for('static', filename='config.js')}}"></script>
 <h1 class="h3"><i class="far fa-newspaper mr-3"></i>{{ title }}</h1>
 <table id="example" class="table" cellspacing="0" width="60%">
   <thead>
@@ -17,12 +22,7 @@
   </thead>
   {% block table_body %}{% endblock %}
 </table>
-<link rel="stylesheet" href="https://code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">
-<link rel="stylesheet" href="https://jqueryui.com/resources/demos/style.css">
-<script src="https://code.jquery.com/jquery-1.12.4.js"></script>
-<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
-<script type="text/javascript" src="{{url_for('static', filename='config.js')}}"></script>
-<script type="text/javascript" src="{{url_for('static', filename='js/yo.js')}}"></script>
+
 
 {% block main_info_modal_body %}{% endblock %}
 <!-- <div class="modal fade" id="myModal">
@@ -123,150 +123,7 @@
   frontMatters = [];
   contentMatters = [];
   const contentApiUrl = `${PORTAL_SERVER}contents?url=`;
-  function getHeader(url) {
-    axios.get(contentApiUrl + url).then(({ data }) => {
-      frontMatters = [];
-      contentMatters = [];
-      aa = data[0]['content'];
-      const content = _.get(data, '0.content', '');
-      blocks = parseMd(aa);
-      oTitle = $("#ctitle").val();
-      // $("#dialog-form").dialog();
-      if ($("#ctype").val() == "collection") {
-        $("#scat").hide();
-
-      }
-      else {
-        $("#sdesc").hide();
-      }
-      $("#myModal").modal();
-      editTarget = url;
-      //console.log(frontMatters);
-      //alert($('#cimage').val());
-    });
-  }
-  function toggleDraft(obj, url) {
-    axios.get(contentApiUrl + url).then(({ data }) => {
-      frontMatters = [];
-      contentMatters = [];
-      aa = data[0]['content'];
-      const content = _.get(data, '0.content', '');
-      blocks = parseMd(aa);
-      editTarget = url;
-      $('#cdraft').removeAttr('checked');
-      $('#cdraft').prop('checked', obj.checked);
-      updateHeader();
-      oTitle = "";
-    });
-  }
-  function updateHeader() {
-    /* if (oTitle != $('#ctitle').val() && $('#ctitle').val() != "" && oTitle != "") {
-      axios.get('/backstage/modTitle/' + oTitle + '/' + $('#ctitle').val()).then(({ data }) => {
-        if (data.success == "0") {
-          alert('已有重複的標題,請重新設定');
-          return;
-        }
-        else {
-          writeMd();
-        }
-      });
-    }
-    else {
-      writeMd();
-    } */
-    $("#uptbtn").attr('disabled', true);
-    writeMd();
-    // location.reload();
-  }
-  function writeMd() {
-
-    axios.get('/backstage/utils?trantext=' + $('#ccategories').val()).then(({ data }) => { $('#ccol1').val(data); })
-      .finally(() => {
-        mdContent = GetMdHeader();
-        mdContent += contentMatters.join("\n");
-        var formData = new FormData();
-        var imagefile = document.querySelector('#cfile');
-        formData.append("image", imagefile.files[0]);
-        axios.post('/backstage/upload/title', formData, {
-          headers: {
-            'Content-Type': 'multipart/form-data'
-          }
-        }).then(({ data }) => {
-          $('#cfile').val("");
-          if (data.success == "1") {
-            mdContent = mdContent.replace($('#cimage').val(), '/img/collection/' + data.file.url.substring(data.file.url.lastIndexOf('/') + 1));
-            //alert(data.file.url.substring(data.file.url.lastIndexOf('/')+1));
-          }
-
-          postData = {
-            content: mdContent,
-            url: editTarget
-          };
-          //console.log(mdContent);
-          axios.post(contentApiUrl + editTarget, json = postData).then(({ data }) => {
-          });
-        }).finally(() => {
-          alert('資料已更新'); // test
-          location.reload();
-        });
-      });
-    /*
-    mdContent += '---\n';
-    mdContent += 'title: "' + $('#ctitle').val() + '"\n';
-    mdContent += 'date: ' + $('#cdate').val() + '\n';
-    mdContent += 'draft: ' + (!$('#cdraft').is(':checked')) + '\n';
-    mdContent += 'type: "' + $('#ctype').val() + '"\n';
-    mdContent += 'url: "' + $('#curl').val() + '"\n';
-    //mdContent += 'url: "' + $('#curl').val() + '"\n';
-    mdContent += 'image: "' + $('#cimage').val() + '"\n';
-    if ($('#ctype').val() == "collection") {
-      mdContent += 'description: "' + $('#cdescription').val().replace(/\r?\n/g, '<br>') + '"\n';
-      mdContent += 'weight: ' + ($('#cweight').val() == 'undefined' ? "" : $('#cweight').val()) + '\n';
-      mdContent += 'tag: "' + ($('#ctag').val() == 'undefined' ? "" : $('#ctag').val()) + '"\n';
-    }
-    else if ($('#ctype').val() == "blog") {
-      mdContent += 'categories: ' + $('#ccategories').val() + '\n';
-      mdContent += 'col1: "' + ($('#ccol1').val() == 'undefined' ? "" : $('#ccol1').val()) + '"\n';
-      mdContent += 'col2: "' + ($('#ccol2').val() == 'undefined' ? "" : $('#ccol2').val()) + '"\n';
-    }
-    mdContent += '---\n';
-    */
-
-    //console.log(contentMatters);
-
-    /* var formData = new FormData();
-    var imagefile = document.querySelector('#cfile');
-    formData.append("image", imagefile.files[0]);
-    axios.post('/backstage/upload/title', formData, {
-      headers: {
-        'Content-Type': 'multipart/form-data'
-      }
-    }).then(({ data }) => {
-      $('#cfile').val("");
-      if (data.success == "1") {
-        mdContent = mdContent.replace($('#cimage').val(), '/img/collection/' + data.file.url.substring(data.file.url.lastIndexOf('/') + 1));
-        //alert(data.file.url.substring(data.file.url.lastIndexOf('/')+1));
-      }
-
-      postData = {
-        content: mdContent,
-        url: editTarget
-      };
-      //console.log(mdContent);
-      axios.post(contentApiUrl + editTarget, json = postData).then(({ data }) => {
-      });
-    }).finally(() => {
-      alert('資料已更新'); // test
-      location.reload();
-    }); */
-  }
-
-  $(function () {
-
-    $("#dialog-form").hide();
-
 
-  });
   //allObjs = JSON.parse(htmlDecode('{{ collections }}'));
   //console.log(htmlDecode('{{ collections }}'));
 
@@ -278,7 +135,7 @@
   <div class="modal-dialog" role="document">
     <div class="modal-content">
       <div class="modal-header border-0">
-        <h5 class="modal-title modal__title" id="createModalLabel">新增文章</h5>
+        <h5 class="modal-title modal__title" id="createModalLabel">新增</h5>
         <button type="button" class="close modal__close" data-dismiss="modal" aria-label="Close">
           <span class="modal__close__back">
             <span aria-hidden="true">&times;</span>

+ 47 - 9
backstage/upload/routes.py

@@ -10,6 +10,8 @@ import requests
 from PIL import Image
 from urllib.parse import urlparse
 import uuid
+import json
+from backstage.config import PORTAL_SERVER
 
 
 #from backstage.utils.routes import update_manage_table
@@ -17,11 +19,37 @@ import uuid
 upload_app = Blueprint('upload', __name__)
 
 
+@upload_app.route('/backstage/test/<path:iurl>', methods=['GET'])
+def upload_test(iurl):
+
+    test = iurl[0:iurl.rfind("/")+1]
+    new_response = requests.get(PORTAL_SERVER + 'contents?url=' + test)
+    #my_dict = json.loads(new_response.content.decode('utf-8'))[0].items()
+    for key, value in json.loads(new_response.content.decode('utf-8'))[0].items():
+        if key == 'path':
+            print(value.replace('\\', '/'))
+    # print(my_dict[0].items())
+    return new_response.content
+
+
 @upload_app.route('/backstage/upload/<path:iurl>', methods=['POST'])
 def upload_post(iurl):
+
+    #取得md路徑
+    mdPath = ""
+    new_response = requests.get(PORTAL_SERVER + 'contents?url=' + iurl)
+    #my_dict = json.loads(new_response.content.decode('utf-8'))[0].items()
+    for key, value in json.loads(new_response.content.decode('utf-8'))[0].items():
+        if key == 'path':
+            mdPath = value.replace('\\', '/')
+            mdPath = mdPath[0:mdPath.rfind('/')+1]
+    isProduct = False
+    if mdPath.find("設計家具") >= 0 or mdPath.find("模組系統櫃") >= 0:
+        isProduct = True
     #bdata = request.stream.read()
     filepath = ""
     itype = ""
+    print(mdPath)
     #aa = request.get_data()
     if iurl == "title":
         itype = iurl
@@ -48,8 +76,12 @@ def upload_post(iurl):
             """ if file.filename == '':
                 #flash('No selected file')
                 return redirect(request.url) """
+            oimgtype = file.filename[file.filename.rfind(".")+1:]
+            oimgtypeName = oimgtype
+            if oimgtype.lower() == 'jpg':
+                oimgtypeName = 'jpeg'
 
-            if file:
+            if file and not isProduct:
                 #filename = secure_filename(file.filename)
 
                 #fname = str(uuid.uuid4()) + file.filename[file.filename.rfind("."):]
@@ -57,14 +89,7 @@ def upload_post(iurl):
                 if filepath == "title":
                     sitepath = UPLOAD_PATH_MAP[0][0] + "../../static/img/collection/"
                 else:
-                    if itype == "blog":
-                        sitepath = UPLOAD_PATH_MAP[0][0] + "../blog/" + filepath + "/img/"
-                    else:
-                        sitepath = UPLOAD_PATH_MAP[0][0] + filepath + "/img/"
-                oimgtype = file.filename[file.filename.rfind(".")+1:]
-                oimgtypeName = oimgtype
-                if oimgtype.lower() == 'jpg':
-                    oimgtypeName = 'jpeg'
+                    sitepath = UPLOAD_PATH_MAP[0][0] + "../" + itype + "/" + filepath + "/img/"
 
                 wfname = str(uuid.uuid4()) + ".webp"
                 owfname = wfname.replace('webp', oimgtype)
@@ -96,6 +121,19 @@ def upload_post(iurl):
                 # aa = {"success": 1, "file": {"url": UPLOAD_PATH_MAP[0][1] + filepath[filepath.rfind(
                 #    "/")+1:] + "/img/" + fname, "width": image_object.width, "height": image_object.height}}
                 return aa
+            else:
+                wpath = os.getcwd() + "/backstage/upload/" + filepath+"/img/"
+                wfname = str(uuid.uuid4()) + ".webp"
+                image_object = Image.open(file)
+                #image_object.save(mdPath+wfname, oimgtypeName)
+                if image_object.size[0] > 1000:
+                    image_object.thumbnail(size=((1600, 1600)))
+                image_object.save(wpath+wfname, 'webp')
+                image_object.save(mdPath+wfname, 'webp')
+                owfname = wfname.replace('webp', oimgtype)
+                aa = {"success": 1, "file": {"url": "/backstage/upload/" + filepath+"/img/" + wfname,
+                                             "width": image_object.width, "height": image_object.height}}
+                return aa
         if request.method == 'GET':
             print('GET')
             # print(request.files)