genjson.py 64 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321
  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 html
  16. import json
  17. from pytube import extract
  18. import re
  19. from fastapi import BackgroundTasks, FastAPI
  20. app = FastAPI()
  21. origins = [
  22. "*"
  23. ]
  24. app.add_middleware(
  25. CORSMiddleware,
  26. allow_origins=origins,
  27. allow_credentials=True,
  28. allow_methods=["*"],
  29. allow_headers=["*"],
  30. )
  31. hhhMBPath = '../hhh-home-mb'
  32. hhhPCPath = '../hhh-home-pc'
  33. # connstr = 'mysql://hhh7796hhh:lYmWsu^ujcA1@hhh-v57.cmab1ctkglka.ap-northeast-2.rds.amazonaws.com:3306/xoops?charset=utf8mb4'
  34. #2022/12/13 change
  35. connstr = 'mysql://hhh7796hhh:lYmWsu^ujcA1@ec2-3-35-26-49.ap-northeast-2.compute.amazonaws.com:3306/xoops?charset=utf8mb4'
  36. def ExecuteQuery(isql):
  37. #2022/12/13 change
  38. #host='hhh-v57.cmab1ctkglka.ap-northeast-2.rds.amazonaws.com',
  39. with mysql.connector.connect(
  40. host='ec2-3-35-26-49.ap-northeast-2.compute.amazonaws.com',
  41. database='xoops',
  42. user='hhh7796hhh',
  43. password='lYmWsu^ujcA1',
  44. use_unicode=True,
  45. charset='utf8',
  46. collation='utf8_unicode_ci'
  47. ) as connection :
  48. with connection.cursor(dictionary=True) as cursor:
  49. # connection.set_charset_collation('utf8','utf8_general_ci')
  50. #cursor = connection.cursor(dictionary=True)
  51. cursor.execute(isql)
  52. return cursor.fetchall()
  53. def ExecuteCmd(isql):
  54. #2022/12/13 change
  55. #host='hhh-v57.cmab1ctkglka.ap-northeast-2.rds.amazonaws.com',
  56. with mysql.connector.connect(
  57. host='ec2-3-35-26-49.ap-northeast-2.compute.amazonaws.com',
  58. database='xoops',
  59. user='hhh7796hhh',
  60. password='lYmWsu^ujcA1',
  61. use_unicode=True,
  62. charset='utf8',
  63. collation='utf8_unicode_ci'
  64. ) as connection:
  65. cursor = connection.cursor(dictionary=True)
  66. cursor.execute(isql)
  67. print(cursor.rowcount)
  68. connection.commit()
  69. return None
  70. @app.get("/ExportExecuteDetail")
  71. async def ExportExecuteDetail():
  72. with dataset.connect(connstr) as db:
  73. output = BytesIO()
  74. 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
  75. left join execute_detail d on f.exf_id=d.exf_id
  76. where f.is_delete='N' order BY f.exf_id DESC, exd_id
  77. """)
  78. df = pd.DataFrame(list(records))
  79. writer = pd.ExcelWriter(output)
  80. df.to_excel(writer, sheet_name='bar')
  81. writer.save()
  82. """ workbook = xlsxwriter.Workbook(output)
  83. worksheet = workbook.add_worksheet()
  84. for cols in records:
  85. worksheet.write(0, 0, 'ISBN')
  86. worksheet.write(0, 1, 'Name')
  87. worksheet.write(0, 2, 'Takedown date')
  88. worksheet.write(0, 3, 'Last updated')
  89. workbook.close() """
  90. output.seek(0)
  91. headers = {
  92. 'Content-Disposition': 'attachment; filename="execute_detail_all.xlsx"'
  93. }
  94. return StreamingResponse(output, headers=headers, media_type='application/octet-stream')
  95. @app.get("/")
  96. def read_root():
  97. return {"Hello": "World"}
  98. @app.get("/movexoopstostage")
  99. def movexoopstostage(designerid: str = "0", caseid: str = "0"):
  100. with dataset.connect(connstr) as db:
  101. db.query(
  102. "replace INTO stage._hdesigner SELECT * FROM xoops._hdesigner WHERE hdesigner_id IN ('" + designerid.replace(',', "','")+"');")
  103. db.query(
  104. "replace INTO stage._hcase SELECT * FROM xoops._hcase WHERE hcase_id IN ('"+caseid.replace(',', "','")+"');")
  105. db.query(
  106. "replace INTO stage._hcase_img SELECT * FROM xoops._hcase_img WHERE hcase_id IN ('"+caseid.replace(',', "','")+"');")
  107. return {"success"}
  108. @app.get("/movepxoopstostage")
  109. def movepxoopstostage(brandid: str = "0", productid: str = "0"):
  110. with dataset.connect(connstr) as db:
  111. db.query(
  112. "replace INTO stage._hbrand SELECT * FROM xoops._hbrand WHERE hbrand_id IN ('" + brandid.replace(',', "','")+"');")
  113. db.query(
  114. "replace INTO stage._hbrand_page SELECT * FROM xoops._hbrand_page WHERE hbrand_id IN ('" + brandid.replace(',', "','")+"');")
  115. db.query(
  116. "replace INTO stage._hproduct SELECT * FROM xoops._hproduct WHERE id IN ('"+productid.replace(',', "','")+"');")
  117. db.query(
  118. "replace INTO stage._hproduct_img SELECT * FROM xoops._hproduct_img WHERE hproduct_id IN ('"+productid.replace(',', "','")+"');")
  119. return {"success"}
  120. @app.get("/movecxoopstostage")
  121. def movecxoopstostage(columnid: str = "0"):
  122. with dataset.connect(connstr) as db:
  123. db.query(
  124. "replace INTO stage._hcolumn SELECT * FROM xoops._hcolumn WHERE hcolumn_id IN ('" + columnid.replace(',', "','")+"');")
  125. db.query(
  126. "replace INTO stage._hcolumn_img SELECT * FROM xoops._hcolumn_img WHERE hcolumn_id IN ('" + columnid.replace(',', "','")+"');")
  127. db.query(
  128. "replace INTO stage._hcolumn_page SELECT * FROM xoops._hcolumn_page WHERE hcolumn_id IN ('" + columnid.replace(',', "','")+"');")
  129. return {"success"}
  130. @app.get("/genjson")
  131. def genjson(filename: str = "realtime.json"):
  132. jData = json.load(open(hhhMBPath+'/json/data.json', encoding='utf8'))
  133. 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 '首八大%' ")
  134. for x in jData:
  135. # 頂部輪播區-新刊頭
  136. if x['id'] == 0:
  137. records = ExecuteQuery("""SELECT adlogo lo,adlogo_mobile mlo, adhref lk, adlogo_mobile_webp lomwebp, adlogo_webp dwebp FROM _had
  138. WHERE adtype LIKE '新刊頭%'
  139. AND onoff='1'
  140. 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))
  141. ORDER BY cast(SUBSTR(adtype,4) AS DECIMAL)""")
  142. x["data"] = []
  143. for c in records:
  144. a = {'imgUrl': c['mlo'], 'link': str(
  145. c['lk']), 'DimgUrl': c['lo'], 'webp': str(c['lomwebp']), 'Dwebp': str(c['dwebp'])}
  146. x["data"].append(a)
  147. # print(x["data"])
  148. # 主要輪播區-首八大
  149. if x['id'] == 1:
  150. records = ExecuteQuery("""SELECT adlogo lo,adlogo_mobile mlo, adhref lk, adlogo_mobile_webp lomwebp, adlogo_webp dwebp FROM _had
  151. WHERE adtype LIKE '首八大%'
  152. AND onoff='1'
  153. 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))
  154. ORDER BY cast(SUBSTR(adtype,4) AS DECIMAL)""")
  155. x["data"] = []
  156. for c in records:
  157. a = {'imgUrl': c['mlo'], 'link': str(
  158. c['lk']), 'DimgUrl': c['lo'], 'webp': str(c['lomwebp']), 'Dwebp': str(c['dwebp'])}
  159. x["data"].append(a)
  160. # print(x["data"])
  161. #tab區塊-最夯設計, 影音實錄, 專欄文章
  162. if x['id'] == 2:
  163. x["data"] = []
  164. records = ExecuteQuery("""SELECT caption TT ,cover IMG, CONCAT('https://hhh.com.tw/cases/detail/',hcase_id,'/') LK, short_desc txt
  165. from _hcase
  166. left join _hdesigner ON _hcase.hdesigner_id=_hdesigner.hdesigner_id
  167. WHERE
  168. _hcase.onoff='1' AND _hdesigner.onoff='1'
  169. AND(NOW() > sdate)
  170. ORDER BY hcase_id DESC
  171. LIMIT 3""")
  172. a = {'tab': '最夯設計', 'data': []}
  173. for c in records:
  174. ad = {'imgUrl': c['IMG'], 'link': c['LK'],
  175. 'title': c['TT'], 'description': c['txt']}
  176. a['data'].append(ad)
  177. x["data"].append(a)
  178. records = ExecuteQuery("""SELECT title TT,iframe IMG , CONCAT('https://hhh.com.tw/video-post.php?id=',hvideo_id) LK , name
  179. from _hvideo where display_datetime < NOW()
  180. ORDER BY hvideo_id DESC
  181. LIMIT 4""")
  182. a = {'tab': '影音實錄', 'data': []}
  183. cnt = 0
  184. for c in records:
  185. if cnt == 0:
  186. cnt += 1
  187. continue
  188. tid = extract.video_id(c['IMG'])
  189. timg = "https://img.youtube.com/vi/" + tid+"/hqdefault.jpg"
  190. ad = {'imgUrl': timg, 'link': c['LK'],
  191. 'title': c['name'], 'description': c['TT']}
  192. a['data'].append(ad)
  193. x["data"].append(a)
  194. records = ExecuteQuery("""SELECT ctitle TT,clogo IMG, CONCAT('https://hhh.com.tw/columns/detail/',hcolumn_id,'/') LK, cdesc
  195. from _hcolumn
  196. WHERE onoff='1'
  197. AND NOW() > sdate
  198. ORDER BY hcolumn_id DESC
  199. LIMIT 3""")
  200. a = {'tab': '專欄文章', 'data': []}
  201. for c in records:
  202. ad = {'imgUrl': c['IMG'], 'link': c['LK'],
  203. 'title': c['TT'], 'description': c['cdesc']}
  204. a['data'].append(ad)
  205. x["data"].append(a)
  206. # print(x["data"])
  207. # 主題企劃區
  208. if x['id'] == 3:
  209. records = ExecuteQuery("""SELECT logo lo, CONCAT('https://hhh.com.tw/topic/detail/',htopic_id,'/') lk, `desc`, title FROM _htopic
  210. WHERE onoff = '1'
  211. ORDER BY htopic_id DESC limit 3""")
  212. x["data"] = []
  213. for c in records:
  214. a = {'imgUrl': c['lo'], 'link': str(
  215. c['lk']), 'video': 'false', 'description': c['desc'], 'title': c['title']}
  216. x["data"].append(a)
  217. # print(x["data"])
  218. # 編輯精選
  219. if x['id'] == 4:
  220. records = ExecuteQuery("""SELECT hcolumn_id, ctitle, clogo,cdesc
  221. FROM homepage_set
  222. LEFT JOIN _hcolumn ON mapping_id = hcolumn_id
  223. WHERE outer_set=8
  224. AND homepage_set.onoff='Y'
  225. 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))
  226. ORDER BY inner_sort""")
  227. x["data"] = []
  228. for c in records:
  229. a = {'imgUrl': c['clogo'], 'link': "https://hhh.com.tw/columns/detail/" + str(
  230. c['hcolumn_id']) + "/", 'title': c['ctitle'], 'video': 'false', 'description': c['cdesc']}
  231. x["data"].append(a)
  232. # print(x["data"])
  233. # 首列表廣告
  234. if x['id'] == 5:
  235. records = ExecuteQuery("""SELECT adlogo lo,adlogo_mobile mlo, adhref lk, adlogo_mobile_webp lomwebp, adlogo_webp dwebp FROM _had
  236. WHERE adtype LIKE '首列表廣告%'
  237. AND onoff='1'
  238. 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))
  239. ORDER BY adtype""")
  240. x["data"] = []
  241. for c in records:
  242. a = {'imgUrl': c['mlo'], 'link': str(
  243. c['lk']), 'DimgUrl': c['lo'], 'webp': str(c['lomwebp']), 'Dwebp': str(c['dwebp'])}
  244. x["data"].append(a)
  245. # print(x["data"])
  246. # 來選好物區
  247. if x['id'] == 6:
  248. records = ExecuteQuery(
  249. "SELECT max_row from outer_site_set WHERE title='來選好貨'")
  250. maxrow = 1
  251. for c in records:
  252. maxrow = c['max_row']
  253. 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
  254. , (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
  255. -- SELECT *
  256. FROM homepage_set
  257. left join _hcase ON _hcase.hcase_id=homepage_set.mapping_id AND theme_type='case'-- AND _hcase.onoff = '1'
  258. LEFT JOIN _hproduct ON mapping_id = _hproduct.id AND theme_type='product'-- AND _hproduct.onoff = '1'
  259. LEFT JOIN _hcolumn ON mapping_id = _hcolumn.hcolumn_id AND theme_type='column'-- AND _hcolumn.onoff = '1'
  260. LEFT JOIN _hvideo ON mapping_id = _hvideo.hvideo_id AND theme_type='video'
  261. WHERE homepage_set.onoff='Y'
  262. AND outer_set = (SELECT oss_id from outer_site_set WHERE title='來選好貨')
  263. 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))
  264. ORDER BY outer_set, inner_sort)
  265. UNION
  266. (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) + """)
  267. LIMIT """ + str(maxrow))
  268. x["data"] = []
  269. for c in records:
  270. #print(c)
  271. if c['iframe'] is None:
  272. if isinstance(c['J'], bytearray) or isinstance(c['J'], bytes):
  273. c['J'] = c['J'].decode('utf8')
  274. if isinstance(c['caption'], bytearray) or isinstance(c['caption'], bytes):
  275. c['caption'] = c['caption'].decode('utf8')
  276. if isinstance(c['short_desc'], bytearray) or isinstance(c['short_desc'], bytes):
  277. c['short_desc'] = c['short_desc'].decode('utf8')
  278. a = {'imgUrl': c['J'], 'link': c['url'], 'title': c['caption'],
  279. 'description': c['short_desc'], 'video': 'false'}
  280. else:
  281. tid = extract.video_id(str(c['iframe']))
  282. timg = "https://img.youtube.com/vi/" + tid+"/hqdefault.jpg"
  283. ccaption = ""
  284. cdescription = ""
  285. if isinstance(c['caption'], bytearray):
  286. ccaption = str(c['caption'].decode('utf8'))
  287. else:
  288. ccaption = str(c['caption'])
  289. if c['short_desc'] is not None:
  290. if isinstance(c['short_desc'], bytes):
  291. cdescription = str(c['short_desc'].decode('utf8'))
  292. else:
  293. cdescription = str(c['short_desc'])
  294. a = {'imgUrl': timg, 'link': c['url'], 'title': ccaption,
  295. 'description': cdescription, 'video': tid}
  296. x["data"].append(a)
  297. # print(x["data"])
  298. # 本週推薦
  299. if x['id'] == 7:
  300. records = ExecuteQuery(
  301. "SELECT max_row from outer_site_set WHERE title='本週推薦'")
  302. maxrow = 1
  303. for c in records:
  304. maxrow = c['max_row']
  305. records = ExecuteQuery("""SELECT theme_type, mapping_id, IFNULL(ifnull(ifnull(ifnull(_hcase.caption,_hcolumn.ctitle),_hproduct.name),_hvideo.title),_hbrand.title) caption ,
  306. IFNULL(ifnull(ifnull(_hcase.cover,_hcolumn.clogo),_hproduct.cover),_hbrand.logo) J, iframe , IFNULL(ifnull(ifnull(ifnull(_hcase.short_desc,_hcolumn.cdesc),_hproduct.descr),_hvideo.`desc`),_hbrand.intro) short_desc
  307. , (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) when theme_type='brand' then CONCAT('https://hhh.com.tw/brand-index.php?brand_id=',mapping_id) ELSE '' END) url
  308. -- SELECT *
  309. FROM homepage_set
  310. left join _hcase ON _hcase.hcase_id=homepage_set.mapping_id AND theme_type='case'-- AND _hcase.onoff = '1'
  311. LEFT JOIN _hproduct ON mapping_id = _hproduct.id AND theme_type='product'-- AND _hproduct.onoff = '1'
  312. LEFT JOIN _hcolumn ON mapping_id = _hcolumn.hcolumn_id AND theme_type='column'-- AND _hcolumn.onoff = '1'
  313. LEFT JOIN _hvideo ON mapping_id = _hvideo.hvideo_id AND theme_type='video'
  314. LEFT JOIN _hbrand ON mapping_id = _hbrand.hbrand_id AND theme_type='brand'
  315. WHERE homepage_set.onoff='Y'
  316. AND outer_set = (SELECT oss_id from outer_site_set WHERE title='本週推薦')
  317. 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))
  318. ORDER BY outer_set, inner_sort
  319. LIMIT """ + str(maxrow))
  320. x["data"] = []
  321. for c in records:
  322. if c['iframe'] is None:
  323. if isinstance(c['J'], bytearray) or isinstance(c['J'], bytes):
  324. c['J'] = c['J'].decode('utf8')
  325. if isinstance(c['caption'], bytearray) or isinstance(c['caption'], bytes):
  326. c['caption'] = c['caption'].decode('utf8')
  327. if isinstance(c['short_desc'], bytearray) or isinstance(c['short_desc'], bytes):
  328. c['short_desc'] = c['short_desc'].decode('utf8')
  329. a = {'imgUrl': c['J'], 'link': c['url'], 'title': c['caption'],
  330. 'description': c['short_desc'], 'video': 'false'}
  331. else:
  332. tid = extract.video_id(str(c['iframe']))
  333. timg = "https://img.youtube.com/vi/" + tid+"/hqdefault.jpg"
  334. ccaption = ""
  335. cdescription = ""
  336. if isinstance(c['caption'], bytearray):
  337. ccaption = str(c['caption'].decode('utf8'))
  338. else:
  339. ccaption = str(c['caption'])
  340. if c['short_desc'] is not None:
  341. if isinstance(c['short_desc'], bytes):
  342. cdescription = str(c['short_desc'].decode('utf8'))
  343. else:
  344. cdescription = str(c['short_desc'])
  345. a = {'imgUrl': timg, 'link': c['url'], 'title': ccaption,
  346. 'description': cdescription, 'video': tid}
  347. x["data"].append(a)
  348. # print(x["data"])
  349. # 粉絲推薦
  350. if x['id'] == 8:
  351. records = ExecuteQuery(
  352. "SELECT max_row from outer_site_set WHERE title='粉絲推薦'")
  353. maxrow = 1
  354. for c in records:
  355. maxrow = c['max_row']
  356. records = ExecuteQuery("""SELECT theme_type, mapping_id, IFNULL(ifnull(ifnull(ifnull(_hcase.caption,_hcolumn.ctitle),_hproduct.name),_hvideo.title),_hbrand.title) caption ,
  357. IFNULL(ifnull(ifnull(_hcase.cover,_hcolumn.clogo),_hproduct.cover),_hbrand.logo) J, iframe , IFNULL(ifnull(ifnull(ifnull(_hcase.short_desc,_hcolumn.cdesc),_hproduct.descr),_hvideo.`desc`),_hbrand.intro) short_desc
  358. , (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) when theme_type='brand' then CONCAT('https://hhh.com.tw/brand-index.php?brand_id=',mapping_id) ELSE '' END) url
  359. -- SELECT *
  360. FROM homepage_set
  361. left join _hcase ON _hcase.hcase_id=homepage_set.mapping_id AND theme_type='case'-- AND _hcase.onoff = '1'
  362. LEFT JOIN _hproduct ON mapping_id = _hproduct.id AND theme_type='product'-- AND _hproduct.onoff = '1'
  363. LEFT JOIN _hcolumn ON mapping_id = _hcolumn.hcolumn_id AND theme_type='column'-- AND _hcolumn.onoff = '1'
  364. LEFT JOIN _hvideo ON mapping_id = _hvideo.hvideo_id AND theme_type='video'
  365. LEFT JOIN _hbrand ON mapping_id = _hbrand.hbrand_id AND theme_type='brand'
  366. WHERE homepage_set.onoff='Y'
  367. AND outer_set = (SELECT oss_id from outer_site_set WHERE title='粉絲推薦')
  368. 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))
  369. ORDER BY outer_set, inner_sort
  370. LIMIT """ + str(maxrow))
  371. x["data"] = []
  372. for c in records:
  373. if c['iframe'] is None:
  374. if isinstance(c['J'], bytearray) or isinstance(c['J'], bytes):
  375. c['J'] = c['J'].decode('utf8')
  376. if isinstance(c['caption'], bytearray) or isinstance(c['caption'], bytes):
  377. c['caption'] = c['caption'].decode('utf8')
  378. if isinstance(c['short_desc'], bytearray) or isinstance(c['short_desc'], bytes):
  379. c['short_desc'] = c['short_desc'].decode('utf8')
  380. a = {'imgUrl': c['J'], 'link': c['url'], 'title': c['caption'],
  381. 'description': c['short_desc'], 'video': 'false'}
  382. else:
  383. tid = extract.video_id(str(c['iframe']))
  384. timg = "https://img.youtube.com/vi/" + tid+"/hqdefault.jpg"
  385. ccaption = ""
  386. cdescription = ""
  387. if isinstance(c['caption'], bytearray):
  388. ccaption = str(c['caption'].decode('utf8'))
  389. else:
  390. ccaption = str(c['caption'])
  391. if c['short_desc'] is not None:
  392. if isinstance(c['short_desc'], bytes):
  393. cdescription = str(c['short_desc'].decode('utf8'))
  394. else:
  395. cdescription = str(c['short_desc'])
  396. a = {'imgUrl': timg, 'link': c['url'], 'title': ccaption,
  397. 'description': cdescription, 'video': tid}
  398. x["data"].append(a)
  399. # print(x["data"])
  400. if x['id'] == 9:
  401. records = ExecuteQuery(
  402. "SELECT id, (case when youtube_title = '' OR youtube_title IS NULL then (SELECT title FROM _hvideo where display_datetime < NOW() 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 where display_datetime < NOW() ORDER BY hvideo_id DESC LIMIT 1) ELSE youtube_id end) Y FROM site_setup")
  403. for c in records:
  404. x['title'] = ""
  405. if isinstance(c['T'], bytearray):
  406. x['title'] = str(c['T'].decode('utf8'))
  407. else:
  408. x['title'] = str(c['T'])
  409. x['yt'] = extract.video_id(str(c['Y']))
  410. # print(id)
  411. if x['id'] == 10:
  412. records = ExecuteQuery(
  413. "SELECT all_search_tag ast FROM site_setup")
  414. x["data"] = []
  415. for c in records:
  416. x["data"] = c['ast'].split(',')
  417. # print(id)
  418. # print(jData)
  419. """ if not os.path.exists(hhhMBPath):
  420. os.mkdir(hhhMBPath)
  421. with open(hhhMBPath+'/json/' + filename, 'w', encoding='utf-8') as f:
  422. json.dump(jData, f, ensure_ascii=False, indent=4)
  423. if not os.path.exists(hhhPCPath):
  424. os.mkdir(hhhPCPath)
  425. with open(hhhPCPath+'/json/' + filename, 'w', encoding='utf-8') as f:
  426. json.dump(jData, f, ensure_ascii=False, indent=4) """
  427. return jData
  428. @app.get("/gencase")
  429. def gencase(id: str = "14151", sort: str = "new", page: str="1"):
  430. with dataset.connect(connstr) as db:
  431. jData = json.load(open(hhhMBPath+'/json/cases.json', encoding='utf8'))
  432. records = db.query("""SELECT *, c.style cstyle, c.style2 cstyle2 FROM _hcase c
  433. LEFT JOIN _hdesigner d ON c.hdesigner_id = d.hdesigner_id
  434. WHERE c.hcase_id = '""" + id + """' AND c.onoff='1' AND d.onoff='1' and c.sdate < now() """)
  435. # print(jData)
  436. for x in jData:
  437. tmpCaseDetail = []
  438. icount = 0
  439. for c in records:
  440. icount += 1
  441. #tmpCaseDetail.append({"CaseDetailImg": c["cimg"]})
  442. #x["CaseDetail"] = tmpCaseDetail
  443. if c != None:
  444. x["designerid"] = str(c["hdesigner_id"])
  445. x["CaseId"] = str(c["hcase_id"])
  446. x["Casetitle"] = c["caption"]
  447. x["CaseTeamName"] = c["name"]
  448. x["CaseCompany"] = c["title"]
  449. x["CaseCompanyAddress"] = c["address"]
  450. x["CaseCompanyTel"] = c["phone"]
  451. x["CaseCompanyEmail"] = c["mail"]
  452. x["CaseCompanyWeb"] = c["website"]
  453. x["CaseDate"] = str(c["sdate"])
  454. x["CaseViews"] = c["viewed"]
  455. x["CaseCoverImg"] = c["cover"]
  456. x["CaseImgAmount"] = icount
  457. x["CaseStyle"] = c["cstyle"]
  458. x["CaseHouse"] = c["layout"]
  459. x["CaseSize"] = c["area"]
  460. x["CaseProject"] = ""
  461. x["CaseDataMember"] = c["member"]
  462. x["CaseDataSize"] = c["area"]
  463. x["CaseDataStyle"] = c["cstyle"] + c["cstyle2"]
  464. x["CaseDataType"] = c["type"]
  465. x["CaseDataSituation"] = c["condition"]
  466. x["CaseDataImgProvide"] = c["provider"]
  467. x["CaseDataSpace"] = c["layout"]
  468. x["CaseDataMaterial"] = c["materials"]
  469. x["ContactFreeTel"] = c["service_phone"]
  470. x["ContactDesignerImg"] = c["img_path"]
  471. x["CasePageLink"] = ""
  472. x["CasePageprev"] = ""
  473. #x["CaseTag"]= []
  474. #相同設計師的個案
  475. sql = """SELECT * FROM _hcase c
  476. WHERE hdesigner_id = '""" + x["designerid"] + """' and hcase_id <> '""" + x["CaseId"] + """' and sdate < now() AND c.onoff='1'
  477. ORDER BY """ + ("sdate" if sort == 'new' else 'viewed') + """ DESC
  478. LIMIT """ + str((int(page) - 1)*12) + """,12
  479. """
  480. cases = db.query(sql)
  481. tmpOtherCases = []
  482. for other in cases:
  483. tmpOtherCase = {}
  484. tmpOtherCase["designerid"] = str(other["hdesigner_id"])
  485. tmpOtherCase["casesid"] = str(other["hcase_id"])
  486. tmpOtherCase["Views"] = other["viewed"]
  487. tmpOtherCase["ProfileImg"] = other["cover"]
  488. tmpTags = []
  489. for tag in other["tag"].split(','):
  490. tmpTags.append({"Tag": tag , "TagLink": "" })
  491. tmpOtherCase["ProfileTag"] = tmpTags
  492. tmpOtherCases.append(tmpOtherCase)
  493. x["DesignerProfile"] = tmpOtherCases
  494. #相同風格的個案
  495. sql = """SELECT * FROM _hcase c
  496. WHERE style = '""" + x["CaseStyle"] + """' and hcase_id <> '""" + x["CaseId"] + """' and sdate < now() AND c.onoff='1'
  497. ORDER BY """ + ("sdate" if sort == 'new' else 'viewed') + """ DESC
  498. LIMIT """ + str((int(page) - 1)*12) + """,12
  499. """
  500. cases = db.query(sql)
  501. tmpOtherCases = []
  502. for other in cases:
  503. tmpOtherCase = {}
  504. tmpOtherCase["designerid"] = str(other["hdesigner_id"])
  505. tmpOtherCase["casesid"] = str(other["hcase_id"])
  506. tmpOtherCase["Views"] = other["viewed"]
  507. tmpOtherCase["ProfileImg"] = other["cover"]
  508. tmpTags = []
  509. for tag in other["tag"].split(','):
  510. tmpTags.append({"Tag": tag , "TagLink": "" })
  511. tmpOtherCase["ProfileTag"] = tmpTags
  512. tmpOtherCases.append(tmpOtherCase)
  513. x["StyleProfile"] = tmpOtherCases
  514. #相同風格的RANDOM 10筆
  515. #cases = db.query("""SELECT * FROM _hcase c
  516. #WHERE style = '""" + x["CaseStyle"] + """' and hcase_id <> '""" + x["CaseId"] + """' and sdate < now() AND c.onoff='1'
  517. #ORDER BY RAND()
  518. #LIMIT 10
  519. #""")
  520. """ tmpOtherCases = []
  521. for other in cases:
  522. tmpOtherCase = {}
  523. tmpOtherCase["designerid"] = str(other["hdesigner_id"])
  524. tmpOtherCase["casesid"] = str(other["hcase_id"])
  525. tmpOtherCase["PortfoliolImg"] = other["cover"]
  526. tmpOtherCase["PortfoliolLink"] = ""
  527. tmpOtherCase["PortfoliolImgAlt"] = other["caption"]
  528. tmpOtherCases.append(tmpOtherCase)
  529. x["OtherStylePortfolio"]= tmpOtherCases """
  530. # print(x)
  531. # print(jData)
  532. """ if not os.path.exists(hhhMBPath):
  533. os.mkdir(hhhMBPath)
  534. with open(hhhMBPath+'/json/cases-' + id + '.json', 'w', encoding='utf-8') as f:
  535. json.dump(jData, f, ensure_ascii=False, indent=4) """
  536. return jData
  537. @app.get("/gendesigner")
  538. async def gendesigner(id: str = "447", sort: str = "new", page: str = "1"):
  539. with dataset.connect(connstr) as db:
  540. jData = json.load(open(hhhMBPath+'/json/designers.json', encoding='utf8'))
  541. records = db.query("""SELECT * FROM _hdesigner d
  542. WHERE d.hdesigner_id = '""" + id + """' AND d.onoff='1' """)
  543. check_len=[]
  544. for c in records:
  545. check_len.append(c)
  546. if len(check_len)==0:
  547. return []
  548. # print(jData)
  549. for x in jData:
  550. tmpCaseDetail = []
  551. icount = 0
  552. for c in records:
  553. icount += 1
  554. # tmpCaseDetail.append({"CaseDetailImg":c["cimg"]})
  555. if page == "1":
  556. x["id"] = c["hdesigner_id"]
  557. x["premium"] = c["premium"]
  558. x["BannerImg"] = c["background"]
  559. x["BannerImg_mobile"] = c['background_mobile']
  560. x["CompanyName"] = c["title"].replace("\n","<br>")
  561. x["DesignerName"] = c["name"]
  562. x["Designerimg"] = c["img_path"]
  563. x["Description"] = c["seo"]
  564. x["Approve"] = c["position"]
  565. x["FB_link"] = c["fbpageurl"]
  566. # x["order_computer"] = c["order_computer"]
  567. # x["order_mb"] = c["order_mb"]
  568. if c["service_phone"]!='':
  569. if ',' not in c["service_phone"]:
  570. service_phone = c["service_phone"]
  571. else:
  572. part1=c["service_phone"][0:4]
  573. part2=c["service_phone"][4:7]
  574. part3=c["service_phone"][7:10]
  575. part4=c["service_phone"].split(',')[1]
  576. service_phone = part1+'-'+part2+'-'+part3+'#'+part4
  577. else:
  578. service_phone=''
  579. phone_list=[]
  580. for k1 in c["phone"].split(','):
  581. phone_list.append({"title": "諮詢專線:", "link":'tel:'+k1, "data":k1})
  582. x["Basics"] = []
  583. if service_phone!='':
  584. x["Basics"].append({"title": "免費專線:","link": 'tel:'+c["service_phone"], "data": service_phone})
  585. if c["phone"]!='':
  586. for k2 in phone_list:
  587. x["Basics"].append(k2)
  588. if len(c["fax"])!=0:
  589. x["Basics"].append({"title": "公司傳真:", "link": "fax:"+c["fax"], "data": c["fax"]})
  590. if len(c["address"])!=0:
  591. x["Basics"].append({"title": "公司地址:", "link": "https://www.google.com/search?q="+c["address"], "data": c["address"]})
  592. if len(c["mail"])!=0:
  593. x["Basics"].append({"title": "電子信箱:", "link": "mailto:"+c["mail"], "data": c["mail"]})
  594. if len(c["website"])!=0:
  595. x["Basics"].append({"title": "公司網址:", "link": c["website"], "data": c["website"]})
  596. blog_list=re.findall(r'href="(.*?)"',c["blog"])
  597. if len(blog_list)==0:
  598. blog_list=re.findall(r'http.*',c["blog"])
  599. if len(blog_list)!=0:
  600. for k3 in blog_list:
  601. x["Basics"].append({"title": "其他連結:", "link": k3, "data": k3})
  602. # x["Basics"] = [
  603. # {"title": "免費專線:","link": 'tel:'+c["service_phone"], "data": service_phone},
  604. # # {"title": "諮詢專線:", "link": c["phone"], "data": c["phone"]},
  605. # {"title": "諮詢專線:", "link": c["phone"], "data": c["phone"]},
  606. # {"title": "公司傳真:", "link": c["fax"], "data": c["fax"]},
  607. # {"title": "公司地址:", "link": c["address"], "data": c["address"]},
  608. # {"title": "電子信箱:", "link": c["mail"], "data": c["mail"]},
  609. # {"title": "公司網址:", "link": c["website"], "data": c["website"]}
  610. # ]
  611. x["FreeCall"] = c["service_phone"]
  612. x["ConsoleCall_1"] = c["phone"]
  613. x["ConsoleCall_2"] = c["phone"]
  614. x["Fax"] = c["fax"]
  615. x["Address"] = c["address"]
  616. x["Email"] = c["mail"]
  617. x["Web"] = c["website"]
  618. x["Branches"] = []
  619. branches = db.query("""SELECT * FROM designer_branch br
  620. WHERE br.designer_id = '""" + id + """' """)
  621. for branch in branches:
  622. tmpobj = {
  623. "title": branch["title"],
  624. "address": branch["address"],
  625. "address_link" : "https://www.google.com/search?q="+branch["address"],
  626. "tel": branch["tel"],
  627. "tel_link": "tel:"+branch["tel"],
  628. "fax": branch["fax"],
  629. "fax_link": "fax:"+branch["fax"]
  630. }
  631. x["Branches"].append(tmpobj)
  632. x["Budget"] = c["budget"]
  633. x["Square"] = c["area"]
  634. x["SpecialCase"] = c["special"]
  635. x["Charge"] = c["charge"]
  636. x["Pay"] = c["payment"]
  637. x["WorkLoc"] = c["region"]
  638. x["WorkType"] = c["type"]
  639. x["WorkStyle"] = c["style"]
  640. x["WorkBudget"] = c["budget"]
  641. x["Terms"] = []
  642. if c["budget"]!='':
  643. x["Terms"].append({"title": "接案預算:", "data": c["budget"]})
  644. if c["area"]!='':
  645. x["Terms"].append({"title": "接案坪數:", "data": c["area"]})
  646. if c["special"]!='':
  647. x["Terms"].append({"title": "特殊接案:", "data": c["special"]})
  648. if c["charge"]!='':
  649. x["Terms"].append({"title": "收費方式:", "data": c["charge"]})
  650. if c["payment"]!='':
  651. x["Terms"].append({"title": "付費方式:", "data": c["payment"]})
  652. if c["region"]!='':
  653. x["Terms"].append({"title": "接案區域:", "data": c["region"]})
  654. if c["type"]!='':
  655. x["Terms"].append({"title": "接案類型:", "data": c["type"]})
  656. if c["style"]!='':
  657. x["Terms"].append({"title": "接案風格:", "data": c["style"]})
  658. x["scMedia"] = [
  659. {"name": "Facebook", "img": "https://hhh.com.tw/assets/images/rv_web/fb.svg","premium_img":"https://hhh.com.tw/assets/images/rv_web/fb-premium.png",
  660. "link": c["fbpageurl"]},
  661. {"name": "Line", "img": "https://hhh.com.tw/assets/images/rv_web/line.svg","premium_img":"https://hhh.com.tw/assets/images/rv_web/line-premium.png",
  662. "link": c["line_link"]},
  663. {"name": "Wechat", "img": "https://hhh.com.tw/assets/images/rv_web/wechat.svg","premium_img":"https://hhh.com.tw/assets/images/rv_web/wechat-premium.png",
  664. "link": c["fbpageurl"]},
  665. {"name": "email", "img": "https://hhh.com.tw/assets/images/rv_web/share.svg","premium_img":"https://hhh.com.tw/assets/images/rv_web/share-premium.png",
  666. "link": c["mail"]},
  667. {"name": "Like", "img": "https://hhh.com.tw/assets/images/rv_web/like-o.svg","premium_img":"https://hhh.com.tw/assets/images/rv_web/like-o-premium.png","img_d":"https://hhh.com.tw/assets/images/rv_web/like.svg","premium_img_d":"https://hhh.com.tw/assets/images/rv_web/like-premium.png" ,"link": ""}
  668. ]
  669. x_info = []
  670. if len(c["idea"])!=0:
  671. x_info.append({"title": "設計理念", "data": c["idea"]})
  672. if len(c["taxid"])!=0:
  673. x_info.append( {"title": "公司統編", "data": c["taxid"]})
  674. if len(c["career"])!=0:
  675. x_info.append({"title": "相關經歷", "data": c["career"]})
  676. if len(c["license"])!=0:
  677. x_info.append( {"title": "專業證照", "data": c["license"].replace('\r\n','<br />')})
  678. if len(c["awards"])!=0:
  679. x_info.append( {"title": "獲獎紀錄", "data": c["awards"].replace('\r\n','<br />')})
  680. x["Content"] = [
  681. {
  682. "Title": "設計師作品",
  683. "mb_title": "作品",
  684. "Tabtag": "intro",
  685. "Display_mb": "true",
  686. "isActive": "true",
  687. "Carddata": [],
  688. "total_all":0
  689. },
  690. {
  691. "Title": "設計師影音",
  692. "mb_title": "影音",
  693. "Tabtag": "video",
  694. "Display_mb": "true",
  695. "isActive": "true",
  696. "Carddata": [],
  697. "total_all":0
  698. },
  699. {
  700. "Title": "設計師專欄",
  701. "mb_title": "專欄",
  702. "Tabtag": "columns",
  703. "Display_mb": "true",
  704. "isActive": "true",
  705. "Carddata": [],
  706. "total_all":0
  707. },
  708. {
  709. "Title": "VR360",
  710. "mb_title": "VR",
  711. "Tabtag": "vr360",
  712. "Display_mb": "false",
  713. "isActive": "true",
  714. "Carddata": [],
  715. "total_all":0
  716. },
  717. {
  718. "Title": "設計師公司簡介",
  719. "mb_title": "公司簡介",
  720. "Tabtag": "company",
  721. "Display_mb": "true",
  722. "isActive": "true",
  723. "Carddata": [],
  724. "info":x_info
  725. # "info": [
  726. # {"title": "設計理念", "data": c["idea"]},
  727. # {"title": "公司統編", "data": c["taxid"]},
  728. # {"title": "相關經歷", "data": c["career"]},
  729. # {"title": "專業證照", "data": c["license"]},
  730. # {"title": "獲獎紀錄", "data": c["awards"]}
  731. # ]
  732. }
  733. ]
  734. records = db.query("""SELECT count(1) FROM _hcase c WHERE c.hdesigner_id = '""" + id + """' AND c.onoff='1' and c.sdate < now(); """ )
  735. for c in records:
  736. x["Content"][0]["total_all"] = str(c["count(1)"])
  737. records = db.query("""SELECT count(1) FROM _hvideo v WHERE v.hdesigner_id = '""" + id + """' AND display_datetime < NOW() and iframe<>'' ;""")
  738. for c in records:
  739. x["Content"][1]["total_all"] = str(c["count(1)"])
  740. records = db.query("""SELECT count(1) FROM _hcolumn c WHERE onoff=1 AND (c.hdesigner_ids LIKE '""" + id + """,%' OR c.hdesigner_ids LIKE '%,""" + id + """,%' OR c.hdesigner_ids LIKE '%,""" + id + """' OR c.hdesigner_ids = '""" + id + """') ;""")
  741. for c in records:
  742. x["Content"][2]["total_all"] = str(c["count(1)"])
  743. records = db.query("""SELECT count(1) FROM _hcase c WHERE c.hdesigner_id = '""" + id + """' and istaging != '' AND c.onoff='1' and c.sdate < now();""")
  744. for c in records:
  745. x["Content"][3]["total_all"] = str(c["count(1)"])
  746. # 設計師作品
  747. x["Content"][0]["Carddata"] = []
  748. cases = db.query("""SELECT tag,cover,caption,hcase_id,viewed,sdate,style,style2,type,`condition` FROM _hcase c
  749. WHERE c.hdesigner_id = '""" + id + """' AND c.onoff='1' and c.sdate < now()
  750. ORDER BY """ + ("sdate" if sort == 'new' else 'corder ASC,viewed') + """ DESC
  751. LIMIT """ + str((int(page) - 1)*12) + """,12
  752. """)
  753. for case in cases:
  754. tag_use = ''
  755. if case['style']!='':
  756. tag_use += case['style'].strip()
  757. tag_use += ','
  758. if case['style2']!='':
  759. tag_use += case['style2'].strip()
  760. tag_use += ','
  761. if case['type']!='':
  762. tag_use += case['type'].strip()
  763. tag_use += ','
  764. if case['condition']!='':
  765. tag_use += case['condition'].strip()
  766. tmpobj = {
  767. "url": "https://hhh.com.tw/cases/detail/d/"+str(case["hcase_id"]),
  768. "imgURL": case["cover"].replace('/_hcase/', '/_hcase_orig/').replace('/_hcase_img/', '/_hcase_img_orig/'),
  769. "title": case["caption"],
  770. "tag": [{"name": tag, "link": "https://hhh.com.tw/search/lists/case/{}-keyword/".format(tag)} for tag in tag_use.split(',')],
  771. # "tag": [{"name": tag, "link": "https://hhh.com.tw/search/lists/case/{}-keyword/".format(tag)} for tag in case["tag"].split(',')],
  772. "views": case["viewed"],
  773. "dateSort": str(case["sdate"])
  774. }
  775. x["Content"][0]["Carddata"].append(tmpobj)
  776. # 設計師影音
  777. # https://i.ytimg.com/vi/y6VmaLC7O9Y/hqdefault.jpg
  778. x["Content"][1]["Carddata"] = []
  779. # videos = db.query("""SELECT tag_vpattern,iframe,title,hvideo_id,viewed,display_datetime FROM _hvideo v
  780. # WHERE v.hdesigner_id = '""" + id + """' AND display_datetime < NOW() and iframe<>''
  781. # ORDER BY """ + ("hvideo_id" if sort == 'new' else 'viewed') + """ DESC
  782. # LIMIT """ + str((int(page) - 1)*12) + """,12
  783. # """)
  784. videos = db.query("""SELECT tag_vpattern,iframe,title,hvideo_id,viewed,display_datetime FROM _hvideo v
  785. WHERE v.hdesigner_id = '""" + id + """' AND display_datetime < NOW() and iframe<>''
  786. ORDER BY """+ "hvideo_id" + """ DESC
  787. LIMIT """ + str((int(page) - 1)*12) + """,12
  788. """)
  789. for video in videos:
  790. print(str(video['iframe']))
  791. tmpobj = {
  792. "url": "https://hhh.com.tw/video-post.php?id="+str(video['hvideo_id']),
  793. "imgURL": "https://i.ytimg.com/vi/" + extract.video_id(html.unescape(str(video['iframe'])))+"/hqdefault.jpg",
  794. "title": video["title"],
  795. "tag": [{"name": tag, "link": "https://hhh.com.tw/search/lists/video/{}-keyword/".format(tag)} for tag in video["tag_vpattern"].split(',')],
  796. "views": video["viewed"],
  797. "dateSort": str(video["display_datetime"])
  798. }
  799. x["Content"][1]["Carddata"].append(tmpobj)
  800. # 設計師專欄
  801. # x["Content"][2]["Carddata"] = []
  802. # columns = db.query("""SELECT Ctag,clogo,ctitle,hcolumn_id,viewed,sdate FROM _hcolumn c
  803. # WHERE onoff=1 AND (hdesigner_ids LIKE '""" + id + """,%' OR hdesigner_ids LIKE '%,""" + id + """,%' OR hdesigner_ids LIKE '%,""" + id + """' OR hdesigner_ids = '""" + id + """')
  804. # ORDER BY """ + ("sdate" if sort == 'new' else 'viewed') + """ DESC
  805. # LIMIT """ + str((int(page) - 1)*12) + """,12
  806. # """)
  807. x["Content"][2]["Carddata"] = []
  808. columns = db.query("""SELECT Ctag,clogo,ctitle,hcolumn_id,viewed,sdate FROM _hcolumn c
  809. WHERE onoff=1 AND (hdesigner_ids LIKE '""" + id + """,%' OR hdesigner_ids LIKE '%,""" + id + """,%' OR hdesigner_ids LIKE '%,""" + id + """' OR hdesigner_ids = '""" + id + """')
  810. ORDER BY """ + "sdate" + """ DESC
  811. LIMIT """ + str((int(page) - 1)*12) + """,12
  812. """)
  813. for column in columns:
  814. tmpobj = {
  815. "url": "https://hhh.com.tw/columns/detail/"+str(column['hcolumn_id']),
  816. "imgURL": column['clogo'],
  817. "title": column["ctitle"],
  818. "tag": [] if not column["Ctag"] else [{"name": tag, "link": "https://hhh.com.tw/search/lists/column/{}-keyword/".format(tag)} for tag in column["Ctag"].split(',')],
  819. "views": column["viewed"],
  820. "dateSort": str(column["sdate"])
  821. }
  822. x["Content"][2]["Carddata"].append(tmpobj)
  823. # VR360
  824. # x["Content"][3]["Carddata"] = []
  825. # cases = db.query("""SELECT tag,cover,caption,hcase_id,viewed,sdate FROM _hcase c
  826. # WHERE c.hdesigner_id = '""" + id + """' and istaging != '' AND c.onoff='1'
  827. # ORDER BY """ + ("sdate" if sort == 'new' else 'viewed') + """ DESC
  828. # LIMIT """ + str((int(page) - 1)*12) + """,12
  829. # """)
  830. x["Content"][3]["Carddata"] = []
  831. cases = db.query("""SELECT tag,cover,caption,hcase_id,viewed,sdate FROM _hcase c
  832. WHERE c.hdesigner_id = '""" + id + """' and istaging != '' AND c.onoff='1' and c.sdate < now()
  833. ORDER BY """ + "sdate" + """ DESC
  834. LIMIT """ + str((int(page) - 1)*12) + """,12
  835. """)
  836. for case in cases:
  837. tmpobj = {
  838. "url": "https://hhh.com.tw/cases/detail/d/"+str(case["hcase_id"]),
  839. "imgURL": case["cover"],
  840. "title": case["caption"],
  841. "tag": [{"name": tag, "link": "https://hhh.com.tw/search/lists/column/{}-keyword/".format(tag)} for tag in case["tag"].split(',')],
  842. "views": case["viewed"],
  843. "dateSort": str(case["sdate"])
  844. }
  845. x["Content"][3]["Carddata"].append(tmpobj)
  846. # 設計公司簡介
  847. #x["Content"][4]["Carddata"] = []
  848. #cases = db.query("")
  849. """ for case in cases:
  850. tmpobj = {
  851. "imgURL":case["cover"],
  852. "title":case["caption"],
  853. "tag":[{"name": tag, "link": ""} for tag in case["tag"].split(',')],
  854. "views":case["viewed"],
  855. "dateSort":str(case["sdate"])
  856. }
  857. x["Content"][4]["Carddata"].append(tmpobj) """
  858. # print(x)
  859. # print(jData)
  860. """ if not os.path.exists(hhhMBPath):
  861. os.mkdir(hhhMBPath)
  862. with open(hhhMBPath+'/json/designers-' + id + '.json', 'w', encoding='utf-8') as f:
  863. json.dump(jData, f, ensure_ascii=False, indent=4) """
  864. return jData
  865. @app.get("/gencolumn")
  866. def gencolumn(id: str = "6392", sort: str = "new", page: str="1"):
  867. with dataset.connect(connstr) as db:
  868. jData = json.load(open(hhhMBPath+'/json/Columns.json', encoding='utf8'))
  869. # records = db.query("""SELECT * FROM _hcolumn c
  870. # WHERE c.hcolumn_id = '""" + id + """' AND c.onoff='1' """)
  871. records = db.query("""SELECT * FROM _hcolumn c
  872. WHERE c.hcolumn_id = '""" + id + """' AND c.onoff='1' """)
  873. #print(id)
  874. base_c_url="https://hhh.com.tw/columns/lists/"
  875. ctype_sub_dist={
  876. 'hometrends': '居家趨勢',
  877. 'hotrank' : '人氣排行',
  878. 'archdesign' : '建築設計',
  879. 'styleselection' : '風格選店',
  880. 'charitable' : '公益活動',
  881. 'exhibition' : '展演資訊',
  882. 'smallhouse' : '小宅規劃',
  883. 'oldhouse' : '老屋翻新',
  884. 'stylebuild' : '風格營造',
  885. 'color' : '配色佈置',
  886. 'goodhouse' : '好宅特輯',
  887. 'proposal' : '設計提案',
  888. 'news' : '新聞最前線',
  889. 'allocation' : '預算分配',
  890. 'process' : '施工流程',
  891. 'knowledge' : '建材知識',
  892. 'decorating' : '裝潢撇步',
  893. 'fengshui' : '居家風水',
  894. 'housekeeping' : '家事清潔',
  895. 'storageskills' : '收納技巧',
  896. 'renovation' : '改造修繕',
  897. 'retire' : '退休好幸福',
  898. 'furnishings' : '家具家飾',
  899. 'appliances' : '美型家電',
  900. 'recommend' : '推薦廚衛',
  901. 'homegoods' : '居家好物',
  902. 'quality' : '優質建材',
  903. 'brandnews' : '品牌新訊',
  904. 'housingnews' : '房市新聞',
  905. 'specsearch' : '建案特搜',
  906. 'buyandsell' : '買屋賣屋',
  907. 'mortgage' : '房貸稅務',
  908. 'renting' : '租房須知',
  909. }
  910. ctype_sub_dist_converse = {v: k for k, v in ctype_sub_dist.items()}
  911. for x in jData:
  912. icount = 0
  913. c = None
  914. for c in records:
  915. icount += 1
  916. if c != None:
  917. x["Columnsid"] = str(c["hcolumn_id"])
  918. x["Columnstitle"] = c["ctitle"]
  919. x["ColumnsCoverImg"] = c["clogo"]
  920. x["ctype"] = c["ctype"]
  921. x["ctype_sub"] = c["ctype_sub"]
  922. if c["ctype"] == "不限":
  923. x["ctype_link"] = base_c_url+"all-columntypea"
  924. x["ctype_sub_link"] = ""
  925. x["ctype_sub"] = ""
  926. else:
  927. try:
  928. x["ctype_sub_link"] = ctype_sub_dist_converse[c["ctype_sub"]]+"-columntypeb"
  929. except:
  930. x["ctype_sub_link"] = ""
  931. if c["ctype"] == "編輯精選":
  932. x["ctype_link"] = base_c_url+"editorchoose-columntypea"
  933. elif c["ctype"] == "居家設計":
  934. x["ctype_link"] = base_c_url+"housedesign-columntypea"
  935. elif c["ctype"] == "裝修前線":
  936. x["ctype_link"] = base_c_url+"decoration-columntypea"
  937. elif c["ctype"] == "生活PLUS":
  938. x["ctype_link"] = base_c_url+"plus-columntypea"
  939. elif c["ctype"] == "品牌好物":
  940. x["ctype_link"] = base_c_url+"gooditem-columntypea"
  941. elif c["ctype"] == "房市焦點":
  942. x["ctype_link"] = base_c_url+"focus-columntypea"
  943. x["ColumnsDate"] = str(c["sdate"])
  944. x["ColumnsViews"] = str(c["viewed"])
  945. if page == "1":
  946. x["ColumnsContent"] = html.unescape(c["page_content"]).replace('../hhh/',"//www.hhh.com.tw/modules/gs/hhh/").replace('<img',"<img alt='幸福空間專欄' ").replace('../../../uploads/',"//www.hhh.com.tw/uploads/")
  947. tmpTags = []
  948. c["ctag"] = c["ctag"].replace(' ',',')
  949. for tag in c["ctag"].split(','):
  950. tmpTags.append({"Tag": tag})
  951. x["ColumnsTag"] = tmpTags
  952. x["author_inf"] = c["extend_str"]
  953. #相同類別的最新12筆
  954. sql = """SELECT * FROM _hcolumn c
  955. 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'
  956. ORDER BY """ + ("sdate" if sort == 'new' else 'viewed') + """ DESC
  957. LIMIT """ + str((int(page) - 1)*12) + """,12
  958. """
  959. if c["ctype"]=='不限':
  960. sql = """SELECT * FROM _hcolumn c
  961. where hcolumn_id <> '""" + str(c["hcolumn_id"]) + """' and sdate < now() AND c.onoff='1'
  962. ORDER BY """ + ("sdate" if sort == 'new' else 'viewed') + """ DESC
  963. LIMIT """ + str((int(page) - 1)*12) + """,12"""
  964. ctypes = db.query(sql)
  965. tmpOtherCols = []
  966. for other in ctypes:
  967. tmpOtherCol = {}
  968. tmpOtherCol["Columnsid"] = str(other["hcolumn_id"])
  969. tmpOtherCol["ColumnsCoverImg"] = other["clogo"]
  970. tmpOtherCol["Views"] = other["viewed"]
  971. tmpOtherCol["Columnstitle"] = other["ctitle"]
  972. tmpTags = []
  973. other["ctag"] = other["ctag"].replace(' ',',')
  974. for tag in other["ctag"].split(','):
  975. tmpTags.append({"Tag": tag})
  976. tmpOtherCol["ColumnsTag"] = tmpTags
  977. tmpOtherCols.append(tmpOtherCol)
  978. x["OtherColumns"] = tmpOtherCols
  979. if icount == 0:
  980. return []
  981. #print(x)
  982. # print(jData)
  983. """ if not os.path.exists(hhhMBPath):
  984. os.mkdir(hhhMBPath)
  985. with open(hhhMBPath+'/json/Columns-' + id + '.json', 'w', encoding='utf-8') as f:
  986. json.dump(jData, f, ensure_ascii=False, indent=4) """
  987. return jData
  988. @app.get("/gencolumn_use")
  989. def gencolumn_use(id: str = "6392", sort: str = "new", page: str="1"):
  990. with dataset.connect(connstr) as db:
  991. jData = json.load(open(hhhMBPath+'/json/Columns.json', encoding='utf8'))
  992. # records = db.query("""SELECT * FROM _hcolumn c
  993. # WHERE c.hcolumn_id = '""" + id + """' AND c.onoff='1' """)
  994. records = db.query("""SELECT * FROM _hcolumn c
  995. WHERE c.hcolumn_id = '""" + id + """' """)
  996. #print(id)
  997. base_c_url="https://hhh.com.tw/columns/lists/"
  998. ctype_sub_dist={
  999. 'hometrends': '居家趨勢',
  1000. 'hotrank' : '人氣排行',
  1001. 'archdesign' : '建築設計',
  1002. 'styleselection' : '風格選店',
  1003. 'charitable' : '公益活動',
  1004. 'exhibition' : '展演資訊',
  1005. 'smallhouse' : '小宅規劃',
  1006. 'oldhouse' : '老屋翻新',
  1007. 'stylebuild' : '風格營造',
  1008. 'color' : '配色佈置',
  1009. 'goodhouse' : '好宅特輯',
  1010. 'proposal' : '設計提案',
  1011. 'news' : '新聞最前線',
  1012. 'allocation' : '預算分配',
  1013. 'process' : '施工流程',
  1014. 'knowledge' : '建材知識',
  1015. 'decorating' : '裝潢撇步',
  1016. 'fengshui' : '居家風水',
  1017. 'housekeeping' : '家事清潔',
  1018. 'storageskills' : '收納技巧',
  1019. 'renovation' : '改造修繕',
  1020. 'retire' : '退休好幸福',
  1021. 'furnishings' : '家具家飾',
  1022. 'appliances' : '美型家電',
  1023. 'recommend' : '推薦廚衛',
  1024. 'homegoods' : '居家好物',
  1025. 'quality' : '優質建材',
  1026. 'brandnews' : '品牌新訊',
  1027. 'housingnews' : '房市新聞',
  1028. 'specsearch' : '建案特搜',
  1029. 'buyandsell' : '買屋賣屋',
  1030. 'mortgage' : '房貸稅務',
  1031. 'renting' : '租房須知',
  1032. }
  1033. ctype_sub_dist_converse = {v: k for k, v in ctype_sub_dist.items()}
  1034. for x in jData:
  1035. icount = 0
  1036. c = None
  1037. for c in records:
  1038. icount += 1
  1039. if c != None:
  1040. x["Columnsid"] = str(c["hcolumn_id"])
  1041. x["Columnstitle"] = c["ctitle"]
  1042. x["ColumnsCoverImg"] = c["clogo"]
  1043. x["ctype"] = c["ctype"]
  1044. x["ctype_sub"] = c["ctype_sub"]
  1045. if c["ctype"] == "不限":
  1046. x["ctype_link"] = base_c_url+"all-columntypea"
  1047. x["ctype_sub_link"] = ""
  1048. x["ctype_sub"] = ""
  1049. else:
  1050. try:
  1051. x["ctype_sub_link"] = ctype_sub_dist_converse[c["ctype_sub"]]+"-columntypeb"
  1052. except:
  1053. x["ctype_sub_link"] = ""
  1054. if c["ctype"] == "編輯精選":
  1055. x["ctype_link"] = base_c_url+"editorchoose-columntypea"
  1056. elif c["ctype"] == "居家設計":
  1057. x["ctype_link"] = base_c_url+"housedesign-columntypea"
  1058. elif c["ctype"] == "裝修前線":
  1059. x["ctype_link"] = base_c_url+"decoration-columntypea"
  1060. elif c["ctype"] == "生活PLUS":
  1061. x["ctype_link"] = base_c_url+"plus-columntypea"
  1062. elif c["ctype"] == "品牌好物":
  1063. x["ctype_link"] = base_c_url+"gooditem-columntypea"
  1064. elif c["ctype"] == "房市焦點":
  1065. x["ctype_link"] = base_c_url+"focus-columntypea"
  1066. x["ColumnsDate"] = str(c["sdate"])
  1067. x["ColumnsViews"] = str(c["viewed"])
  1068. if page == "1":
  1069. x["ColumnsContent"] = html.unescape(c["page_content"]).replace('../hhh/',"//www.hhh.com.tw/modules/gs/hhh/").replace('<img',"<img alt='幸福空間專欄' ").replace('../../../uploads/',"//www.hhh.com.tw/uploads/")
  1070. tmpTags = []
  1071. c["ctag"] = c["ctag"].replace(' ',',')
  1072. for tag in c["ctag"].split(','):
  1073. tmpTags.append({"Tag": tag})
  1074. x["ColumnsTag"] = tmpTags
  1075. x["author_inf"] = c["extend_str"]
  1076. #相同類別的最新12筆
  1077. sql = """SELECT * FROM _hcolumn c
  1078. 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'
  1079. ORDER BY """ + ("sdate" if sort == 'new' else 'viewed') + """ DESC
  1080. LIMIT """ + str((int(page) - 1)*12) + """,12
  1081. """
  1082. if c["ctype"]=='不限':
  1083. sql = """SELECT * FROM _hcolumn c
  1084. where hcolumn_id <> '""" + str(c["hcolumn_id"]) + """' and sdate < now() AND c.onoff='1'
  1085. ORDER BY """ + ("sdate" if sort == 'new' else 'viewed') + """ DESC
  1086. LIMIT """ + str((int(page) - 1)*12) + """,12"""
  1087. ctypes = db.query(sql)
  1088. tmpOtherCols = []
  1089. for other in ctypes:
  1090. tmpOtherCol = {}
  1091. tmpOtherCol["Columnsid"] = str(other["hcolumn_id"])
  1092. tmpOtherCol["ColumnsCoverImg"] = other["clogo"]
  1093. tmpOtherCol["Views"] = other["viewed"]
  1094. tmpOtherCol["Columnstitle"] = other["ctitle"]
  1095. tmpTags = []
  1096. other["ctag"] = other["ctag"].replace(' ',',')
  1097. for tag in other["ctag"].split(','):
  1098. tmpTags.append({"Tag": tag})
  1099. tmpOtherCol["ColumnsTag"] = tmpTags
  1100. tmpOtherCols.append(tmpOtherCol)
  1101. x["OtherColumns"] = tmpOtherCols
  1102. if icount == 0:
  1103. return []
  1104. #print(x)
  1105. # print(jData)
  1106. """ if not os.path.exists(hhhMBPath):
  1107. os.mkdir(hhhMBPath)
  1108. with open(hhhMBPath+'/json/Columns-' + id + '.json', 'w', encoding='utf-8') as f:
  1109. json.dump(jData, f, ensure_ascii=False, indent=4) """
  1110. return jData
  1111. @app.get("/getColumnAds")
  1112. def getColumnAds():
  1113. with dataset.connect(connstr) as db:
  1114. ads = []
  1115. records = db.query("""SELECT adlogo_mobile imgUrl, adlogo DimgUrl, adhref link,alt_use alt,adid
  1116. FROM _had hh
  1117. WHERE adtype LIKE '專欄首大%'
  1118. AND hh.onoff='1'
  1119. and NOW() BETWEEN start_time AND end_time
  1120. ORDER BY cast(SUBSTR(adtype, 4) AS DECIMAL) """)
  1121. """ for x in records:
  1122. ads.append(x) """
  1123. ads.extend(records)
  1124. rData = json.loads(json.dumps(ads))
  1125. #print(json.dumps(ads))
  1126. return rData
  1127. from threading import Lock
  1128. import threading
  1129. mutex = Lock()
  1130. @app.post("/add_designer_clicks")
  1131. def add_designer_clicks(cid:str):
  1132. with mutex:
  1133. with dataset.connect(connstr) as db:
  1134. records = db.query("""UPDATE _hdesigner SET clicks=clicks+1 WHERE hdesigner_id="""+cid)
  1135. db.commit()
  1136. return True
  1137. cid_locks = {}
  1138. @app.post("/add_columns_viewed")
  1139. def add_columns_clicks(cid: str):
  1140. if cid not in cid_locks:
  1141. cid_locks[cid] = threading.Lock()
  1142. with cid_locks[cid]:
  1143. with dataset.connect(connstr) as db:
  1144. records = db.query("UPDATE _hcolumn SET viewed = viewed + 1 WHERE hcolumn_id = :cid", cid=cid)
  1145. db.commit()
  1146. return True
  1147. '''
  1148. @app.post("/add_columns_viewed")
  1149. def add_columns_clicks(cid:str):
  1150. with mutex:
  1151. with dataset.connect(connstr) as db:
  1152. records = db.query("""UPDATE _hcolumn SET viewed=viewed+1 WHERE hcolumn_id="""+cid)
  1153. db.commit()
  1154. return True
  1155. '''
  1156. #print(getColumnAds())
  1157. """ if __name__ == "__main__":
  1158. uvicorn.run(app, host="0.0.0.0", port=8000) """