genjson.py 44 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931
  1. import os
  2. from typing import Optional
  3. import mysql.connector
  4. from dataset.util import ResultIter
  5. from fastapi import FastAPI
  6. from fastapi.middleware.cors import CORSMiddleware
  7. from pytrends.request import TrendReq
  8. from datetime import tzinfo
  9. import datetime
  10. from io import BytesIO
  11. from fastapi.responses import StreamingResponse
  12. import xlsxwriter
  13. import pandas as pd
  14. import dataset
  15. import json
  16. from pytube import extract
  17. app = FastAPI()
  18. origins = [
  19. "*"
  20. ]
  21. app.add_middleware(
  22. CORSMiddleware,
  23. allow_origins=origins,
  24. allow_credentials=True,
  25. allow_methods=["*"],
  26. allow_headers=["*"],
  27. )
  28. hhhMBPath = '../hhh-home-mb'
  29. hhhPCPath = '../hhh-home-pc'
  30. connstr = 'mysql://hhh7796hhh:lYmWsu^ujcA1@hhh-v57.cmab1ctkglka.ap-northeast-2.rds.amazonaws.com:3306/xoops?charset=utf8mb4'
  31. def ExecuteQuery(isql):
  32. with mysql.connector.connect(
  33. host='hhh-v57.cmab1ctkglka.ap-northeast-2.rds.amazonaws.com',
  34. database='xoops',
  35. user='hhh7796hhh',
  36. password='lYmWsu^ujcA1',
  37. use_unicode=True,
  38. charset='utf8',
  39. collation='utf8_unicode_ci'
  40. ) as connection :
  41. with connection.cursor(dictionary=True) as cursor:
  42. # connection.set_charset_collation('utf8','utf8_general_ci')
  43. #cursor = connection.cursor(dictionary=True)
  44. cursor.execute(isql)
  45. return cursor.fetchall()
  46. def ExecuteCmd(isql):
  47. with mysql.connector.connect(
  48. host='hhh-v57.cmab1ctkglka.ap-northeast-2.rds.amazonaws.com',
  49. database='xoops',
  50. user='hhh7796hhh',
  51. password='lYmWsu^ujcA1',
  52. use_unicode=True,
  53. charset='utf8',
  54. collation='utf8_unicode_ci'
  55. ) as connection:
  56. cursor = connection.cursor(dictionary=True)
  57. cursor.execute(isql)
  58. print(cursor.rowcount)
  59. connection.commit()
  60. return None
  61. @app.get("/ExportExecuteDetail")
  62. async def ExportExecuteDetail():
  63. with dataset.connect(connstr) as db:
  64. output = BytesIO()
  65. records = db.query(""" select f.exf_id, num 合約, company 合約公司,lv1 大項目,lv2 執行項, contract_time 合約到期日,price 金額,sales_man 業務,quota 額度,creator 建立者,is_close 狀態,sdate 上架日期,edate 下架日期,f.note 備註,designer 設計師,mobile 手機,telete 電話,contract_person 聯絡人,detail_status 合約名稱,d.create_time 建立時間,d.update_time 更新時間,last_update 最後更新 from execute_form f
  66. left join execute_detail d on f.exf_id=d.exf_id
  67. where f.is_delete='N' order BY f.exf_id DESC, exd_id
  68. """)
  69. df = pd.DataFrame(list(records))
  70. writer = pd.ExcelWriter(output)
  71. df.to_excel(writer, sheet_name='bar')
  72. writer.save()
  73. """ workbook = xlsxwriter.Workbook(output)
  74. worksheet = workbook.add_worksheet()
  75. for cols in records:
  76. worksheet.write(0, 0, 'ISBN')
  77. worksheet.write(0, 1, 'Name')
  78. worksheet.write(0, 2, 'Takedown date')
  79. worksheet.write(0, 3, 'Last updated')
  80. workbook.close() """
  81. output.seek(0)
  82. headers = {
  83. 'Content-Disposition': 'attachment; filename="execute_detail_all.xlsx"'
  84. }
  85. return StreamingResponse(output, headers=headers, media_type='application/octet-stream')
  86. @app.get("/")
  87. def read_root():
  88. return {"Hello": "World"}
  89. @app.get("/movexoopstostage")
  90. def movexoopstostage(designerid: str = "0", caseid: str = "0"):
  91. with dataset.connect(connstr) as db:
  92. db.query(
  93. "replace INTO stage._hdesigner SELECT * FROM xoops._hdesigner WHERE hdesigner_id IN ('" + designerid.replace(',', "','")+"');")
  94. db.query(
  95. "replace INTO stage._hcase SELECT * FROM xoops._hcase WHERE hcase_id IN ('"+caseid.replace(',', "','")+"');")
  96. db.query(
  97. "replace INTO stage._hcase_img SELECT * FROM xoops._hcase_img WHERE hcase_id IN ('"+caseid.replace(',', "','")+"');")
  98. return {"success"}
  99. @app.get("/movepxoopstostage")
  100. def movepxoopstostage(brandid: str = "0", productid: str = "0"):
  101. with dataset.connect(connstr) as db:
  102. db.query(
  103. "replace INTO stage._hbrand SELECT * FROM xoops._hbrand WHERE hbrand_id IN ('" + brandid.replace(',', "','")+"');")
  104. db.query(
  105. "replace INTO stage._hbrand_page SELECT * FROM xoops._hbrand_page WHERE hbrand_id IN ('" + brandid.replace(',', "','")+"');")
  106. db.query(
  107. "replace INTO stage._hproduct SELECT * FROM xoops._hproduct WHERE id IN ('"+productid.replace(',', "','")+"');")
  108. db.query(
  109. "replace INTO stage._hproduct_img SELECT * FROM xoops._hproduct_img WHERE hproduct_id IN ('"+productid.replace(',', "','")+"');")
  110. return {"success"}
  111. @app.get("/movecxoopstostage")
  112. def movecxoopstostage(columnid: str = "0"):
  113. with dataset.connect(connstr) as db:
  114. db.query(
  115. "replace INTO stage._hcolumn SELECT * FROM xoops._hcolumn WHERE hcolumn_id IN ('" + columnid.replace(',', "','")+"');")
  116. db.query(
  117. "replace INTO stage._hcolumn_img SELECT * FROM xoops._hcolumn_img WHERE hcolumn_id IN ('" + columnid.replace(',', "','")+"');")
  118. db.query(
  119. "replace INTO stage._hcolumn_page SELECT * FROM xoops._hcolumn_page WHERE hcolumn_id IN ('" + columnid.replace(',', "','")+"');")
  120. return {"success"}
  121. @app.get("/genjson")
  122. def genjson(filename: str = "realtime.json"):
  123. jData = json.load(open(hhhMBPath+'/json/data.json', encoding='utf8'))
  124. records = ExecuteQuery("SELECT * FROM _had where (now() between start_time and end_time or ( start_time is null and end_time is null) or ( start_time = '0000-00-00 00:00:00' and end_time = '0000-00-00 00:00:00')) and onoff='1' and adtype like '首八大%' ")
  125. for x in jData:
  126. # 頂部輪播區-新刊頭
  127. if x['id'] == 0:
  128. records = ExecuteQuery("""SELECT adlogo lo,adlogo_mobile mlo, adhref lk, adlogo_mobile_webp lomwebp, adlogo_webp dwebp FROM _had
  129. WHERE adtype LIKE '新刊頭%'
  130. AND onoff='1'
  131. AND(NOW() BETWEEN start_time AND end_time OR(start_time='0000-00-00 00:00:00' and end_time='0000-00-00 00:00:00') or (start_time is null and end_time is NULL))
  132. ORDER BY cast(SUBSTR(adtype,4) AS DECIMAL)""")
  133. x["data"] = []
  134. for c in records:
  135. a = {'imgUrl': c['mlo'], 'link': str(
  136. c['lk']), 'DimgUrl': c['lo'], 'webp': str(c['lomwebp']), 'Dwebp': str(c['dwebp'])}
  137. x["data"].append(a)
  138. # print(x["data"])
  139. # 主要輪播區-首八大
  140. if x['id'] == 1:
  141. records = ExecuteQuery("""SELECT adlogo lo,adlogo_mobile mlo, adhref lk, adlogo_mobile_webp lomwebp, adlogo_webp dwebp FROM _had
  142. WHERE adtype LIKE '首八大%'
  143. AND onoff='1'
  144. AND(NOW() BETWEEN start_time AND end_time OR(start_time='0000-00-00 00:00:00' and end_time='0000-00-00 00:00:00') or (start_time is null and end_time is NULL))
  145. ORDER BY cast(SUBSTR(adtype,4) AS DECIMAL)""")
  146. x["data"] = []
  147. for c in records:
  148. a = {'imgUrl': c['mlo'], 'link': str(
  149. c['lk']), 'DimgUrl': c['lo'], 'webp': str(c['lomwebp']), 'Dwebp': str(c['dwebp'])}
  150. x["data"].append(a)
  151. # print(x["data"])
  152. #tab區塊-最夯設計, 影音實錄, 專欄文章
  153. if x['id'] == 2:
  154. x["data"] = []
  155. records = ExecuteQuery("""SELECT caption TT ,cover IMG, CONCAT('https://hhh.com.tw/cases/detail/',hcase_id,'/') LK, short_desc txt
  156. from _hcase
  157. left join _hdesigner ON _hcase.hdesigner_id=_hdesigner.hdesigner_id
  158. WHERE
  159. _hcase.onoff='1' AND _hdesigner.onoff='1'
  160. AND(NOW() > sdate)
  161. ORDER BY hcase_id DESC
  162. LIMIT 3""")
  163. a = {'tab': '最夯設計', 'data': []}
  164. for c in records:
  165. ad = {'imgUrl': c['IMG'], 'link': c['LK'],
  166. 'title': c['TT'], 'description': c['txt']}
  167. a['data'].append(ad)
  168. x["data"].append(a)
  169. records = ExecuteQuery("""SELECT title TT,iframe IMG , CONCAT('https://hhh.com.tw/video-post.php?id=',hvideo_id) LK , name
  170. from _hvideo
  171. ORDER BY hvideo_id DESC
  172. LIMIT 4""")
  173. a = {'tab': '影音實錄', 'data': []}
  174. cnt = 0
  175. for c in records:
  176. if cnt == 0:
  177. cnt += 1
  178. continue
  179. tid = extract.video_id(c['IMG'])
  180. timg = "https://img.youtube.com/vi/" + tid+"/hqdefault.jpg"
  181. ad = {'imgUrl': timg, 'link': c['LK'],
  182. 'title': c['name'], 'description': c['TT']}
  183. a['data'].append(ad)
  184. x["data"].append(a)
  185. records = ExecuteQuery("""SELECT ctitle TT,clogo IMG, CONCAT('https://hhh.com.tw/columns/detail/',hcolumn_id,'/') LK, cdesc
  186. from _hcolumn
  187. WHERE onoff='1'
  188. AND NOW() > sdate
  189. ORDER BY hcolumn_id DESC
  190. LIMIT 3""")
  191. a = {'tab': '專欄文章', 'data': []}
  192. for c in records:
  193. ad = {'imgUrl': c['IMG'], 'link': c['LK'],
  194. 'title': c['TT'], 'description': c['cdesc']}
  195. a['data'].append(ad)
  196. x["data"].append(a)
  197. # print(x["data"])
  198. # 主題企劃區
  199. if x['id'] == 3:
  200. records = ExecuteQuery("""SELECT logo lo, CONCAT('https://hhh.com.tw/topic/detail/',htopic_id,'/') lk, `desc`, title FROM _htopic
  201. WHERE onoff = '1'
  202. ORDER BY htopic_id DESC limit 3""")
  203. x["data"] = []
  204. for c in records:
  205. a = {'imgUrl': c['lo'], 'link': str(
  206. c['lk']), 'video': 'false', 'description': c['desc'], 'title': c['title']}
  207. x["data"].append(a)
  208. # print(x["data"])
  209. # 編輯精選
  210. if x['id'] == 4:
  211. records = ExecuteQuery("""SELECT hcolumn_id, ctitle, clogo,cdesc
  212. FROM homepage_set
  213. LEFT JOIN _hcolumn ON mapping_id = hcolumn_id
  214. WHERE outer_set=8
  215. AND homepage_set.onoff='Y'
  216. AND(NOW() BETWEEN homepage_set.start_time AND homepage_set.end_time OR(homepage_set.start_time='0000-00-00 00:00:00' and homepage_set.end_time='0000-00-00 00:00:00') or (homepage_set.start_time is null and homepage_set.end_time is NULL))
  217. ORDER BY inner_sort""")
  218. x["data"] = []
  219. for c in records:
  220. a = {'imgUrl': c['clogo'], 'link': "https://hhh.com.tw/columns/detail/" + str(
  221. c['hcolumn_id']) + "/", 'title': c['ctitle'], 'video': 'false', 'description': c['cdesc']}
  222. x["data"].append(a)
  223. # print(x["data"])
  224. # 首列表廣告
  225. if x['id'] == 5:
  226. records = ExecuteQuery("""SELECT adlogo lo,adlogo_mobile mlo, adhref lk, adlogo_mobile_webp lomwebp, adlogo_webp dwebp FROM _had
  227. WHERE adtype LIKE '首列表廣告%'
  228. AND onoff='1'
  229. AND(NOW() BETWEEN start_time AND end_time OR(start_time='0000-00-00 00:00:00' and end_time='0000-00-00 00:00:00') or (start_time is null and end_time is NULL))
  230. ORDER BY adtype""")
  231. x["data"] = []
  232. for c in records:
  233. a = {'imgUrl': c['mlo'], 'link': str(
  234. c['lk']), 'DimgUrl': c['lo'], 'webp': str(c['lomwebp']), 'Dwebp': str(c['dwebp'])}
  235. x["data"].append(a)
  236. # print(x["data"])
  237. # 來選好物區
  238. if x['id'] == 6:
  239. records = ExecuteQuery(
  240. "SELECT max_row from outer_site_set WHERE title='來選好貨'")
  241. maxrow = 1
  242. for c in records:
  243. maxrow = c['max_row']
  244. records = ExecuteQuery("""(SELECT theme_type, mapping_id, IFNULL(ifnull(ifnull(_hcase.caption,_hcolumn.ctitle),_hproduct.name),_hvideo.title) COLLATE utf8_general_ci caption , IFNULL(ifnull(_hcase.cover,_hcolumn.clogo),_hproduct.cover) COLLATE utf8_general_ci J, iframe , IFNULL(ifnull(ifnull(_hcase.short_desc,_hcolumn.cdesc),_hproduct.descr),_hvideo.`desc`) COLLATE utf8_general_ci short_desc
  245. , (case when theme_type='case' then CONCAT('https://hhh.com.tw/cases/detail/d/',mapping_id) when theme_type='column' then CONCAT('https://hhh.com.tw/columns/detail/',mapping_id) when theme_type='product' then CONCAT('https://hhh.com.tw/product-post.php?id=',mapping_id) when theme_type='video' then CONCAT('https://hhh.com.tw/video-post.php?id=',mapping_id) ELSE '' END) url
  246. -- SELECT *
  247. FROM homepage_set
  248. left join _hcase ON _hcase.hcase_id=homepage_set.mapping_id AND theme_type='case'-- AND _hcase.onoff = '1'
  249. LEFT JOIN _hproduct ON mapping_id = _hproduct.id AND theme_type='product'-- AND _hproduct.onoff = '1'
  250. LEFT JOIN _hcolumn ON mapping_id = _hcolumn.hcolumn_id AND theme_type='column'-- AND _hcolumn.onoff = '1'
  251. LEFT JOIN _hvideo ON mapping_id = _hvideo.hvideo_id AND theme_type='video'
  252. WHERE homepage_set.onoff='Y'
  253. AND outer_set = (SELECT oss_id from outer_site_set WHERE title='來選好貨')
  254. AND(NOW() BETWEEN homepage_set.start_time AND homepage_set.end_time OR(homepage_set.start_time='0000-00-00 00:00:00' and homepage_set.end_time='0000-00-00 00:00:00') or (homepage_set.start_time is null and homepage_set.end_time is NULL))
  255. ORDER BY outer_set, inner_sort)
  256. UNION
  257. (SELECT 'product', id, `name`, cover, NULL ,descr ,CONCAT('https://hhh.com.tw/product-post.php?id=',id) FROM _hproduct WHERE onoff='1' ORDER BY id DESC LIMIT """ + str(maxrow) + """)
  258. LIMIT """ + str(maxrow))
  259. x["data"] = []
  260. for c in records:
  261. #print(c)
  262. if c['iframe'] is None:
  263. if isinstance(c['J'], bytearray) or isinstance(c['J'], bytes):
  264. c['J'] = c['J'].decode('utf8')
  265. if isinstance(c['caption'], bytearray) or isinstance(c['caption'], bytes):
  266. c['caption'] = c['caption'].decode('utf8')
  267. if isinstance(c['short_desc'], bytearray) or isinstance(c['short_desc'], bytes):
  268. c['short_desc'] = c['short_desc'].decode('utf8')
  269. a = {'imgUrl': c['J'], 'link': c['url'], 'title': c['caption'],
  270. 'description': c['short_desc'], 'video': 'false'}
  271. else:
  272. tid = extract.video_id(str(c['iframe']))
  273. timg = "https://img.youtube.com/vi/" + tid+"/hqdefault.jpg"
  274. ccaption = ""
  275. cdescription = ""
  276. if isinstance(c['caption'], bytearray):
  277. ccaption = str(c['caption'].decode('utf8'))
  278. else:
  279. ccaption = str(c['caption'])
  280. if c['short_desc'] is not None:
  281. if isinstance(c['short_desc'], bytes):
  282. cdescription = str(c['short_desc'].decode('utf8'))
  283. else:
  284. cdescription = str(c['short_desc'])
  285. a = {'imgUrl': timg, 'link': c['url'], 'title': ccaption,
  286. 'description': cdescription, 'video': tid}
  287. x["data"].append(a)
  288. # print(x["data"])
  289. # 本週推薦
  290. if x['id'] == 7:
  291. records = ExecuteQuery(
  292. "SELECT max_row from outer_site_set WHERE title='本週推薦'")
  293. maxrow = 1
  294. for c in records:
  295. maxrow = c['max_row']
  296. records = ExecuteQuery("""SELECT theme_type, mapping_id, IFNULL(ifnull(ifnull(_hcase.caption,_hcolumn.ctitle),_hproduct.name),_hvideo.title) caption , IFNULL(ifnull(_hcase.cover,_hcolumn.clogo),_hproduct.cover) J, iframe , IFNULL(ifnull(ifnull(_hcase.short_desc,_hcolumn.cdesc),_hproduct.descr),_hvideo.`desc`) short_desc
  297. , (case when theme_type='case' then CONCAT('https://hhh.com.tw/cases/detail/d/',mapping_id) when theme_type='column' then CONCAT('https://hhh.com.tw/columns/detail/',mapping_id) when theme_type='product' then CONCAT('https://hhh.com.tw/product-post.php?id=',mapping_id) when theme_type='video' then CONCAT('https://hhh.com.tw/video-post.php?id=',mapping_id) ELSE '' END) url
  298. -- SELECT *
  299. FROM homepage_set
  300. left join _hcase ON _hcase.hcase_id=homepage_set.mapping_id AND theme_type='case'-- AND _hcase.onoff = '1'
  301. LEFT JOIN _hproduct ON mapping_id = _hproduct.id AND theme_type='product'-- AND _hproduct.onoff = '1'
  302. LEFT JOIN _hcolumn ON mapping_id = _hcolumn.hcolumn_id AND theme_type='column'-- AND _hcolumn.onoff = '1'
  303. LEFT JOIN _hvideo ON mapping_id = _hvideo.hvideo_id AND theme_type='video'
  304. WHERE homepage_set.onoff='Y'
  305. AND outer_set = (SELECT oss_id from outer_site_set WHERE title='本週推薦')
  306. AND(NOW() BETWEEN homepage_set.start_time AND homepage_set.end_time OR(homepage_set.start_time='0000-00-00 00:00:00' and homepage_set.end_time='0000-00-00 00:00:00') or (homepage_set.start_time is null and homepage_set.end_time is NULL))
  307. ORDER BY outer_set, inner_sort
  308. LIMIT """ + str(maxrow))
  309. x["data"] = []
  310. for c in records:
  311. if c['iframe'] is None:
  312. if isinstance(c['J'], bytearray) or isinstance(c['J'], bytes):
  313. c['J'] = c['J'].decode('utf8')
  314. if isinstance(c['caption'], bytearray) or isinstance(c['caption'], bytes):
  315. c['caption'] = c['caption'].decode('utf8')
  316. if isinstance(c['short_desc'], bytearray) or isinstance(c['short_desc'], bytes):
  317. c['short_desc'] = c['short_desc'].decode('utf8')
  318. a = {'imgUrl': c['J'], 'link': c['url'], 'title': c['caption'],
  319. 'description': c['short_desc'], 'video': 'false'}
  320. else:
  321. tid = extract.video_id(str(c['iframe']))
  322. timg = "https://img.youtube.com/vi/" + tid+"/hqdefault.jpg"
  323. ccaption = ""
  324. cdescription = ""
  325. if isinstance(c['caption'], bytearray):
  326. ccaption = str(c['caption'].decode('utf8'))
  327. else:
  328. ccaption = str(c['caption'])
  329. if c['short_desc'] is not None:
  330. if isinstance(c['short_desc'], bytes):
  331. cdescription = str(c['short_desc'].decode('utf8'))
  332. else:
  333. cdescription = str(c['short_desc'])
  334. a = {'imgUrl': timg, 'link': c['url'], 'title': ccaption,
  335. 'description': cdescription, 'video': tid}
  336. x["data"].append(a)
  337. # print(x["data"])
  338. # 粉絲推薦
  339. if x['id'] == 8:
  340. records = ExecuteQuery(
  341. "SELECT max_row from outer_site_set WHERE title='粉絲推薦'")
  342. maxrow = 1
  343. for c in records:
  344. maxrow = c['max_row']
  345. records = ExecuteQuery("""SELECT theme_type, mapping_id, IFNULL(ifnull(ifnull(_hcase.caption,_hcolumn.ctitle),_hproduct.name),_hvideo.title) caption , IFNULL(ifnull(_hcase.cover,_hcolumn.clogo),_hproduct.cover) J, iframe , IFNULL(ifnull(ifnull(_hcase.short_desc,_hcolumn.cdesc),_hproduct.descr),_hvideo.`desc`) short_desc
  346. , (case when theme_type='case' then CONCAT('https://hhh.com.tw/cases/detail/d/',mapping_id) when theme_type='column' then CONCAT('https://hhh.com.tw/columns/detail/',mapping_id) when theme_type='product' then CONCAT('https://hhh.com.tw/product-post.php?id=',mapping_id) when theme_type='video' then CONCAT('https://hhh.com.tw/video-post.php?id=',mapping_id) ELSE '' END) url
  347. -- SELECT *
  348. FROM homepage_set
  349. left join _hcase ON _hcase.hcase_id=homepage_set.mapping_id AND theme_type='case'-- AND _hcase.onoff = '1'
  350. LEFT JOIN _hproduct ON mapping_id = _hproduct.id AND theme_type='product'-- AND _hproduct.onoff = '1'
  351. LEFT JOIN _hcolumn ON mapping_id = _hcolumn.hcolumn_id AND theme_type='column'-- AND _hcolumn.onoff = '1'
  352. LEFT JOIN _hvideo ON mapping_id = _hvideo.hvideo_id AND theme_type='video'
  353. WHERE homepage_set.onoff='Y'
  354. AND outer_set = (SELECT oss_id from outer_site_set WHERE title='粉絲推薦')
  355. AND(NOW() BETWEEN homepage_set.start_time AND homepage_set.end_time OR(homepage_set.start_time='0000-00-00 00:00:00' and homepage_set.end_time='0000-00-00 00:00:00') or (homepage_set.start_time is null and homepage_set.end_time is NULL))
  356. ORDER BY outer_set, inner_sort
  357. LIMIT """ + str(maxrow))
  358. x["data"] = []
  359. for c in records:
  360. if c['iframe'] is None:
  361. if isinstance(c['J'], bytearray) or isinstance(c['J'], bytes):
  362. c['J'] = c['J'].decode('utf8')
  363. if isinstance(c['caption'], bytearray) or isinstance(c['caption'], bytes):
  364. c['caption'] = c['caption'].decode('utf8')
  365. if isinstance(c['short_desc'], bytearray) or isinstance(c['short_desc'], bytes):
  366. c['short_desc'] = c['short_desc'].decode('utf8')
  367. a = {'imgUrl': c['J'], 'link': c['url'], 'title': c['caption'],
  368. 'description': c['short_desc'], 'video': 'false'}
  369. else:
  370. tid = extract.video_id(str(c['iframe']))
  371. timg = "https://img.youtube.com/vi/" + tid+"/hqdefault.jpg"
  372. ccaption = ""
  373. cdescription = ""
  374. if isinstance(c['caption'], bytearray):
  375. ccaption = str(c['caption'].decode('utf8'))
  376. else:
  377. ccaption = str(c['caption'])
  378. if c['short_desc'] is not None:
  379. if isinstance(c['short_desc'], bytes):
  380. cdescription = str(c['short_desc'].decode('utf8'))
  381. else:
  382. cdescription = str(c['short_desc'])
  383. a = {'imgUrl': timg, 'link': c['url'], 'title': ccaption,
  384. 'description': cdescription, 'video': tid}
  385. x["data"].append(a)
  386. # print(x["data"])
  387. if x['id'] == 9:
  388. records = ExecuteQuery(
  389. "SELECT id, (case when youtube_title = '' OR youtube_title IS NULL then (SELECT title FROM _hvideo ORDER BY hvideo_id DESC LIMIT 1) ELSE youtube_title END) T, (case when youtube_id = '' OR youtube_id IS NULL then (SELECT iframe FROM _hvideo ORDER BY hvideo_id DESC LIMIT 1) ELSE youtube_id end) Y FROM site_setup")
  390. for c in records:
  391. x['title'] = ""
  392. if isinstance(c['T'], bytearray):
  393. x['title'] = str(c['T'].decode('utf8'))
  394. else:
  395. x['title'] = str(c['T'])
  396. x['yt'] = extract.video_id(str(c['Y']))
  397. # print(id)
  398. if x['id'] == 10:
  399. records = ExecuteQuery(
  400. "SELECT all_search_tag ast FROM site_setup")
  401. x["data"] = []
  402. for c in records:
  403. x["data"] = c['ast'].split(',')
  404. # print(id)
  405. # print(jData)
  406. """ if not os.path.exists(hhhMBPath):
  407. os.mkdir(hhhMBPath)
  408. with open(hhhMBPath+'/json/' + filename, 'w', encoding='utf-8') as f:
  409. json.dump(jData, f, ensure_ascii=False, indent=4)
  410. if not os.path.exists(hhhPCPath):
  411. os.mkdir(hhhPCPath)
  412. with open(hhhPCPath+'/json/' + filename, 'w', encoding='utf-8') as f:
  413. json.dump(jData, f, ensure_ascii=False, indent=4) """
  414. return jData
  415. @app.get("/gencase")
  416. def gencase(id: str = "14151", sort: str = "new", page: str="1"):
  417. with dataset.connect(connstr) as db:
  418. jData = json.load(open(hhhMBPath+'/json/cases.json', encoding='utf8'))
  419. records = db.query("""SELECT *, c.style cstyle, c.style2 cstyle2 FROM _hcase c
  420. LEFT JOIN _hdesigner d ON c.hdesigner_id = d.hdesigner_id
  421. WHERE c.hcase_id = '""" + id + """' AND c.onoff='1' AND d.onoff='1' and c.sdate < now() """)
  422. # print(jData)
  423. for x in jData:
  424. tmpCaseDetail = []
  425. icount = 0
  426. for c in records:
  427. icount += 1
  428. #tmpCaseDetail.append({"CaseDetailImg": c["cimg"]})
  429. #x["CaseDetail"] = tmpCaseDetail
  430. if c != None:
  431. x["designerid"] = str(c["hdesigner_id"])
  432. x["CaseId"] = str(c["hcase_id"])
  433. x["Casetitle"] = c["caption"]
  434. x["CaseTeamName"] = c["name"]
  435. x["CaseCompany"] = c["title"]
  436. x["CaseCompanyAddress"] = c["address"]
  437. x["CaseCompanyTel"] = c["phone"]
  438. x["CaseCompanyEmail"] = c["mail"]
  439. x["CaseCompanyWeb"] = c["website"]
  440. x["CaseDate"] = str(c["sdate"])
  441. x["CaseViews"] = c["viewed"]
  442. x["CaseCoverImg"] = c["cover"]
  443. x["CaseImgAmount"] = icount
  444. x["CaseStyle"] = c["cstyle"]
  445. x["CaseHouse"] = c["layout"]
  446. x["CaseSize"] = c["area"]
  447. x["CaseProject"] = ""
  448. x["CaseDataMember"] = c["member"]
  449. x["CaseDataSize"] = c["area"]
  450. x["CaseDataStyle"] = c["cstyle"] + c["cstyle2"]
  451. x["CaseDataType"] = c["type"]
  452. x["CaseDataSituation"] = c["condition"]
  453. x["CaseDataImgProvide"] = c["provider"]
  454. x["CaseDataSpace"] = c["layout"]
  455. x["CaseDataMaterial"] = c["materials"]
  456. x["ContactFreeTel"] = c["service_phone"]
  457. x["ContactDesignerImg"] = c["img_path"]
  458. x["CasePageLink"] = ""
  459. x["CasePageprev"] = ""
  460. #x["CaseTag"]= []
  461. #相同設計師的個案
  462. sql = """SELECT * FROM _hcase c
  463. WHERE hdesigner_id = '""" + x["designerid"] + """' and hcase_id <> '""" + x["CaseId"] + """' and sdate < now() AND c.onoff='1'
  464. ORDER BY """ + ("sdate" if sort == 'new' else 'viewed') + """ DESC
  465. LIMIT """ + str((int(page) - 1)*12) + """,12
  466. """
  467. cases = db.query(sql)
  468. tmpOtherCases = []
  469. for other in cases:
  470. tmpOtherCase = {}
  471. tmpOtherCase["designerid"] = str(other["hdesigner_id"])
  472. tmpOtherCase["casesid"] = str(other["hcase_id"])
  473. tmpOtherCase["Views"] = other["viewed"]
  474. tmpOtherCase["ProfileImg"] = other["cover"]
  475. tmpTags = []
  476. for tag in other["tag"].split(','):
  477. tmpTags.append({"Tag": tag , "TagLink": "" })
  478. tmpOtherCase["ProfileTag"] = tmpTags
  479. tmpOtherCases.append(tmpOtherCase)
  480. x["DesignerProfile"] = tmpOtherCases
  481. #相同風格的個案
  482. sql = """SELECT * FROM _hcase c
  483. WHERE style = '""" + x["CaseStyle"] + """' and hcase_id <> '""" + x["CaseId"] + """' and sdate < now() AND c.onoff='1'
  484. ORDER BY """ + ("sdate" if sort == 'new' else 'viewed') + """ DESC
  485. LIMIT """ + str((int(page) - 1)*12) + """,12
  486. """
  487. cases = db.query(sql)
  488. tmpOtherCases = []
  489. for other in cases:
  490. tmpOtherCase = {}
  491. tmpOtherCase["designerid"] = str(other["hdesigner_id"])
  492. tmpOtherCase["casesid"] = str(other["hcase_id"])
  493. tmpOtherCase["Views"] = other["viewed"]
  494. tmpOtherCase["ProfileImg"] = other["cover"]
  495. tmpTags = []
  496. for tag in other["tag"].split(','):
  497. tmpTags.append({"Tag": tag , "TagLink": "" })
  498. tmpOtherCase["ProfileTag"] = tmpTags
  499. tmpOtherCases.append(tmpOtherCase)
  500. x["StyleProfile"] = tmpOtherCases
  501. #相同風格的RANDOM 10筆
  502. #cases = db.query("""SELECT * FROM _hcase c
  503. #WHERE style = '""" + x["CaseStyle"] + """' and hcase_id <> '""" + x["CaseId"] + """' and sdate < now() AND c.onoff='1'
  504. #ORDER BY RAND()
  505. #LIMIT 10
  506. #""")
  507. """ tmpOtherCases = []
  508. for other in cases:
  509. tmpOtherCase = {}
  510. tmpOtherCase["designerid"] = str(other["hdesigner_id"])
  511. tmpOtherCase["casesid"] = str(other["hcase_id"])
  512. tmpOtherCase["PortfoliolImg"] = other["cover"]
  513. tmpOtherCase["PortfoliolLink"] = ""
  514. tmpOtherCase["PortfoliolImgAlt"] = other["caption"]
  515. tmpOtherCases.append(tmpOtherCase)
  516. x["OtherStylePortfolio"]= tmpOtherCases """
  517. # print(x)
  518. # print(jData)
  519. """ if not os.path.exists(hhhMBPath):
  520. os.mkdir(hhhMBPath)
  521. with open(hhhMBPath+'/json/cases-' + id + '.json', 'w', encoding='utf-8') as f:
  522. json.dump(jData, f, ensure_ascii=False, indent=4) """
  523. return jData
  524. @app.get("/gendesigner")
  525. def gendesigner(id: str = "447", sort: str = "new", page: str = "1"):
  526. with dataset.connect(connstr) as db:
  527. jData = json.load(open(hhhMBPath+'/json/designers.json', encoding='utf8'))
  528. records = db.query("""SELECT * FROM _hdesigner d
  529. WHERE d.hdesigner_id = '""" + id + """' AND d.onoff='1' """)
  530. # print(jData)
  531. for x in jData:
  532. tmpCaseDetail = []
  533. icount = 0
  534. for c in records:
  535. icount += 1
  536. # tmpCaseDetail.append({"CaseDetailImg":c["cimg"]})
  537. if page == "1":
  538. x["id"] = c["hdesigner_id"]
  539. x["BannerImg"] = c["background"]
  540. x["CompanyName"] = c["title"]
  541. x["DesignerName"] = c["name"]
  542. x["Designerimg"] = c["img_path"]
  543. x["Description"] = c["seo"]
  544. x["Approve"] = c["position"]
  545. x["FB_link"] = c["fbpageurl"]
  546. x["Basics"] = [
  547. {"title": "免費專線:",
  548. "link": c["service_phone"], "data": c["service_phone"]},
  549. {"title": "諮詢專線:", "link": c["phone"], "data": c["phone"]},
  550. {"title": "諮詢專線:", "link": c["phone"], "data": c["phone"]},
  551. {"title": "公司傳真:", "link": c["fax"], "data": c["fax"]},
  552. {"title": "公司地址:", "link": c["address"], "data": c["address"]},
  553. {"title": "電子信箱:", "link": c["mail"], "data": c["mail"]},
  554. {"title": "公司網址:", "link": c["website"], "data": c["website"]}
  555. ]
  556. x["FreeCall"] = c["service_phone"]
  557. x["ConsoleCall_1"] = c["phone"]
  558. x["ConsoleCall_2"] = c["phone"]
  559. x["Fax"] = c["fax"]
  560. x["Address"] = c["address"]
  561. x["Email"] = c["mail"]
  562. x["Web"] = c["website"]
  563. x["Branches"] = []
  564. branches = db.query("""SELECT * FROM designer_branch br
  565. WHERE br.designer_id = '""" + id + """' """)
  566. for branch in branches:
  567. tmpobj = {
  568. "title": branch["title"],
  569. "address": branch["address"],
  570. "tel": branch["tel"],
  571. "fax": branch["fax"]
  572. }
  573. x["Branches"].append(tmpobj)
  574. x["Budget"] = c["budget"]
  575. x["Square"] = c["area"]
  576. x["SpecialCase"] = c["special"]
  577. x["Charge"] = c["charge"]
  578. x["Pay"] = c["payment"]
  579. x["WorkLoc"] = c["region"]
  580. x["WorkType"] = c["type"]
  581. x["WorkStyle"] = c["style"]
  582. x["WorkBudget"] = c["budget"]
  583. x["Terms"] = [
  584. {"title": "接案預算:", "data": c["budget"]},
  585. {"title": "接案坪數:", "data": c["area"]},
  586. {"title": "特殊接案:", "data": c["special"]},
  587. {"title": "收費方式:", "data": c["charge"]},
  588. {"title": "付費方式:", "data": c["payment"]},
  589. {"title": "接案區域:", "data": c["region"]},
  590. {"title": "接案類型:", "data": c["type"]},
  591. {"title": "接案風格:", "data": c["style"]}
  592. ]
  593. x["scMedia"] = [
  594. {"name": "Facebook", "img": "https://hhh.com.tw/assets/images/rv_web/fb.svg",
  595. "link": c["fbpageurl"]},
  596. {"name": "Line", "img": "https://hhh.com.tw/assets/images/rv_web/line.svg",
  597. "link": c["line_link"]},
  598. {"name": "Wechat", "img": "https://hhh.com.tw/assets/images/rv_web/wechat.svg",
  599. "link": c["fbpageurl"]},
  600. {"name": "email", "img": "https://hhh.com.tw/assets/images/rv_web/share.svg",
  601. "link": c["mail"]},
  602. {"name": "Like", "img": "https://hhh.com.tw/assets/images/rv_web/like-o.svg", "link": ""}
  603. ]
  604. x["Content"] = [
  605. {
  606. "Title": "設計師作品",
  607. "mb_title": "作品",
  608. "Tabtag": "intro",
  609. "Display_mb": "true",
  610. "isActive": "true",
  611. "Carddata": []
  612. },
  613. {
  614. "Title": "設計師影音",
  615. "mb_title": "影音",
  616. "Tabtag": "video",
  617. "Display_mb": "true",
  618. "isActive": "true",
  619. "Carddata": []
  620. },
  621. {
  622. "Title": "設計師專欄",
  623. "mb_title": "專欄",
  624. "Tabtag": "columns",
  625. "Display_mb": "true",
  626. "isActive": "true",
  627. "Carddata": []
  628. },
  629. {
  630. "Title": "VR360",
  631. "mb_title": "",
  632. "Tabtag": "vr360",
  633. "Display_mb": "false",
  634. "isActive": "true",
  635. "Carddata": []
  636. },
  637. {
  638. "Title": "設計師公司簡介",
  639. "mb_title": "公司簡介",
  640. "Tabtag": "company",
  641. "Display_mb": "true",
  642. "isActive": "true",
  643. "Carddata": [],
  644. "info": [
  645. {"title": "設計理念", "data": c["idea"]},
  646. {"title": "公司統編", "data": c["taxid"]},
  647. {"title": "相關經歷", "data": c["career"]},
  648. {"title": "專業證照", "data": c["license"]},
  649. {"title": "獲獎紀錄", "data": c["awards"]}
  650. ]
  651. }
  652. ]
  653. # 設計師作品
  654. x["Content"][0]["Carddata"] = []
  655. cases = db.query("""SELECT tag,cover,caption,hcase_id,viewed,sdate FROM _hcase c
  656. WHERE c.hdesigner_id = '""" + id + """' AND c.onoff='1'
  657. ORDER BY """ + ("sdate" if sort == 'new' else 'viewed') + """ DESC
  658. LIMIT """ + str((int(page) - 1)*12) + """,12
  659. """)
  660. for case in cases:
  661. tmpobj = {
  662. "url": "https://hhh.com.tw/cases/detail/d/"+str(case["hcase_id"]),
  663. "imgURL": case["cover"],
  664. "title": case["caption"],
  665. "tag": [{"name": tag, "link": ""} for tag in case["tag"].split(',')],
  666. "views": case["viewed"],
  667. "dateSort": str(case["sdate"])
  668. }
  669. x["Content"][0]["Carddata"].append(tmpobj)
  670. # 設計師影音
  671. # https://i.ytimg.com/vi/y6VmaLC7O9Y/hqdefault.jpg
  672. x["Content"][1]["Carddata"] = []
  673. videos = db.query("""SELECT tag_vpattern,iframe,title,hvideo_id,viewed,display_datetime FROM _hvideo v
  674. WHERE v.hdesigner_id = '""" + id + """' AND display_datetime < NOW()
  675. ORDER BY """ + ("display_datetime" if sort == 'new' else 'viewed') + """ DESC
  676. LIMIT """ + str((int(page) - 1)*12) + """,12
  677. """)
  678. for video in videos:
  679. tmpobj = {
  680. "url": "https://hhh.com.tw/video-post.php?id="+str(video['hvideo_id']),
  681. "imgURL": "https://i.ytimg.com/vi/" + extract.video_id(str(video['iframe']))+"/hqdefault.jpg",
  682. "title": video["title"],
  683. "tag": [{"name": tag, "link": ""} for tag in video["tag_vpattern"].split(',')],
  684. "views": video["viewed"],
  685. "dateSort": str(video["display_datetime"])
  686. }
  687. x["Content"][1]["Carddata"].append(tmpobj)
  688. # 設計師專欄
  689. x["Content"][2]["Carddata"] = []
  690. columns = db.query("""SELECT tag,clogo,ctitle,hcolumn_id,viewed,sdate FROM _hcolumn c
  691. WHERE onoff=1 AND (hdesigner_ids LIKE '""" + id + """,%' OR hdesigner_ids LIKE '%,""" + id + """,%' OR hdesigner_ids LIKE '%,""" + id + """' OR hdesigner_ids = '""" + id + """')
  692. ORDER BY """ + ("sdate" if sort == 'new' else 'viewed') + """ DESC
  693. LIMIT """ + str((int(page) - 1)*12) + """,12
  694. """)
  695. for column in columns:
  696. tmpobj = {
  697. "url": "https://hhh.com.tw/video-post.php?id="+str(video['hvideo_id']),
  698. "imgURL": column['clogo'],
  699. "title": column["ctitle"],
  700. "tag": [] if not column["tag"] else [{"name": tag, "link": ""} for tag in column["tag"].split(',')],
  701. "views": column["viewed"],
  702. "dateSort": str(column["sdate"])
  703. }
  704. x["Content"][2]["Carddata"].append(tmpobj)
  705. # VR360
  706. x["Content"][3]["Carddata"] = []
  707. cases = db.query("""SELECT tag,cover,caption,hcase_id,viewed,sdate FROM _hcase c
  708. WHERE c.hdesigner_id = '""" + id + """' and istaging != '' AND c.onoff='1'
  709. ORDER BY """ + ("sdate" if sort == 'new' else 'viewed') + """ DESC
  710. LIMIT """ + str((int(page) - 1)*12) + """,12
  711. """)
  712. for case in cases:
  713. tmpobj = {
  714. "url": "https://hhh.com.tw/cases/detail/d/"+str(case["hcase_id"]),
  715. "imgURL": case["cover"],
  716. "title": case["caption"],
  717. "tag": [{"name": tag, "link": ""} for tag in case["tag"].split(',')],
  718. "views": case["viewed"],
  719. "dateSort": str(case["sdate"])
  720. }
  721. x["Content"][3]["Carddata"].append(tmpobj)
  722. # 設計公司簡介
  723. #x["Content"][4]["Carddata"] = []
  724. #cases = db.query("")
  725. """ for case in cases:
  726. tmpobj = {
  727. "imgURL":case["cover"],
  728. "title":case["caption"],
  729. "tag":[{"name": tag, "link": ""} for tag in case["tag"].split(',')],
  730. "views":case["viewed"],
  731. "dateSort":str(case["sdate"])
  732. }
  733. x["Content"][4]["Carddata"].append(tmpobj) """
  734. # print(x)
  735. # print(jData)
  736. """ if not os.path.exists(hhhMBPath):
  737. os.mkdir(hhhMBPath)
  738. with open(hhhMBPath+'/json/designers-' + id + '.json', 'w', encoding='utf-8') as f:
  739. json.dump(jData, f, ensure_ascii=False, indent=4) """
  740. return jData
  741. @app.get("/gencolumn")
  742. def gencolumn(id: str = "6392", sort: str = "new", page: str="1"):
  743. with dataset.connect(connstr) as db:
  744. jData = json.load(open(hhhMBPath+'/json/Columns.json', encoding='utf8'))
  745. records = db.query("""SELECT * FROM _hcolumn c
  746. WHERE c.hcolumn_id = '""" + id + """' AND c.onoff='1' """)
  747. #print(id)
  748. for x in jData:
  749. icount = 0
  750. c = None
  751. for c in records:
  752. icount += 1
  753. if c != None:
  754. x["Columnsid"] = str(c["hcolumn_id"])
  755. x["Columnstitle"] = c["ctitle"]
  756. x["ColumnsCoverImg"] = c["clogo"]
  757. x["ColumnsDate"] = str(c["sdate"])
  758. x["ColumnsViews"] = str(c["viewed"])
  759. if page == "1":
  760. x["ColumnsContent"] = c["page_content"]
  761. tmpTags = []
  762. for tag in c["ctag"].split(','):
  763. tmpTags.append({"Tag": tag})
  764. x["ColumnsTag"] = tmpTags
  765. x["author_inf"] = c["extend_str"]
  766. #相同類別的最新12筆
  767. sql = """SELECT * FROM _hcolumn c
  768. WHERE (c.ctype like '%""" + str(c["ctype"]) + """%' and c.ctype_sub like '%""" + str(c["ctype_sub"]) + """%') and hcolumn_id <> '""" + str(c["hcolumn_id"]) + """' and sdate < now() AND c.onoff='1'
  769. ORDER BY """ + ("sdate" if sort == 'new' else 'viewed') + """ DESC
  770. LIMIT """ + str((int(page) - 1)*12) + """,12
  771. """
  772. ctypes = db.query(sql)
  773. tmpOtherCols = []
  774. for other in ctypes:
  775. tmpOtherCol = {}
  776. tmpOtherCol["Columnsid"] = str(other["hcolumn_id"])
  777. tmpOtherCol["ColumnsCoverImg"] = other["clogo"]
  778. tmpOtherCol["Views"] = other["viewed"]
  779. tmpOtherCol["Columnstitle"] = other["ctitle"]
  780. tmpTags = []
  781. for tag in other["ctag"].split(','):
  782. tmpTags.append({"Tag": tag})
  783. tmpOtherCol["ColumnsTag"] = tmpTags
  784. tmpOtherCols.append(tmpOtherCol)
  785. x["OtherColumns"] = tmpOtherCols
  786. #print(x)
  787. # print(jData)
  788. """ if not os.path.exists(hhhMBPath):
  789. os.mkdir(hhhMBPath)
  790. with open(hhhMBPath+'/json/Columns-' + id + '.json', 'w', encoding='utf-8') as f:
  791. json.dump(jData, f, ensure_ascii=False, indent=4) """
  792. return jData
  793. @app.get("/getColumnAds")
  794. def getColumnAds():
  795. with dataset.connect(connstr) as db:
  796. ads = []
  797. records = db.query("""SELECT adlogo_mobile imgUrl, adlogo DimgUrl, adhref link
  798. FROM _had hh
  799. WHERE adtype LIKE '專欄首大%'
  800. AND hh.onoff='1'
  801. and NOW() BETWEEN start_time AND end_time
  802. ORDER BY cast(SUBSTR(adtype, 4) AS DECIMAL) """)
  803. """ for x in records:
  804. ads.append(x) """
  805. ads.extend(records)
  806. rData = json.loads(json.dumps(ads))
  807. #print(json.dumps(ads))
  808. return rData
  809. #print(getColumnAds())
  810. """ if __name__ == "__main__":
  811. uvicorn.run(app, host="0.0.0.0", port=8000) """