routes.py 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359
  1. from backstage.config import UPLOAD_PATH_MAP
  2. import os
  3. import shutil
  4. from flask import render_template, Blueprint, request, redirect, url_for
  5. import flask
  6. from flask_cors import CORS, cross_origin
  7. from flask.helpers import make_response, send_file, send_from_directory
  8. from werkzeug.wrappers import Response
  9. import requests
  10. from PIL import Image, ImageFile
  11. from urllib.parse import urlparse
  12. import uuid
  13. import json
  14. from backstage.config import PORTAL_SERVER
  15. ImageFile.LOAD_TRUNCATED_IMAGES = True
  16. Image.MAX_IMAGE_PIXELS = None
  17. #from backstage.utils.routes import update_manage_table
  18. upload_app = Blueprint('upload', __name__)
  19. @upload_app.route('/backstage/test/<path:iurl>', methods=['GET'])
  20. def upload_test(iurl):
  21. test = iurl[0:iurl.rfind("/")+1]
  22. new_response = requests.get(PORTAL_SERVER + 'contents?url=' + test)
  23. #my_dict = json.loads(new_response.content.decode('utf-8'))[0].items()
  24. for key, value in json.loads(new_response.content.decode('utf-8'))[0].items():
  25. if key == 'path':
  26. print(value.replace('\\', '/'))
  27. # print(my_dict[0].items())
  28. return new_response.content
  29. @upload_app.route('/backstage/multiupload/<path:iurl>', methods=['POST']) #collections
  30. def upload_multi_post(iurl):
  31. # 取得md路徑
  32. mdPath = ""
  33. new_response = requests.get(PORTAL_SERVER + 'contents?url=' + iurl)
  34. #my_dict = json.loads(new_response.content.decode('utf-8'))[0].items()
  35. obj = json.loads(new_response.content.decode('utf-8'))
  36. if len(obj) > 0:
  37. for key, value in obj[0].items():
  38. if key == 'path':
  39. mdPath = value.replace('\\', '/')
  40. #print(mdPath)
  41. mdPath = mdPath[0:mdPath.rfind('/')+1]
  42. #print(mdPath)
  43. isProduct = False
  44. if mdPath.find("設計家具") >= 0 or mdPath.find("模組系統櫃") >= 0:
  45. isProduct = True
  46. #bdata = request.stream.read()
  47. filepath = ""
  48. itype = ""
  49. print("markdown path is" + mdPath)
  50. #aa = request.get_data()
  51. if iurl == "title":
  52. itype = iurl
  53. filepath = iurl
  54. else:
  55. itype = iurl[0:iurl.find("/")]
  56. filepath = iurl[iurl.rfind("/")+1:]
  57. if request.method == 'POST':
  58. # check if the post request has the file part
  59. # print(request.full_path)
  60. """ if 'file' not in request.files:
  61. #flash('No file part')
  62. return redirect(request.url) """
  63. print(request.files)
  64. print(len(request.files))
  65. if len(request.files) == 0:
  66. aa = {"success": 0}
  67. return aa
  68. else:
  69. n=0
  70. filelink = ''
  71. for i in request.files:
  72. n+=1
  73. fname = 'image' + str(n)
  74. file = request.files[fname]
  75. print("The file is at" + filepath)
  76. # If the user does not select a file, the browser submits an
  77. # empty file without a filename.
  78. """ if file.filename == '':
  79. #flash('No selected file')
  80. return redirect(request.url) """
  81. oimgtype = file.filename[file.filename.rfind(".")+1:]
  82. oimgtypeName = oimgtype
  83. if oimgtype.lower() == 'jpg':
  84. oimgtypeName = 'jpeg'
  85. if file and not isProduct:
  86. #filename = secure_filename(file.filename)
  87. #fname = str(uuid.uuid4()) + file.filename[file.filename.rfind("."):]
  88. #sitepath = UPLOAD_PATH_MAP[0][0] + filepath[filepath.rfind("/")+1:] + "/img/"
  89. if filepath == "title":
  90. sitepath = UPLOAD_PATH_MAP[0][2] + "/static/img/title/"
  91. else:
  92. sitepath = mdPath + "/img/"
  93. #sitepath = UPLOAD_PATH_MAP[0][0] + "../" + itype + "/" + filepath + "/img/"
  94. wfname = str(uuid.uuid4()).replace('-','') + ".webp"
  95. owfname = wfname.replace('webp', oimgtype)
  96. #fullpath = UPLOAD_PATH_MAP[0][0] + filepath[filepath.rfind("/")+1:] + "\\img\\" + fname
  97. #print(UPLOAD_PATH_MAP[0][1] + filepath[filepath.rfind("/")+1:] + "/img/" + fname)
  98. # file.save(fullpath)
  99. #image_object = Image.open(fullpath)
  100. #print(request.args.get('url', type=str))
  101. wpath = os.getcwd() + "/backstage/upload/" + filepath+"/img/"
  102. owpath = os.getcwd() + "/backstage/upload/" + filepath+"/img/orig/"
  103. print("1wpath is " + wpath)
  104. print("1owpath is " + owpath)
  105. #fullpath = wpath + fname
  106. if not os.path.exists(wpath):
  107. os.makedirs(wpath)
  108. if not os.path.exists(owpath):
  109. os.makedirs(owpath)
  110. if not os.path.exists(sitepath):
  111. os.makedirs(sitepath)
  112. # file.save(fullpath)
  113. image_object = Image.open(file)
  114. image_object.save(owpath+owfname)
  115. if image_object.size[0] > 1000:
  116. image_object.thumbnail(size=((1600, 1600)))
  117. image_object.save(wpath+wfname)
  118. image_object.save(sitepath+wfname)
  119. print("Loc1a: " + wpath+wfname)
  120. print("Loc1b: " + owpath+wfname)
  121. print("Loc2: " + sitepath+wfname)
  122. print(filepath)
  123. #file.save(os.getcwd()+ "/backstage/upload/img/"+ fname)
  124. # return redirect(url_for('download_file', name=file.filename))
  125. filelink += wfname + ";;;"
  126. print(filelink)
  127. aa = {"success": 1, "fileurl": filelink}
  128. return aa
  129. if request.method == 'GET':
  130. print('GET')
  131. # print(request.files)
  132. # print(request.form)
  133. # print(requests.post("/backstage/upload"))
  134. aa = {"success": 1, "file": {"url": "http://www.choozmo.com/images/logo%20%281%29.webp", }}
  135. return aa
  136. @upload_app.route('/backstage/upload/<path:iurl>', methods=['POST'])
  137. def upload_post(iurl):
  138. # 取得md路徑
  139. mdPath = ""
  140. new_response = requests.get(PORTAL_SERVER + 'contents?url=' + iurl)
  141. #my_dict = json.loads(new_response.content.decode('utf-8'))[0].items()
  142. obj = json.loads(new_response.content.decode('utf-8'))
  143. if len(obj) > 0:
  144. for key, value in obj[0].items():
  145. if key == 'path':
  146. mdPath = value.replace('\\', '/')
  147. #print(mdPath)
  148. mdPath = mdPath[0:mdPath.rfind('/')+1]
  149. #print(mdPath)
  150. print(mdPath)
  151. isProduct = False
  152. if mdPath.find("設計家具") >= 0 or mdPath.find("模組系統櫃") >= 0:
  153. isProduct = True
  154. #bdata = request.stream.read()
  155. filepath = ""
  156. itype = ""
  157. print(mdPath)
  158. #aa = request.get_data()
  159. if iurl == "title":
  160. itype = iurl
  161. filepath = iurl
  162. else:
  163. itype = iurl[0:iurl.find("/")]
  164. filepath = iurl[iurl.rfind("/")+1:]
  165. if request.method == 'POST':
  166. # check if the post request has the file part
  167. # print(request.full_path)
  168. """ if 'file' not in request.files:
  169. #flash('No file part')
  170. return redirect(request.url) """
  171. if len(request.files) == 0:
  172. aa = {"success": 0}
  173. return aa
  174. else:
  175. file = request.files['image']
  176. #file2 = request.files['image2'] #again, reference
  177. print("The file is at" + filepath)
  178. # If the user does not select a file, the browser submits an
  179. # empty file without a filename.
  180. """ if file.filename == '':
  181. #flash('No selected file')
  182. return redirect(request.url) """
  183. oimgtype = file.filename[file.filename.rfind(".")+1:]
  184. oimgtypeName = oimgtype
  185. if oimgtype.lower() == 'jpg':
  186. oimgtypeName = 'jpeg'
  187. if file and not isProduct:
  188. #filename = secure_filename(file.filename)
  189. #fname = str(uuid.uuid4()) + file.filename[file.filename.rfind("."):]
  190. #sitepath = UPLOAD_PATH_MAP[0][0] + filepath[filepath.rfind("/")+1:] + "/img/"
  191. if filepath == "title":
  192. sitepath = UPLOAD_PATH_MAP[0][2] + "/static/img/title/"
  193. else:
  194. sitepath = mdPath + "/img/"
  195. #sitepath = UPLOAD_PATH_MAP[0][0] + "../" + itype + "/" + filepath + "/img/"
  196. wfname = str(uuid.uuid4()).replace('-','') + ".webp"
  197. owfname = wfname.replace('webp', oimgtype)
  198. #fullpath = UPLOAD_PATH_MAP[0][0] + filepath[filepath.rfind("/")+1:] + "\\img\\" + fname
  199. #print(UPLOAD_PATH_MAP[0][1] + filepath[filepath.rfind("/")+1:] + "/img/" + fname)
  200. # file.save(fullpath)
  201. #image_object = Image.open(fullpath)
  202. #print(request.args.get('url', type=str))
  203. wpath = os.getcwd() + "/backstage/upload/" + filepath+"/img/"
  204. owpath = os.getcwd() + "/backstage/upload/" + filepath+"/img/orig/"
  205. print("1wpath is " + wpath)
  206. print("1owpath is " + owpath)
  207. #fullpath = wpath + fname
  208. if not os.path.exists(wpath):
  209. os.makedirs(wpath)
  210. if not os.path.exists(owpath):
  211. os.makedirs(owpath)
  212. if not os.path.exists(sitepath):
  213. os.makedirs(sitepath)
  214. # file.save(fullpath)
  215. image_object = Image.open(file)
  216. image_object.save(owpath+owfname)
  217. if image_object.size[0] > 1000:
  218. image_object.thumbnail(size=((1600, 1600)))
  219. image_object.save(wpath+wfname)
  220. image_object.save(sitepath+wfname)
  221. print("Loc1a: " + wpath+wfname)
  222. print("Loc1b: " + owpath+wfname)
  223. print("Loc2: " + sitepath+wfname)
  224. print(filepath)
  225. #file.save(os.getcwd()+ "/backstage/upload/img/"+ fname)
  226. # return redirect(url_for('download_file', name=file.filename))
  227. aa = {"success": 1, "file": {"url": "/backstage/upload/" +
  228. filepath+"/img/" + wfname, "width": image_object.width, "height": image_object.height}}
  229. # aa = {"success": 1, "file": {"url": UPLOAD_PATH_MAP[0][1] + filepath[filepath.rfind(
  230. # "/")+1:] + "/img/" + fname, "width": image_object.width, "height": image_object.height}}
  231. return aa
  232. elif isProduct:
  233. wpath = os.getcwd() + "/backstage/upload/" + filepath+"/img/"
  234. print("2wpath is " + wpath)
  235. wfname = str(uuid.uuid4()) + ".webp"
  236. image_object = Image.open(file)
  237. #image_object.save(mdPath+wfname, oimgtypeName)
  238. if image_object.size[0] > 1000:
  239. image_object.thumbnail(size=((1600, 1600)))
  240. if not os.path.exists(wpath):
  241. os.makedirs(wpath)
  242. image_object.save(wpath+wfname)
  243. image_object.save(mdPath+wfname)
  244. print("Loc3: " + wpath+wfname)
  245. print("Loc4: " + mdPath+wfname)
  246. owfname = wfname.replace('webp', oimgtype)
  247. aa = {"success": 1, "file": {"url": "/backstage/upload/" + filepath+"/img/" + wfname,
  248. "width": image_object.width, "height": image_object.height}}
  249. return aa
  250. if request.method == 'GET':
  251. print('GET')
  252. # print(request.files)
  253. # print(request.form)
  254. # print(requests.post("/backstage/upload"))
  255. aa = {"success": 1, "file": {"url": "http://www.choozmo.com/images/logo%20%281%29.webp", }}
  256. return aa
  257. @upload_app.route('/backstage/upload/<path:filepath>', methods=['GET'])
  258. def upload_get(filepath):
  259. # print(filepath)
  260. #print(os.getcwd() + "/backstage/upload/"+filepath, filepath[filepath.rfind("/")+1:])
  261. #aa = {"success" : 1,"file": { "url" : "https://www.tesla.com/tesla_theme/assets/img/_vehicle_redesign/roadster_and_semi/roadster/hero.jpg", } }
  262. # return redirect(url_for('upload.upload_get',filename=filename), code=301)
  263. # return send_from_directory(os.getcwd() + "/backstage/upload/"+filepath, filepath[filepath.rfind("/")+1:])
  264. return send_file(os.getcwd() + "/backstage/upload/"+filepath)
  265. @upload_app.route('/backstage/getimage/<path:iurl>', methods=['POST', 'GET'])
  266. def get_image(iurl):
  267. itype = iurl[0:iurl.find("/")]
  268. filepath = iurl[iurl.rfind("/")+1:]
  269. # print(request.get_json()['url'])
  270. if itype == "blog":
  271. sitepath = UPLOAD_PATH_MAP[0][0] + "../blog/" + filepath + "/img/"
  272. else:
  273. sitepath = UPLOAD_PATH_MAP[0][0] + filepath + "/img/"
  274. #sitepath = UPLOAD_PATH_MAP[0][0] + filepath + "/img/"
  275. oimgtype = str(request.get_json()['url'])[str(request.get_json()['url']).rfind(".")+1:]
  276. oimgtypeName = oimgtype
  277. if oimgtype.lower() == 'jpg':
  278. oimgtypeName = 'jpeg'
  279. # fname = str(uuid.uuid4()) + str(request.get_json()
  280. # ['url'])[str(request.get_json()['url']).rfind("."):]
  281. wfname = str(uuid.uuid4()) + ".webp"
  282. owfname = wfname.replace('webp', oimgtype)
  283. wpath = os.getcwd() + "/backstage/upload/" + filepath+"/img/"
  284. owpath = os.getcwd() + "/backstage/upload/" + filepath+"/img/orig/"
  285. """ fullpath = wpath + fname
  286. if not os.path.exists(wpath):
  287. os.makedirs(wpath)
  288. f = open(fullpath, 'wb')
  289. f.write(requests.get(request.get_json()['url']).content)
  290. f.close() """
  291. if not os.path.exists(wpath):
  292. os.makedirs(wpath)
  293. if not os.path.exists(owpath):
  294. os.makedirs(owpath)
  295. if not os.path.exists(sitepath):
  296. os.makedirs(sitepath)
  297. image_object = Image.open(requests.get(request.get_json()['url'], stream=True).raw)
  298. image_object.save(owpath+owfname)
  299. if image_object.size[0] > 1000:
  300. image_object.thumbnail(size=((1600, 1600)))
  301. image_object.save(wpath+wfname)
  302. image_object.save(sitepath+wfname)
  303. # send_file()
  304. #aa = {"success" : 1,"file": { "url" : "http://localhost:9000/backstage/upload/avatar1.jpg", } }
  305. #resp = make_response(open(os.getcwd()+ "/backstage/upload/" + fname, 'br').read(), 301)
  306. #resp.content_type = "image/jpeg"
  307. #resp.content_encoding = "Unicode"
  308. # return redirect(request.get_json()['url'], code=301)
  309. aa = {"success": 1, "file": {"url": "/backstage/upload/" +
  310. filepath+"/img/" + wfname, "width": image_object.width, "height": image_object.height}}
  311. return aa
  312. @upload_app.route('/backstage/modTitle/<path:filepath>', methods=['GET'])
  313. def modify_title(filepath):
  314. oldPath = UPLOAD_PATH_MAP[0][0] + filepath.split('/')[0]
  315. newPath = UPLOAD_PATH_MAP[0][0] + filepath.split('/')[1]
  316. # os.renames(oldPath,newPath)
  317. """ if os.path.exists(newPath):
  318. return {"success" : 0, "message" : "New directory exists."} """
  319. """ shutil.copytree(oldPath, newPath)
  320. shutil.rmtree(oldPath) """
  321. print(oldPath + ' => ' + newPath)
  322. return {"success": 1}