genjson_designer.py 64 KB

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