genjson_emering.py 79 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661
  1. import os
  2. from typing import Optional
  3. from dataset.util import ResultIter
  4. from fastapi import FastAPI
  5. from fastapi.middleware.cors import CORSMiddleware
  6. from pytrends.request import TrendReq
  7. from datetime import tzinfo
  8. import datetime
  9. import mysql.connector
  10. from mysql.connector import Error
  11. from io import BytesIO
  12. from fastapi.responses import StreamingResponse
  13. import xlsxwriter
  14. import pandas as pd
  15. import dataset
  16. import json
  17. from pytube import extract
  18. import random
  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. #https://m3.hhh.com.tw:18687/docs
  31. hhhMBPath = '../hhh-home-mb'
  32. hhhPCPath = '../hhh-home-pc'
  33. # db = dataset.connect(
  34. # 'mysql://hhh7796hhh:lYmWsu^ujcA1@hhh-v57.cmab1ctkglka.ap-northeast-2.rds.amazonaws.com:3306/xoops?charset=utf8mb4')
  35. #2022/12/13 change
  36. db = dataset.connect( 'mysql://hhh7796hhh:lYmWsu^ujcA1@ec2-3-35-26-49.ap-northeast-2.compute.amazonaws.com:3306/xoops?charset=utf8mb4')
  37. def ExecuteQuery(isql):
  38. #2022/12/13 change
  39. #host='hhh-v57.cmab1ctkglka.ap-northeast-2.rds.amazonaws.com',
  40. connection = mysql.connector.connect(
  41. host='ec2-3-35-26-49.ap-northeast-2.compute.amazonaws.com',
  42. database='xoops',
  43. user='hhh7796hhh',
  44. password='lYmWsu^ujcA1',
  45. use_unicode=True,
  46. charset='utf8',
  47. collation='utf8_unicode_ci'
  48. )
  49. # connection.set_charset_collation('utf8','utf8_general_ci')
  50. cursor = connection.cursor(dictionary=True)
  51. cursor.execute(isql)
  52. if cursor.rowcount == -1:
  53. return cursor.fetchall()
  54. else:
  55. connection.commit()
  56. return cursor.rowcount
  57. def ExecuteCmd(isql):
  58. #2022/12/13 change
  59. #host='hhh-v57.cmab1ctkglka.ap-northeast-2.rds.amazonaws.com',
  60. connection = mysql.connector.connect(
  61. host='ec2-3-35-26-49.ap-northeast-2.compute.amazonaws.com',
  62. database='xoops',
  63. user='hhh7796hhh',
  64. password='lYmWsu^ujcA1'
  65. )
  66. cursor = connection.cursor(dictionary=True)
  67. cursor.execute(isql)
  68. print(cursor.rowcount)
  69. connection.commit()
  70. return None
  71. @app.get("/ExportExecuteDetail")
  72. async def ExportExecuteDetail():
  73. output = BytesIO()
  74. records = ExecuteQuery(""" 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. ExecuteQuery(
  101. "replace INTO stage._hdesigner SELECT * FROM xoops._hdesigner WHERE hdesigner_id IN ('" + designerid.replace(',', "','")+"');")
  102. ExecuteQuery(
  103. "replace INTO stage._hcase SELECT * FROM xoops._hcase WHERE hcase_id IN ('"+caseid.replace(',', "','")+"');")
  104. ExecuteQuery(
  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. ExecuteQuery(
  110. "replace INTO stage._hbrand SELECT * FROM xoops._hbrand WHERE hbrand_id IN ('" + brandid.replace(',', "','")+"');")
  111. ExecuteQuery(
  112. "replace INTO stage._hbrand_page SELECT * FROM xoops._hbrand_page WHERE hbrand_id IN ('" + brandid.replace(',', "','")+"');")
  113. ExecuteQuery(
  114. "replace INTO stage._hproduct SELECT * FROM xoops._hproduct WHERE id IN ('"+productid.replace(',', "','")+"');")
  115. ExecuteQuery(
  116. "replace INTO stage._hproduct_img SELECT * FROM xoops._hproduct_img WHERE hproduct_id IN ('"+productid.replace(',', "','")+"');")
  117. return {"success"}
  118. @app.get("/movecxoopstostage")
  119. def movecxoopstostage(columnid: str = "0"):
  120. ExecuteQuery(
  121. "replace INTO stage._hcolumn SELECT * FROM xoops._hcolumn WHERE hcolumn_id IN ('" + columnid.replace(',', "','")+"');")
  122. ExecuteQuery(
  123. "replace INTO stage._hcolumn_img SELECT * FROM xoops._hcolumn_img WHERE hcolumn_id IN ('" + columnid.replace(',', "','")+"');")
  124. ExecuteQuery(
  125. "replace INTO stage._hcolumn_page SELECT * FROM xoops._hcolumn_page WHERE hcolumn_id IN ('" + columnid.replace(',', "','")+"');")
  126. return {"success"}
  127. @app.get("/genjson")
  128. def genjson(filename: str = "realtime.json"):
  129. jData = json.load(open(hhhMBPath+'/json/data.json', encoding='utf8'))
  130. 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 '首八大%' ")
  131. for x in jData:
  132. # 頂部輪播區-新刊頭
  133. if x['id'] == 0:
  134. records = ExecuteQuery("""SELECT adlogo lo,adlogo_mobile mlo, adhref lk, adlogo_mobile_webp lomwebp, adlogo_webp dwebp FROM _had
  135. WHERE adtype LIKE '新刊頭%'
  136. AND onoff='1'
  137. 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))
  138. ORDER BY cast(SUBSTR(adtype,4) AS DECIMAL)""")
  139. x["data"] = []
  140. for c in records:
  141. a = {'imgUrl': c['mlo'], 'link': str(
  142. c['lk']), 'DimgUrl': c['lo'], 'webp': str(c['lomwebp']), 'Dwebp': str(c['dwebp'])}
  143. x["data"].append(a)
  144. # print(x["data"])
  145. # 主要輪播區-首八大
  146. if x['id'] == 1:
  147. records = ExecuteQuery("""SELECT adlogo lo,adlogo_mobile mlo, adhref lk, adlogo_mobile_webp lomwebp, adlogo_webp dwebp FROM _had
  148. WHERE adtype LIKE '首八大%'
  149. AND onoff='1'
  150. 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))
  151. ORDER BY cast(SUBSTR(adtype,4) AS DECIMAL)""")
  152. x["data"] = []
  153. for c in records:
  154. a = {'imgUrl': c['mlo'], 'link': str(
  155. c['lk']), 'DimgUrl': c['lo'], 'webp': str(c['lomwebp']), 'Dwebp': str(c['dwebp'])}
  156. x["data"].append(a)
  157. # print(x["data"])
  158. #tab區塊-最夯設計, 影音實錄, 專欄文章
  159. if x['id'] == 2:
  160. x["data"] = []
  161. records = ExecuteQuery("""SELECT caption TT ,cover IMG, CONCAT('https://hhh.com.tw/cases/detail/',hcase_id,'/') LK, short_desc txt
  162. from _hcase
  163. left join _hdesigner ON _hcase.hdesigner_id=_hdesigner.hdesigner_id
  164. WHERE
  165. _hcase.onoff='1' AND _hdesigner.onoff='1'
  166. AND(NOW() > sdate)
  167. ORDER BY hcase_id DESC
  168. LIMIT 3""")
  169. a = {'tab': '最夯設計', 'data': []}
  170. for c in records:
  171. ad = {'imgUrl': c['IMG'], 'link': c['LK'],
  172. 'title': c['TT'], 'description': c['txt']}
  173. a['data'].append(ad)
  174. x["data"].append(a)
  175. records = ExecuteQuery("""SELECT title TT,iframe IMG , CONCAT('https://hhh.com.tw/video-post.php?id=',hvideo_id) LK , name
  176. from _hvideo
  177. ORDER BY hvideo_id DESC
  178. LIMIT 4""")
  179. a = {'tab': '影音實錄', 'data': []}
  180. cnt = 0
  181. for c in records:
  182. if cnt == 0:
  183. cnt += 1
  184. continue
  185. tid = extract.video_id(c['IMG'])
  186. timg = "https://img.youtube.com/vi/" + tid+"/hqdefault.jpg"
  187. ad = {'imgUrl': timg, 'link': c['LK'],
  188. 'title': c['name'], 'description': c['TT']}
  189. a['data'].append(ad)
  190. x["data"].append(a)
  191. records = ExecuteQuery("""SELECT ctitle TT,clogo IMG, CONCAT('https://hhh.com.tw/columns/detail/',hcolumn_id,'/') LK, cdesc
  192. from _hcolumn
  193. WHERE onoff='1'
  194. AND NOW() > sdate
  195. ORDER BY hcolumn_id DESC
  196. LIMIT 3""")
  197. a = {'tab': '專欄文章', 'data': []}
  198. for c in records:
  199. ad = {'imgUrl': c['IMG'], 'link': c['LK'],
  200. 'title': c['TT'], 'description': c['cdesc']}
  201. a['data'].append(ad)
  202. x["data"].append(a)
  203. # print(x["data"])
  204. # 主題企劃區
  205. if x['id'] == 3:
  206. records = ExecuteQuery("""SELECT logo lo, CONCAT('https://hhh.com.tw/topic/detail/',htopic_id,'/') lk, `desc`, title FROM _htopic
  207. WHERE onoff = '1'
  208. ORDER BY htopic_id DESC limit 3""")
  209. x["data"] = []
  210. for c in records:
  211. a = {'imgUrl': c['lo'], 'link': str(
  212. c['lk']), 'video': 'false', 'description': c['desc'], 'title': c['title']}
  213. x["data"].append(a)
  214. # print(x["data"])
  215. # 編輯精選
  216. if x['id'] == 4:
  217. records = ExecuteQuery("""SELECT hcolumn_id, ctitle, clogo,cdesc
  218. FROM homepage_set
  219. LEFT JOIN _hcolumn ON mapping_id = hcolumn_id
  220. WHERE outer_set=8
  221. AND homepage_set.onoff='Y'
  222. 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))
  223. ORDER BY inner_sort""")
  224. x["data"] = []
  225. for c in records:
  226. a = {'imgUrl': c['clogo'], 'link': "https://hhh.com.tw/columns/detail/" + str(
  227. c['hcolumn_id']) + "/", 'title': c['ctitle'], 'video': 'false', 'description': c['cdesc']}
  228. x["data"].append(a)
  229. # print(x["data"])
  230. # 首列表廣告
  231. if x['id'] == 5:
  232. records = ExecuteQuery("""SELECT adlogo lo,adlogo_mobile mlo, adhref lk, adlogo_mobile_webp lomwebp, adlogo_webp dwebp FROM _had
  233. WHERE adtype LIKE '首列表廣告%'
  234. AND onoff='1'
  235. 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))
  236. ORDER BY adtype""")
  237. x["data"] = []
  238. for c in records:
  239. a = {'imgUrl': c['mlo'], 'link': str(
  240. c['lk']), 'DimgUrl': c['lo'], 'webp': str(c['lomwebp']), 'Dwebp': str(c['dwebp'])}
  241. x["data"].append(a)
  242. # print(x["data"])
  243. # 來選好物區
  244. if x['id'] == 6:
  245. records = ExecuteQuery(
  246. "SELECT max_row from outer_site_set WHERE title='來選好貨'")
  247. maxrow = 1
  248. for c in records:
  249. maxrow = c['max_row']
  250. 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
  251. , (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
  252. -- SELECT *
  253. FROM homepage_set
  254. left join _hcase ON _hcase.hcase_id=homepage_set.mapping_id AND theme_type='case'-- AND _hcase.onoff = '1'
  255. LEFT JOIN _hproduct ON mapping_id = _hproduct.id AND theme_type='product'-- AND _hproduct.onoff = '1'
  256. LEFT JOIN _hcolumn ON mapping_id = _hcolumn.hcolumn_id AND theme_type='column'-- AND _hcolumn.onoff = '1'
  257. LEFT JOIN _hvideo ON mapping_id = _hvideo.hvideo_id AND theme_type='video'
  258. WHERE homepage_set.onoff='Y'
  259. AND outer_set = (SELECT oss_id from outer_site_set WHERE title='來選好貨')
  260. 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))
  261. ORDER BY outer_set, inner_sort)
  262. UNION
  263. (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) + """)
  264. LIMIT """ + str(maxrow))
  265. x["data"] = []
  266. for c in records:
  267. #print(c)
  268. if c['iframe'] is None:
  269. if isinstance(c['J'], bytearray) or isinstance(c['J'], bytes):
  270. c['J'] = c['J'].decode('utf8')
  271. if isinstance(c['caption'], bytearray) or isinstance(c['caption'], bytes):
  272. c['caption'] = c['caption'].decode('utf8')
  273. if isinstance(c['short_desc'], bytearray) or isinstance(c['short_desc'], bytes):
  274. c['short_desc'] = c['short_desc'].decode('utf8')
  275. a = {'imgUrl': c['J'], 'link': c['url'], 'title': c['caption'],
  276. 'description': c['short_desc'], 'video': 'false'}
  277. else:
  278. tid = extract.video_id(str(c['iframe']))
  279. timg = "https://img.youtube.com/vi/" + tid+"/hqdefault.jpg"
  280. ccaption = ""
  281. cdescription = ""
  282. if isinstance(c['caption'], bytearray):
  283. ccaption = str(c['caption'].decode('utf8'))
  284. else:
  285. ccaption = str(c['caption'])
  286. if c['short_desc'] is not None:
  287. if isinstance(c['short_desc'], bytes):
  288. cdescription = str(c['short_desc'].decode('utf8'))
  289. else:
  290. cdescription = str(c['short_desc'])
  291. a = {'imgUrl': timg, 'link': c['url'], 'title': ccaption,
  292. 'description': cdescription, 'video': tid}
  293. x["data"].append(a)
  294. # print(x["data"])
  295. # 本週推薦
  296. if x['id'] == 7:
  297. records = ExecuteQuery(
  298. "SELECT max_row from outer_site_set WHERE title='本週推薦'")
  299. maxrow = 1
  300. for c in records:
  301. maxrow = c['max_row']
  302. records = ExecuteQuery("""SELECT theme_type, mapping_id, IFNULL(ifnull(ifnull(_hcase.caption,_hcolumn.ctitle),_hproduct.name),_hvideo.title) caption , IFNULL(ifnull(_hcase.cover,_hcolumn.clogo),_hproduct.cover) J, iframe , IFNULL(ifnull(ifnull(_hcase.short_desc,_hcolumn.cdesc),_hproduct.descr),_hvideo.`desc`) short_desc
  303. , (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
  304. -- SELECT *
  305. FROM homepage_set
  306. left join _hcase ON _hcase.hcase_id=homepage_set.mapping_id AND theme_type='case'-- AND _hcase.onoff = '1'
  307. LEFT JOIN _hproduct ON mapping_id = _hproduct.id AND theme_type='product'-- AND _hproduct.onoff = '1'
  308. LEFT JOIN _hcolumn ON mapping_id = _hcolumn.hcolumn_id AND theme_type='column'-- AND _hcolumn.onoff = '1'
  309. LEFT JOIN _hvideo ON mapping_id = _hvideo.hvideo_id AND theme_type='video'
  310. WHERE homepage_set.onoff='Y'
  311. AND outer_set = (SELECT oss_id from outer_site_set WHERE title='本週推薦')
  312. 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))
  313. ORDER BY outer_set, inner_sort
  314. LIMIT """ + str(maxrow))
  315. x["data"] = []
  316. for c in records:
  317. if c['iframe'] is None:
  318. if isinstance(c['J'], bytearray) or isinstance(c['J'], bytes):
  319. c['J'] = c['J'].decode('utf8')
  320. if isinstance(c['caption'], bytearray) or isinstance(c['caption'], bytes):
  321. c['caption'] = c['caption'].decode('utf8')
  322. if isinstance(c['short_desc'], bytearray) or isinstance(c['short_desc'], bytes):
  323. c['short_desc'] = c['short_desc'].decode('utf8')
  324. a = {'imgUrl': c['J'], 'link': c['url'], 'title': c['caption'],
  325. 'description': c['short_desc'], 'video': 'false'}
  326. else:
  327. tid = extract.video_id(str(c['iframe']))
  328. timg = "https://img.youtube.com/vi/" + tid+"/hqdefault.jpg"
  329. ccaption = ""
  330. cdescription = ""
  331. if isinstance(c['caption'], bytearray):
  332. ccaption = str(c['caption'].decode('utf8'))
  333. else:
  334. ccaption = str(c['caption'])
  335. if c['short_desc'] is not None:
  336. if isinstance(c['short_desc'], bytes):
  337. cdescription = str(c['short_desc'].decode('utf8'))
  338. else:
  339. cdescription = str(c['short_desc'])
  340. a = {'imgUrl': timg, 'link': c['url'], 'title': ccaption,
  341. 'description': cdescription, 'video': tid}
  342. x["data"].append(a)
  343. # print(x["data"])
  344. # 粉絲推薦
  345. if x['id'] == 8:
  346. records = ExecuteQuery(
  347. "SELECT max_row from outer_site_set WHERE title='粉絲推薦'")
  348. maxrow = 1
  349. for c in records:
  350. maxrow = c['max_row']
  351. records = ExecuteQuery("""SELECT theme_type, mapping_id, IFNULL(ifnull(ifnull(_hcase.caption,_hcolumn.ctitle),_hproduct.name),_hvideo.title) caption , IFNULL(ifnull(_hcase.cover,_hcolumn.clogo),_hproduct.cover) J, iframe , IFNULL(ifnull(ifnull(_hcase.short_desc,_hcolumn.cdesc),_hproduct.descr),_hvideo.`desc`) short_desc
  352. , (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
  353. -- SELECT *
  354. FROM homepage_set
  355. left join _hcase ON _hcase.hcase_id=homepage_set.mapping_id AND theme_type='case'-- AND _hcase.onoff = '1'
  356. LEFT JOIN _hproduct ON mapping_id = _hproduct.id AND theme_type='product'-- AND _hproduct.onoff = '1'
  357. LEFT JOIN _hcolumn ON mapping_id = _hcolumn.hcolumn_id AND theme_type='column'-- AND _hcolumn.onoff = '1'
  358. LEFT JOIN _hvideo ON mapping_id = _hvideo.hvideo_id AND theme_type='video'
  359. WHERE homepage_set.onoff='Y'
  360. AND outer_set = (SELECT oss_id from outer_site_set WHERE title='粉絲推薦')
  361. 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))
  362. ORDER BY outer_set, inner_sort
  363. LIMIT """ + str(maxrow))
  364. x["data"] = []
  365. for c in records:
  366. if c['iframe'] is None:
  367. if isinstance(c['J'], bytearray) or isinstance(c['J'], bytes):
  368. c['J'] = c['J'].decode('utf8')
  369. if isinstance(c['caption'], bytearray) or isinstance(c['caption'], bytes):
  370. c['caption'] = c['caption'].decode('utf8')
  371. if isinstance(c['short_desc'], bytearray) or isinstance(c['short_desc'], bytes):
  372. c['short_desc'] = c['short_desc'].decode('utf8')
  373. a = {'imgUrl': c['J'], 'link': c['url'], 'title': c['caption'],
  374. 'description': c['short_desc'], 'video': 'false'}
  375. else:
  376. tid = extract.video_id(str(c['iframe']))
  377. timg = "https://img.youtube.com/vi/" + tid+"/hqdefault.jpg"
  378. ccaption = ""
  379. cdescription = ""
  380. if isinstance(c['caption'], bytearray):
  381. ccaption = str(c['caption'].decode('utf8'))
  382. else:
  383. ccaption = str(c['caption'])
  384. if c['short_desc'] is not None:
  385. if isinstance(c['short_desc'], bytes):
  386. cdescription = str(c['short_desc'].decode('utf8'))
  387. else:
  388. cdescription = str(c['short_desc'])
  389. a = {'imgUrl': timg, 'link': c['url'], 'title': ccaption,
  390. 'description': cdescription, 'video': tid}
  391. x["data"].append(a)
  392. # print(x["data"])
  393. if x['id'] == 9:
  394. records = ExecuteQuery(
  395. "SELECT id, (case when youtube_title = '' OR youtube_title IS NULL then (SELECT title FROM _hvideo ORDER BY hvideo_id DESC LIMIT 1) ELSE youtube_title END) T, (case when youtube_id = '' OR youtube_id IS NULL then (SELECT iframe FROM _hvideo ORDER BY hvideo_id DESC LIMIT 1) ELSE youtube_id end) Y FROM site_setup")
  396. for c in records:
  397. x['title'] = ""
  398. if isinstance(c['T'], bytearray):
  399. x['title'] = str(c['T'].decode('utf8'))
  400. else:
  401. x['title'] = str(c['T'])
  402. x['yt'] = extract.video_id(str(c['Y']))
  403. # print(id)
  404. if x['id'] == 10:
  405. records = ExecuteQuery(
  406. "SELECT all_search_tag ast FROM site_setup")
  407. x["data"] = []
  408. for c in records:
  409. x["data"] = c['ast'].split(',')
  410. # print(id)
  411. # print(jData)
  412. """ if not os.path.exists(hhhMBPath):
  413. os.mkdir(hhhMBPath)
  414. with open(hhhMBPath+'/json/' + filename, 'w', encoding='utf-8') as f:
  415. json.dump(jData, f, ensure_ascii=False, indent=4)
  416. if not os.path.exists(hhhPCPath):
  417. os.mkdir(hhhPCPath)
  418. with open(hhhPCPath+'/json/' + filename, 'w', encoding='utf-8') as f:
  419. json.dump(jData, f, ensure_ascii=False, indent=4) """
  420. return jData
  421. @app.get("/gendesigner_list_six")
  422. def gendesigner_list_six(sort: str = "new", page: str="1",city: str = "0", county: str="0",region:str="0",dtype:str="0",dstyle:str="0",budget:str="0",arch:str="0",award:str="0",agent:str="0"):
  423. #jData = json.load(open(hhhMBPath+'/json/designer_list_all.json', encoding='utf8'))
  424. condition = ""
  425. if city != "0":
  426. condition+=""" and (t2.address like '%"""+city+"""%' or t3.address like '%"""+city+"""%') """
  427. if county != "0":
  428. condition+=""" and (t2.address like '%"""+county+"""%' or t3.address like '%"""+county+"""%') """
  429. if region != "0":
  430. condition+=""" and (t2.region like '%"""+region+"""%' or t2.region like '%不限%') """
  431. if dtype != "0":
  432. condition+=""" and (t2.type like '%"""+dtype+"""%' or t2.type like '%不限%') """
  433. if dstyle != "0":
  434. condition+=""" and (t2.style like '%"""+dstyle+"""%' or t2.style like '%不限%') """
  435. if arch != "0":
  436. condition+=""" and license!='' """
  437. if award !="0":
  438. condition+=""" and (t2.awards like '%亞洲設計獎%') """
  439. if agent !="0":
  440. condition+=""" and (t2.guarantee > 0) """
  441. if budget!="0":
  442. if budget==1:
  443. condition+=""" and (t2.min_budget>=0 and t2.min_budget<=1000000) """
  444. elif budget==2:
  445. condition+=""" and (t2.min_budget>=1000001 and t2.min_budget<=2000000) """
  446. elif budget==3:
  447. condition+=""" and (t2.min_budget>=2000001 and t2.min_budget<=3000000) """
  448. elif budget==4:
  449. condition+=""" and (t2.min_budget>=3000001 and t2.min_budget<=4000000) """
  450. elif budget==5:
  451. condition+=""" and (t2.min_budget>=4000001 and t2.min_budget<=5000000) """
  452. elif budget==6:
  453. condition+=""" and (t2.min_budget>=5000001)"""
  454. #jData = json.load(open(hhhMBPath+'/json/designer_list_six.json', encoding='utf8'))
  455. if condition=="":
  456. if page=="1":
  457. # records = db.query("""SELECT d.hdesigner_id,d.img_path,d.title,d.name,(select c.cover from _hcase c where c.hdesigner_id = d.hdesigner_id and c.onoff=1 ORDER BY c.corder ASC ,c.viewed DESC limit 1 ) as cover FROM _hdesigner d left join xoops.designer_branch b on b.designer_id = d.hdesigner_id left join xoops._hawards ha on ha.hdesigner_id = d.hdesigner_id where ha.onoff=1 and d.top="O" GROUP BY d.hdesigner_id Order By rand(); """)
  458. records = db.query("""SELECT t2.hdesigner_id,t2.img_path,t2.name,t2.title,(SELECT t1.cover from _hcase t1 where t1.hdesigner_id = t2.hdesigner_id and t1.onoff=1 ORDER BY t1.corder ASC ,t1.viewed DESC limit 1 ) as cover FROM _hdesigner t2 left JOIN _hcase t1 on t1.hdesigner_id=t2.hdesigner_id left JOIN designer_branch t3 on t1.hdesigner_id=t3.designer_id where t2.onoff=1 and t2.top_six="O" GROUP BY t2.hdesigner_id Order By rand(); """)
  459. else:
  460. records = db.query("""SELECT t2.hdesigner_id,t2.img_path,t2.name,t2.title,(SELECT t1.cover from _hcase t1 where t1.hdesigner_id = t2.hdesigner_id and t1.onoff=1 ORDER BY t1.corder ASC ,t1.viewed DESC limit 1 ) as cover FROM _hdesigner t2 left JOIN _hcase t1 on t1.hdesigner_id=t2.hdesigner_id left JOIN designer_branch t3 on t1.hdesigner_id=t3.designer_id where t2.onoff=1 and t2.top_six!="O" GROUP BY t2.hdesigner_id Order By"""+" "+("t1.sdate" if sort == 'new' else 't1.viewed')+""" DESC LIMIT"""+" "+str((int(page) - 2)*18+12)+""" ,6;""")
  461. else:
  462. records = db.query("""SELECT t2.hdesigner_id,t2.img_path,t2.name,t2.title,(SELECT t1.cover from _hcase t1 where t1.hdesigner_id = t2.hdesigner_id and t1.onoff=1 ORDER BY t1.corder ASC ,t1.viewed DESC limit 1 ) as cover FROM _hdesigner t2 left JOIN _hcase t1 on t1.hdesigner_id=t2.hdesigner_id left JOIN designer_branch t3 on t1.hdesigner_id=t3.designer_id where t2.onoff=1 """+condition+""" GROUP BY t2.hdesigner_id Order By """+" "+("t1.sdate" if sort == 'new' else 't1.viewed')+""" DESC LIMIT"""+" "+str((int(page) - 1)*18)+""" ,6;""")
  463. #print(records)
  464. #print(jData)
  465. jData = []
  466. for c in records:
  467. if "_hcase_img" in c["cover"]:
  468. cover=c["cover"].replace("_hcase_img","_hcase_img_orig")
  469. else:
  470. cover=c["cover"].replace("_hcase","_hcase_orig")
  471. jData.append({"hdesigner_id":str(c["hdesigner_id"]),"img_path":str(c["img_path"]),"name":c["name"],"title":c["title"],"cover":cover} )
  472. #for x,c in zip(jData,records):
  473. # x["hdesigner_id"] = str(c["hdesigner_id"])
  474. # x["img_path"] = str(c["img_path"])
  475. # x["name"] = c["name"]
  476. # x["title"] = c["title"]
  477. # x["cover"] = c["cover"]
  478. return jData
  479. @app.get("/gendesigner_list_twelve")
  480. def gendesigner_list_twelve(sort: str = "new", page: str="1",city: str = "0", county: str="0",region:str="0",dtype:str="0",dstyle:str="0",budget:str="0",arch:str="0",award:str="0",agent:str="0"):
  481. #jData = json.load(open(hhhMBPath+'/json/designer_list_twelve.json', encoding='utf8'))
  482. condition = ""
  483. if city != "0":
  484. condition+=""" and (t2.address like '%"""+city+"""%' or t3.address like '%"""+city+"""%') """
  485. if county != "0":
  486. condition+=""" and (t2.address like '%"""+county+"""%' or t3.address like '%"""+county+"""%') """
  487. if region != "0":
  488. condition+=""" and (t2.region like '%"""+region+"""%' or t2.region like '%不限%') """
  489. if dtype != "0":
  490. condition+=""" and (t2.type like '%"""+dtype+"""%' or t2.type like '%不限%') """
  491. if dstyle != "0":
  492. condition+=""" and (t2.style like '%"""+dstyle+"""%' or t2.style like '%不限%') """
  493. if arch != "0":
  494. condition+=""" and license!='' """
  495. if award !="0":
  496. condition+=""" and (t2.awards like '%亞洲設計獎%') """
  497. if agent !="0":
  498. condition+=""" and (t2.guarantee > 0) """
  499. if budget!="0":
  500. if budget==1:
  501. condition+=""" and (t2.min_budget>=0 and t2.min_budget<=1000000) """
  502. elif budget==2:
  503. condition+=""" and (t2.min_budget>=1000001 and t2.min_budget<=2000000) """
  504. elif budget==3:
  505. condition+=""" and (t2.min_budget>=2000001 and t2.min_budget<=3000000) """
  506. elif budget==4:
  507. condition+=""" and (t2.min_budget>=3000001 and t2.min_budget<=4000000) """
  508. elif budget==5:
  509. condition+=""" and (t2.min_budget>=4000001 and t2.min_budget<=5000000) """
  510. elif budget==6:
  511. condition+=""" and (t2.min_budget>=5000001)"""
  512. if condition=="":
  513. records = db.query("""SELECT t2.hdesigner_id,t2.img_path,t2.name,t2.title,(SELECT t1.cover from _hcase t1 where t1.hdesigner_id = t2.hdesigner_id and t1.onoff=1 ORDER BY t1.corder ASC ,t1.viewed DESC limit 1 ) as cover FROM _hdesigner t2 left JOIN _hcase t1 on t1.hdesigner_id=t2.hdesigner_id left JOIN designer_branch t3 on t1.hdesigner_id=t3.designer_id where t2.onoff=1 and t2.top_six!="O" GROUP BY t2.hdesigner_id Order By"""+" "+("t1.sdate" if sort == 'new' else 't1.viewed')+""" DESC LIMIT"""+" "+str((int(page)-1)*18)+""" ,12;""")
  514. else:
  515. records = db.query("""SELECT t2.hdesigner_id,t2.img_path,t2.name,t2.title,(SELECT t1.cover from _hcase t1 where t1.hdesigner_id = t2.hdesigner_id and t1.onoff=1 ORDER BY t1.corder ASC ,t1.viewed DESC limit 1 ) as cover FROM _hdesigner t2 left JOIN _hcase t1 on t1.hdesigner_id=t2.hdesigner_id left JOIN designer_branch t3 on t1.hdesigner_id=t3.designer_id where t2.onoff=1 """+condition+""" GROUP BY t2.hdesigner_id Order By"""+" "+("t1.sdate" if sort == 'new' else 't1.viewed')+""" DESC LIMIT"""+" "+str((int(page)-1)*18+6)+""" ,12;""")
  516. #print(records)
  517. #print(jData)
  518. #for x,c in zip(jData,records):
  519. # x["hdesigner_id"] = str(c["hdesigner_id"])
  520. # x["img_path"] = str(c["img_path"])
  521. # x["name"] = c["name"]
  522. # x["title"] = c["title"]
  523. # x["cover"] = c["cover"]
  524. jData = []
  525. for c in records:
  526. if "_hcase_img" in c["cover"]:
  527. cover=c["cover"].replace("_hcase_img","_hcase_img_orig")
  528. else:
  529. cover=c["cover"].replace("_hcase","_hcase_orig")
  530. jData.append({"hdesigner_id":str(c["hdesigner_id"]),"img_path":str(c["img_path"]),"name":c["name"],"title":c["title"],"cover":cover} )
  531. return jData
  532. @app.get("/gendesigner_list_all")
  533. def gendesigner_list_all(city: str = "0", county: str="0",region:str="0",dtype:str="0",dstyle:str="0",budget:str="0",arch:str="0",award:str="0",agent:str="0"):
  534. #jData = json.load(open(hhhMBPath+'/json/designer_list_all.json', encoding='utf8'))
  535. condition = ""
  536. if city != "0":
  537. condition+=""" and (t2.address like '%"""+city+"""%' or t3.address like '%"""+city+"""%') """
  538. if county != "0":
  539. condition+=""" and (t2.address like '%"""+county+"""%' or t3.address like '%"""+county+"""%') """
  540. if region != "0":
  541. condition+=""" and (t2.region like '%"""+region+"""%' or t2.region like '%不限%') """
  542. if dtype != "0":
  543. condition+=""" and (t2.type like '%"""+dtype+"""%' or t2.type like '%不限%') """
  544. if dstyle != "0":
  545. condition+=""" and (t2.style like '%"""+dstyle+"""%' or t2.style like '%不限%') """
  546. if arch != "0":
  547. condition+=""" and license!='' """
  548. if award !="0":
  549. condition+=""" and (t2.awards like '%亞洲設計獎%') """
  550. if agent !="0":
  551. condition+=""" and (t2.guarantee > 0) """
  552. if budget!="0":
  553. if budget==1:
  554. condition+=""" and (t2.min_budget>=0 and t2.min_budget<=1000000) """
  555. elif budget==2:
  556. condition+=""" and (t2.min_budget>=1000001 and t2.min_budget<=2000000) """
  557. elif budget==3:
  558. condition+=""" and (t2.min_budget>=2000001 and t2.min_budget<=3000000) """
  559. elif budget==4:
  560. condition+=""" and (t2.min_budget>=3000001 and t2.min_budget<=4000000) """
  561. elif budget==5:
  562. condition+=""" and (t2.min_budget>=4000001 and t2.min_budget<=5000000) """
  563. elif budget==6:
  564. condition+=""" and (t2.min_budget>=5000001)"""
  565. records = db.query("""SELECT t2.hdesigner_id,t2.img_path,t2.name,t2.title,(SELECT t1.cover from _hcase t1 where t1.hdesigner_id = t2.hdesigner_id and t1.onoff=1 ORDER BY t1.corder ASC ,t1.viewed DESC limit 1 ) as cover FROM _hdesigner t2 left JOIN _hcase t1 on t1.hdesigner_id=t2.hdesigner_id left JOIN designer_branch t3 on t1.hdesigner_id=t3.designer_id where t2.onoff=1 """+condition+""" GROUP BY t2.hdesigner_id;""")
  566. #print(records)
  567. #print(jData)
  568. jData = []
  569. for c in records:
  570. if "_hcase_img" in c["cover"]:
  571. cover=c["cover"].replace("_hcase_img","_hcase_img_orig")
  572. else:
  573. cover=c["cover"].replace("_hcase","_hcase_orig")
  574. jData.append({"hdesigner_id":str(c["hdesigner_id"]),"img_path":str(c["img_path"]),"name":c["name"],"title":c["title"],"cover":c["cover"]} )
  575. json.dumps(jData)
  576. #print(jData)
  577. #print(len(jData))
  578. return jData
  579. @app.get("/find_designer_show")
  580. def find_designer_show(cid:str ,type_use: str="computer"):
  581. condition = ""
  582. #jData = json.load(open(hhhMBPath+'/json/designer_list_all.json', encoding='utf8'))
  583. if type_use == "computer":
  584. records = db.query("""SELECT order_computer FROM _hdesigner where hdesigner_id="""+cid+""";""")
  585. jData = []
  586. for c in records:
  587. jData.append({"order_show_type":str(c["order_computer"])} )
  588. json.dumps(jData)
  589. else:
  590. records = db.query("""SELECT order_mb FROM _hdesigner where hdesigner_id="""+cid+""";""")
  591. jData = []
  592. for c in records:
  593. jData.append({"order_show_type":str(c["order_mb"])} )
  594. json.dumps(jData)
  595. #print(records)
  596. #print(jData)
  597. #print(jData)
  598. #print(len(jData))
  599. return jData
  600. @app.get("/find_total")
  601. def find_total(cid:str ,type_use: str):
  602. condition = ""
  603. if type_use=='case':
  604. #jData = json.load(open(hhhMBPath+'/json/designer_list_all.json', encoding='utf8'))
  605. records = db.query("""SELECT count(*) FROM _hcase c
  606. WHERE c.hdesigner_id = '""" + cid + """' AND c.onoff='1'; """ )
  607. elif type_use=='video':
  608. records = db.query("""SELECT count(*) FROM _hvideo v
  609. WHERE v.hdesigner_id = '""" + cid + """' AND display_datetime < NOW() ;""")
  610. elif type_use == 'column':
  611. records = db.query("""SELECT count(*) FROM _hcolumn c
  612. WHERE onoff=1 AND (c.hdesigner_ids LIKE '""" + cid + """,%' OR c.hdesigner_ids LIKE '%,""" + cid + """,%' OR c.hdesigner_ids LIKE '%,""" + cid + """' OR c.hdesigner_ids = '""" + cid + """') ;""")
  613. elif type_use == 'vr360':
  614. records = db.query("""SELECT count(*) FROM _hcase c
  615. WHERE c.hdesigner_id = '""" + cid + """' and istaging != '' AND c.onoff='1' ;""")
  616. jData = []
  617. for c in records:
  618. jData.append({"total":str(c["count(*)"])} )
  619. json.dumps(jData)
  620. #print(records)
  621. #print(jData)
  622. #print(jData)
  623. #print(len(jData))
  624. return jData
  625. @app.get("/find_user_favorite")
  626. def find_user_favorite(user_id: str ,cid:str, type_use: str="designer"):
  627. condition = ""
  628. #jData = json.load(open(hhhMBPath+'/json/designer_list_all.json', encoding='utf8'))
  629. records = db.query("""SELECT * FROM user_favorite where status=0 and user_id="""+user_id+""" and table_id="""+cid+""" and type= '"""+type_use+"""' ;""")
  630. #print(records)
  631. #print(jData)
  632. jData = []
  633. for c in records:
  634. jData.append({"id":str(c["id"]),"user_id":str(c["user_id"]),"type":c["type"],"cid":c["table_id"],"create_time":str(c["create_time"]),"status":str(c["status"])} )
  635. json.dumps(jData)
  636. #print(jData)
  637. #print(len(jData))
  638. return jData
  639. # @app.post("/add_user_favorite")
  640. # def add_user_favorite(user_id: str ,cid:str, type_use: str="designer"):
  641. # records = db.query("""SELECT * FROM user_favorite where status=1 and user_id="""+user_id+""" and table_id="""+cid+""" and type= '"""+type_use+"""' ;""")
  642. # jData = []
  643. # for c in records:
  644. # jData.append({"id":str(c["id"]),"user_id":str(c["user_id"]),"type":c["type"],"cid":c["table_id"],"create_time":str(c["create_time"]),"status":str(c["status"])} )
  645. # json.dumps(jData)
  646. # if len(jData)>0:
  647. # db.query("""UPDATE user_favorite SET status=0 WHERE user_id="""+user_id+""" and table_id="""+cid+""" and type= '"""+type_use+"""';""")
  648. # else:
  649. # records = db.query("""SELECT * FROM user_favorite where status=0 and user_id="""+user_id+""" and table_id="""+cid+""" and type= '"""+type_use+"""' ;""")
  650. # jData = []
  651. # json.dumps(jData)
  652. # if len(jData)==0:
  653. # db.query("""INSERT INTO user_favorite (user_id, type, table_id) values ( """+user_id+""",'"""+type_use+"""',"""+cid+""");""")
  654. # db.commit()
  655. # return True
  656. # @app.post("/delete_user_favorite")
  657. # def delete_user_favorite(user_id: str ,cid:str, type_use: str="designer"):
  658. # records = db.query("""SELECT * FROM user_favorite where status=0 and user_id="""+user_id+""" and table_id="""+cid+""" and type= '"""+type_use+"""' ;""")
  659. # jData = []
  660. # for c in records:
  661. # jData.append({"id":str(c["id"]),"user_id":str(c["user_id"]),"type":c["type"],"cid":c["table_id"],"create_time":str(c["create_time"]),"status":str(c["status"])} )
  662. # json.dumps(jData)
  663. # if len(jData)>0:
  664. # db.query("""UPDATE user_favorite SET status=1 WHERE user_id="""+user_id+""" and table_id="""+cid+""" and type= '"""+type_use+"""';""")
  665. # return True
  666. #===================================================================================================================================
  667. @app.get("/gencase")
  668. def gencase(id: str = "14151", sort: str = "new", page: str="1"):
  669. jData = json.load(open(hhhMBPath+'/json/cases.json', encoding='utf8'))
  670. records = db.query("""SELECT *, c.style cstyle, c.style2 cstyle2 FROM _hcase c
  671. LEFT JOIN _hdesigner d ON c.hdesigner_id = d.hdesigner_id
  672. WHERE c.hcase_id = '""" + id + """' AND c.onoff='1' AND d.onoff='1' and c.sdate < now() """)
  673. #print(jData)
  674. for x in jData:
  675. tmpCaseDetail = []
  676. icount = 0
  677. for c in records:
  678. icount += 1
  679. #tmpCaseDetail.append({"CaseDetailImg": c["cimg"]})
  680. #x["CaseDetail"] = tmpCaseDetail
  681. if c != None:
  682. x["designerid"] = str(c["hdesigner_id"])
  683. x["CaseId"] = str(c["hcase_id"])
  684. x["Casetitle"] = c["caption"]
  685. x["CaseTeamName"] = c["name"]
  686. x["CaseCompany"] = c["title"]
  687. x["CaseCompanyAddress"] = c["address"]
  688. x["CaseCompanyTel"] = c["phone"]
  689. x["CaseCompanyEmail"] = c["mail"]
  690. x["CaseCompanyWeb"] = c["website"]
  691. x["CaseDate"] = str(c["sdate"])
  692. x["CaseViews"] = c["viewed"]
  693. x["CaseCoverImg"] = c["cover"]
  694. x["CaseImgAmount"] = icount
  695. x["CaseStyle"] = c["cstyle"]
  696. x["CaseHouse"] = c["layout"]
  697. x["CaseSize"] = c["area"]
  698. x["CaseProject"] = ""
  699. x["CaseDataMember"] = c["member"]
  700. x["CaseDataSize"] = c["area"]
  701. x["CaseDataStyle"] = c["cstyle"] + c["cstyle2"]
  702. x["CaseDataType"] = c["type"]
  703. x["CaseDataSituation"] = c["condition"]
  704. x["CaseDataImgProvide"] = c["provider"]
  705. x["CaseDataSpace"] = c["layout"]
  706. x["CaseDataMaterial"] = c["materials"]
  707. x["ContactFreeTel"] = c["service_phone"]
  708. x["ContactDesignerImg"] = c["img_path"]
  709. x["CasePageLink"] = ""
  710. x["CasePageprev"] = ""
  711. #x["CaseTag"]= []
  712. #相同設計師的個案
  713. sql = """SELECT * FROM _hcase c
  714. WHERE hdesigner_id = '""" + x["designerid"] + """' and hcase_id <> '""" + x["CaseId"] + """' and sdate < now() AND c.onoff='1'
  715. ORDER BY """ + ("sdate" if sort == 'new' else 'viewed') + """ DESC
  716. LIMIT """ + str((int(page) - 1)*12) + """,12
  717. """
  718. cases = db.query(sql)
  719. tmpOtherCases = []
  720. for other in cases:
  721. tmpOtherCase = {}
  722. tmpOtherCase["designerid"] = str(other["hdesigner_id"])
  723. tmpOtherCase["casesid"] = str(other["hcase_id"])
  724. tmpOtherCase["Views"] = other["viewed"]
  725. tmpOtherCase["ProfileImg"] = other["cover"]
  726. tmpTags = []
  727. for tag in other["tag"].split(','):
  728. tmpTags.append({"Tag": tag , "TagLink": "" })
  729. tmpOtherCase["ProfileTag"] = tmpTags
  730. tmpOtherCases.append(tmpOtherCase)
  731. x["DesignerProfile"] = tmpOtherCases
  732. #相同風格的個案
  733. sql = """SELECT * FROM _hcase c
  734. WHERE style = '""" + x["CaseStyle"] + """' and hcase_id <> '""" + x["CaseId"] + """' and sdate < now() AND c.onoff='1'
  735. ORDER BY """ + ("sdate" if sort == 'new' else 'viewed') + """ DESC
  736. LIMIT """ + str((int(page) - 1)*12) + """,12
  737. """
  738. cases = db.query(sql)
  739. tmpOtherCases = []
  740. for other in cases:
  741. tmpOtherCase = {}
  742. tmpOtherCase["designerid"] = str(other["hdesigner_id"])
  743. tmpOtherCase["casesid"] = str(other["hcase_id"])
  744. tmpOtherCase["Views"] = other["viewed"]
  745. tmpOtherCase["ProfileImg"] = other["cover"]
  746. tmpTags = []
  747. for tag in other["tag"].split(','):
  748. tmpTags.append({"Tag": tag , "TagLink": "" })
  749. tmpOtherCase["ProfileTag"] = tmpTags
  750. tmpOtherCases.append(tmpOtherCase)
  751. x["StyleProfile"] = tmpOtherCases
  752. #相同風格的RANDOM 10筆
  753. #cases = db.query("""SELECT * FROM _hcase c
  754. #WHERE style = '""" + x["CaseStyle"] + """' and hcase_id <> '""" + x["CaseId"] + """' and sdate < now() AND c.onoff='1'
  755. #ORDER BY RAND()
  756. #LIMIT 10
  757. #""")
  758. """ tmpOtherCases = []
  759. for other in cases:
  760. tmpOtherCase = {}
  761. tmpOtherCase["designerid"] = str(other["hdesigner_id"])
  762. tmpOtherCase["casesid"] = str(other["hcase_id"])
  763. tmpOtherCase["PortfoliolImg"] = other["cover"]
  764. tmpOtherCase["PortfoliolLink"] = ""
  765. tmpOtherCase["PortfoliolImgAlt"] = other["caption"]
  766. tmpOtherCases.append(tmpOtherCase)
  767. x["OtherStylePortfolio"]= tmpOtherCases """
  768. # print(x)
  769. # print(jData)
  770. """ if not os.path.exists(hhhMBPath):
  771. os.mkdir(hhhMBPath)
  772. with open(hhhMBPath+'/json/cases-' + id + '.json', 'w', encoding='utf-8') as f:
  773. json.dump(jData, f, ensure_ascii=False, indent=4) """
  774. return jData
  775. @app.get("/gendesigner")
  776. def gendesigner(id: str = "14151"):
  777. jData = json.load(open(hhhMBPath+'/json/designers.json', encoding='utf8'))
  778. records = db.query("""SELECT *, ci.name cimg FROM _hcase c
  779. LEFT JOIN _hcase_img ci ON c.hcase_id = ci.hcase_id
  780. LEFT JOIN _hdesigner d ON c.hdesigner_id = d.hdesigner_id
  781. WHERE d.hdesigner_id = '""" + id + """' AND c.onoff='1' AND d.onoff='1' """)
  782. # print(jData)
  783. for x in jData:
  784. tmpCaseDetail = []
  785. icount = 0
  786. for c in records:
  787. icount += 1
  788. # tmpCaseDetail.append({"CaseDetailImg":c["cimg"]})
  789. x["id"] = c["hdesigner_id"]
  790. x["BannerImg"] = c["background"]
  791. x["CompanyName"] = c["title"]
  792. x["DesignerName"] = c["name"]
  793. x["Designerimg"] = c["img_path"]
  794. x["Description"] = c["seo"]
  795. x["Approve"] = c["position"]
  796. x["Basics"] = [
  797. {"title": "免費專線:",
  798. "link": c["service_phone"], "data": c["service_phone"]},
  799. {"title": "諮詢專線:", "link": c["phone"], "data": c["phone"]},
  800. {"title": "諮詢專線:", "link": c["phone"], "data": c["phone"]},
  801. {"title": "公司傳真:", "link": c["fax"], "data": c["fax"]},
  802. {"title": "公司地址:", "link": c["address"], "data": c["address"]},
  803. {"title": "電子信箱:", "link": c["mail"], "data": c["mail"]},
  804. {"title": "公司網址:", "link": c["website"], "data": c["website"]}
  805. ]
  806. x["FreeCall"] = c["service_phone"]
  807. x["ConsoleCall_1"] = c["phone"]
  808. x["ConsoleCall_2"] = c["phone"]
  809. x["Fax"] = c["fax"]
  810. x["Address"] = c["address"]
  811. x["Email"] = c["mail"]
  812. x["Web"] = c["website"]
  813. x["Branches"] = [
  814. {"title": "分公司地址:", "link": "台北市中山區林森北路50號4樓之一",
  815. "data": "台北市中山區林森北路50號4樓之一"},
  816. {"title": "分公司電話:", "link": "tel:02-2562-7755", "data": "02-2562-7755"},
  817. {"title": "分公司傳真:", "link": "tel:02-2562-7002", "data": "02-2562-7002"},
  818. {"title": "分公司地址:", "link": "上海市闵行区东川路2688号", "data": "上海市闵行区东川路2688号"}
  819. ]
  820. x["Budget"] = c["budget"]
  821. x["Square"] = c["area"]
  822. x["SpecialCase"] = c["special"]
  823. x["Charge"] = c["charge"]
  824. x["Pay"] = c["payment"]
  825. x["WorkLoc"] = c["region"]
  826. x["WorkType"] = c["type"]
  827. x["WorkStyle"] = c["style"]
  828. x["WorkBudget"] = c["budget"]
  829. x["Terms"] = [
  830. {"title": "接案預算:", "data": c["budget"]},
  831. {"title": "接案坪數:", "data": c["area"]},
  832. {"title": "特殊接案:", "data": c["special"]},
  833. {"title": "收費方式:", "data": c["charge"]},
  834. {"title": "付費方式:", "data": c["payment"]},
  835. {"title": "接案區域:", "data": c["region"]},
  836. {"title": "接案類型:", "data": c["type"]},
  837. {"title": "接案風格:", "data": c["style"]}
  838. ]
  839. x["scMedia"] = [
  840. {"name": "Facebook", "img": "https://hhh.com.tw/assets/images/rv_web/fb.svg",
  841. "link": c["fbpageurl"]},
  842. {"name": "Line", "img": "https://hhh.com.tw/assets/images/rv_web/line.svg",
  843. "link": c["line_link"]},
  844. {"name": "Wechat", "img": "https://hhh.com.tw/assets/images/rv_web/wechat.svg",
  845. "link": c["fbpageurl"]},
  846. {"name": "email", "img": "https://hhh.com.tw/assets/images/rv_web/share.svg",
  847. "link": c["mail"]},
  848. {"name": "Like", "img": "https://hhh.com.tw/assets/images/rv_web/like-o.svg", "link": ""}
  849. ]
  850. x["Content"] = [
  851. {
  852. "Title": "設計師作品",
  853. "mb_title": "作品",
  854. "Tabtag": "intro",
  855. "Display_mb": "true",
  856. "isActive": "true",
  857. "Carddata": [
  858. ]
  859. },
  860. {
  861. "Title": "設計師影音",
  862. "mb_title": "影音",
  863. "Tabtag": "video",
  864. "Display_mb": "true",
  865. "isActive": "true",
  866. "Carddata": [
  867. ]
  868. },
  869. {
  870. "Title": "設計師專欄",
  871. "mb_title": "專欄",
  872. "Tabtag": "columns",
  873. "Display_mb": "true",
  874. "isActive": "true",
  875. "Carddata": [
  876. ]
  877. },
  878. {
  879. "Title": "VR360",
  880. "mb_title": "",
  881. "Tabtag": "vr360",
  882. "Display_mb": "false",
  883. "isActive": "true",
  884. "Carddata": [
  885. ]
  886. },
  887. {
  888. "Title": "設計師公司簡介",
  889. "mb_title": "公司簡介",
  890. "Tabtag": "company",
  891. "Display_mb": "true",
  892. "isActive": "true",
  893. "Carddata": [
  894. ],
  895. "info": [
  896. {"title": "設計理念", "data": "空間設計的美學藝術,蔡岳儒總監更能將日式精闢的手工藝術融入台灣的設計與工程,更將留日所學發揚光大明確的把結構、 動線、收納、光線與品味融入建築、景觀與室內三大空間之中,藉由點線面展現出空間的獨特性,並賦予空間延續的生命活力。"},
  897. {"title": "公司統編", "data": "經濟部/財政部登記有案:54290717"},
  898. {"title": "相關經歷", "data": "蔡岳儒<br>◆現任/恆岳空間設計 主持設計師<br>◆學歷/東京デザイナー学院卒業<br>◆經歷/十餘年設計、工程經歷。"},
  899. {"title": "專業證照",
  900. "data": "建築師證書 高恒悌 (101) 專高建字第000013號<br>建築物室內裝修專業技術人員登記證 高恒悌 第40EC116787號"},
  901. {"title": "獲獎紀錄", "data": "2020年雪梨設計獎SYDNEY Design Awards GIOD-Quality Arena<br>2020年雪梨設計獎SYDNEY Design Awards SELECTION- Life Savoring"}
  902. ]
  903. }
  904. ]
  905. # print(x)
  906. # print(jData)
  907. """ if not os.path.exists(hhhMBPath):
  908. os.mkdir(hhhMBPath)
  909. with open(hhhMBPath+'/json/designers-' + id + '.json', 'w', encoding='utf-8') as f:
  910. json.dump(jData, f, ensure_ascii=False, indent=4) """
  911. return jData
  912. @app.get("/gencolumn")
  913. def gencolumn(id: str = "6392", sort: str = "new", page: str="1"):
  914. jData = json.load(open(hhhMBPath+'/json/Columns.json', encoding='utf8'))
  915. records = db.query("""SELECT * FROM _hcolumn c
  916. WHERE c.hcolumn_id = '""" + id + """' AND c.onoff='1' """)
  917. #print(id)
  918. for x in jData:
  919. icount = 0
  920. c = None
  921. for c in records:
  922. icount += 1
  923. if c != None:
  924. x["Columnsid"] = str(c["hcolumn_id"])
  925. x["Columnstitle"] = c["ctitle"]
  926. x["ColumnsCoverImg"] = c["clogo"]
  927. x["ColumnsDate"] = str(c["sdate"])
  928. x["ColumnsViews"] = str(c["viewed"])
  929. if page == "1":
  930. x["ColumnsContent"] = c["page_content"]
  931. tmpTags = []
  932. for tag in c["ctag"].split(','):
  933. tmpTags.append({"Tag": tag})
  934. x["ColumnsTag"] = tmpTags
  935. x["author_inf"] = c["extend_str"]
  936. #相同類別的最新12筆
  937. sql = """SELECT * FROM _hcolumn c
  938. 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'
  939. ORDER BY """ + ("sdate" if sort == 'new' else 'viewed') + """ DESC
  940. LIMIT """ + str((int(page) - 1)*12) + """,12
  941. """
  942. ctypes = db.query(sql)
  943. tmpOtherCols = []
  944. for other in ctypes:
  945. tmpOtherCol = {}
  946. tmpOtherCol["Columnsid"] = str(other["hcolumn_id"])
  947. tmpOtherCol["ColumnsCoverImg"] = other["clogo"]
  948. tmpOtherCol["Views"] = other["viewed"]
  949. tmpOtherCol["Columnstitle"] = other["ctitle"]
  950. tmpTags = []
  951. for tag in other["ctag"].split(','):
  952. tmpTags.append({"Tag": tag})
  953. tmpOtherCol["ColumnsTag"] = tmpTags
  954. tmpOtherCols.append(tmpOtherCol)
  955. x["OtherColumns"] = tmpOtherCols
  956. #print(x)
  957. # print(jData)
  958. """ if not os.path.exists(hhhMBPath):
  959. os.mkdir(hhhMBPath)
  960. with open(hhhMBPath+'/json/Columns-' + id + '.json', 'w', encoding='utf-8') as f:
  961. json.dump(jData, f, ensure_ascii=False, indent=4) """
  962. return jData
  963. @app.get("/getColumnAds")
  964. def getColumnAds():
  965. ads = []
  966. records = db.query("""SELECT adlogo_mobile imgUrl, adlogo DimgUrl, adhref link
  967. FROM _had hh
  968. WHERE adtype LIKE '專欄首大%'
  969. AND hh.onoff='1'
  970. and NOW() BETWEEN start_time AND end_time
  971. ORDER BY cast(SUBSTR(adtype, 4) AS DECIMAL) """)
  972. """ for x in records:
  973. ads.append(x) """
  974. ads.extend(records)
  975. rData = json.loads(json.dumps(ads))
  976. #print(json.dumps(ads))
  977. return rData
  978. """ if __name__ == "__main__":
  979. uvicorn.run(app, host="0.0.0.0", port=8000) """
  980. @app.get("/genemering")
  981. async def genemering():
  982. id_use = []
  983. ids = db.query("""SELECT hdesigner_id FROM _hdesigner d where d.emering=1 and d.onoff='1' order by rand();""")
  984. for c in ids:
  985. id_use.append(str(c["hdesigner_id"]))
  986. # with dataset.connect(connstr) as db:
  987. # jData = json.load(open(hhhMBPath+'/json/designers.json', encoding='utf8'))
  988. jData_all = []
  989. for id in id_use:
  990. cases = db.query("""SELECT tag,cover,caption,hcase_id,viewed,sdate,style,style2,type,`condition` FROM _hcase c WHERE c.hdesigner_id = '""" + id + """' AND c.onoff='1' ORDER BY sdate DESC LIMIT 6 """ )
  991. cases_list = []
  992. for case in cases:
  993. tag_use = ''
  994. if case['style']!='':
  995. tag_use += case['style'].strip()
  996. tag_use += ','
  997. if case['style2']!='':
  998. tag_use += case['style2'].strip()
  999. tag_use += ','
  1000. if case['type']!='':
  1001. tag_use += case['type'].strip()
  1002. tag_use += ','
  1003. if case['condition']!='':
  1004. tag_use += case['condition'].strip()
  1005. tmpobj = {
  1006. "url": "https://hhh.com.tw/cases/detail/d/"+str(case["hcase_id"]),
  1007. "imgUrl": case["cover"].replace('/_hcase/', '/_hcase_orig/').replace('/_hcase_img/', '/_hcase_img_orig/'),
  1008. "title": case["caption"],
  1009. "tag": [{"name": tag, "link": "https://hhh.com.tw/search/lists/case/{}-keyword/".format(tag)} for tag in tag_use.split(',')],
  1010. # "tag": [{"name": tag, "link": "https://hhh.com.tw/search/lists/case/{}-keyword/".format(tag)} for tag in case["tag"].split(',')],
  1011. "views": case["viewed"],
  1012. "dateSort": str(case["sdate"])
  1013. }
  1014. cases_list.append(tmpobj)
  1015. records = db.query("""SELECT * FROM _hdesigner d WHERE d.hdesigner_id = '""" + id + """' AND d.onoff='1' """)
  1016. for c in records:
  1017. if c["service_phone"]!='':
  1018. part1=c["service_phone"][0:4]
  1019. part2=c["service_phone"][4:7]
  1020. part3=c["service_phone"][7:10]
  1021. part4=c["service_phone"].split(',')[1]
  1022. service_phone = part1+'-'+part2+'-'+part3+'#'+part4
  1023. else:
  1024. service_phone=''
  1025. jData={"hdesignerId":str(c["hdesigner_id"]),
  1026. "designerName":str(c["name"]),
  1027. "companyName": str(c["title"]),
  1028. 'designerBigImg':"./img/"+id,
  1029. "designerIdea":str(c["idea"]),
  1030. "website":str(c["website"]),
  1031. "servicePhone":service_phone,
  1032. "fbUrl":str(c["fbpageurl"]),
  1033. "cardData": cases_list
  1034. }
  1035. jData_all.append(jData)
  1036. json.dumps(jData_all)
  1037. return jData_all
  1038. from typing import List
  1039. @app.get("/genemering_case")
  1040. async def genemering_case():
  1041. id_use = []
  1042. ids = db.query("""SELECT hdesigner_id FROM _hdesigner d where d.emering=1 and d.onoff='1' order by rand();""")
  1043. for c in ids:
  1044. id_use.append(str(c["hdesigner_id"]))
  1045. # with dataset.connect(connstr) as db:
  1046. # jData = json.load(open(hhhMBPath+'/json/designers.json', encoding='utf8'))
  1047. jData_all = []
  1048. for id in id_use:
  1049. cases = db.query("""SELECT tag,cover,caption,hcase_id,viewed,sdate,style,style2,type,`condition` FROM _hcase c WHERE c.hdesigner_id = '""" + id + """' AND c.onoff='1' ORDER BY sdate DESC LIMIT 6 """ )
  1050. for case in cases:
  1051. tag_use = ''
  1052. if case['style']!='':
  1053. tag_use += case['style'].strip()
  1054. tag_use += ','
  1055. if case['style2']!='':
  1056. tag_use += case['style2'].strip()
  1057. tag_use += ','
  1058. if case['type']!='':
  1059. tag_use += case['type'].strip()
  1060. tag_use += ','
  1061. if case['condition']!='':
  1062. tag_use += case['condition'].strip()
  1063. tmpobj = {
  1064. "url": "https://hhh.com.tw/cases/detail/d/"+str(case["hcase_id"]),
  1065. "imgURL": case["cover"].replace('/_hcase/', '/_hcase_orig/').replace('/_hcase_img/', '/_hcase_img_orig/'),
  1066. "title": case["caption"],
  1067. "tag": [{"name": tag, "link": "https://hhh.com.tw/search/lists/case/{}-keyword/".format(tag)} for tag in tag_use.split(',')],
  1068. # "tag": [{"name": tag, "link": "https://hhh.com.tw/search/lists/case/{}-keyword/".format(tag)} for tag in case["tag"].split(',')],
  1069. "views": case["viewed"],
  1070. "dateSort": str(case["sdate"])
  1071. }
  1072. jData_all.append(tmpobj)
  1073. random.shuffle(jData_all)
  1074. json.dumps(jData_all)
  1075. return jData_all[0:6]
  1076. @app.get("/genemering_calculator_count")
  1077. async def genemering_calculator_count():
  1078. counts_use = []
  1079. counts = db.query("""SELECT count(1) FROM calculator;""")
  1080. for c in counts:
  1081. counts_use.append(str(c["count(1)"]))
  1082. return counts_use
  1083. # with dataset.connect(connstr) as db:
  1084. # jData = json.load(open(hhhMBPath+'/json/designers.json', encoding='utf8'))
  1085. # cases = db.query("""SELECT tag,cover,caption,hcase_id,viewed,sdate,style,style2,type,`condition` FROM _hcase c WHERE c.hdesigner_id = '""" + id + """' AND c.onoff='1' ORDER BY sdate DESC LIMIT 6 """ )
  1086. # cases_list = []
  1087. # for case in cases:
  1088. # tag_use = ''
  1089. # if case['style']!='':
  1090. # tag_use += case['style'].strip()
  1091. # tag_use += ','
  1092. # if case['style2']!='':
  1093. # tag_use += case['style2'].strip()
  1094. # tag_use += ','
  1095. # if case['type']!='':
  1096. # tag_use += case['type'].strip()
  1097. # tag_use += ','
  1098. # if case['condition']!='':
  1099. # tag_use += case['condition'].strip()
  1100. # tmpobj = {
  1101. # "url": "https://hhh.com.tw/cases/detail/d/"+str(case["hcase_id"]),
  1102. # "imgURL": case["cover"].replace('/_hcase/', '/_hcase_orig/').replace('/_hcase_img/', '/_hcase_img_orig/'),
  1103. # "title": case["caption"],
  1104. # "tag": [{"name": tag, "link": "https://hhh.com.tw/search/lists/case/{}-keyword/".format(tag)} for tag in tag_use.split(',')],
  1105. # # "tag": [{"name": tag, "link": "https://hhh.com.tw/search/lists/case/{}-keyword/".format(tag)} for tag in case["tag"].split(',')],
  1106. # "views": case["viewed"],
  1107. # "dateSort": str(case["sdate"])
  1108. # }
  1109. # cases_list.append(tmpobj)
  1110. # records = db.query("""SELECT * FROM _hdesigner d WHERE d.hdesigner_id = '""" + id + """' AND d.onoff='1' """)
  1111. # jData = []
  1112. # for c in records:
  1113. # if c["service_phone"]!='':
  1114. # part1=c["service_phone"][0:4]
  1115. # part2=c["service_phone"][4:7]
  1116. # part3=c["service_phone"][7:10]
  1117. # part4=c["service_phone"].split(',')[1]
  1118. # service_phone = part1+'-'+part2+'-'+part3+'#'+part4
  1119. # else:
  1120. # service_phone=''
  1121. # jData.append({"hdesigner_id":str(c["hdesigner_id"]),
  1122. # "DesignerName":str(c["name"]),
  1123. # "CompanyName": str(c["title"]),
  1124. # 'Designerbigimg':"./img/"+id,
  1125. # "DesignerIdea":str(c["idea"]),
  1126. # "Website":str(c["website"]),
  1127. # "Service_phone":service_phone,
  1128. # "FB_url":str(c["fbpageurl"]),
  1129. # "Carddata": cases_list
  1130. # })
  1131. # json.dumps(jData)
  1132. # return jData
  1133. # check_len=[]
  1134. # for c in records:
  1135. # check_len.append(c)
  1136. # if len(check_len)==0:
  1137. # return []
  1138. # # print(jData)
  1139. # for x in jData:
  1140. # tmpCaseDetail = []
  1141. # icount = 0
  1142. # for c in records:
  1143. # icount += 1
  1144. # # tmpCaseDetail.append({"CaseDetailImg":c["cimg"]})
  1145. # if page == "1":
  1146. # x["id"] = c["hdesigner_id"]
  1147. # x["BannerImg"] = c["background"]
  1148. # x["BannerImg_mobile"] = c['background_mobile']
  1149. # x["CompanyName"] = c["title"]
  1150. # x["DesignerName"] = c["name"]
  1151. # x["Designerimg"] = c["img_path"]
  1152. # x["Description"] = c["seo"]
  1153. # x["Approve"] = c["position"]
  1154. # x["FB_link"] = c["fbpageurl"]
  1155. # # x["order_computer"] = c["order_computer"]
  1156. # # x["order_mb"] = c["order_mb"]
  1157. # if c["service_phone"]!='':
  1158. # part1=c["service_phone"][0:4]
  1159. # part2=c["service_phone"][4:7]
  1160. # part3=c["service_phone"][7:10]
  1161. # part4=c["service_phone"].split(',')[1]
  1162. # service_phone = part1+'-'+part2+'-'+part3+'#'+part4
  1163. # else:
  1164. # service_phone=''
  1165. # phone_list=[]
  1166. # for k1 in c["phone"].split(','):
  1167. # phone_list.append({"title": "諮詢專線:", "link":'tel:'+k1, "data":k1})
  1168. # x["Basics"] = []
  1169. # if service_phone!='':
  1170. # x["Basics"].append({"title": "免費專線:","link": 'tel:'+c["service_phone"], "data": service_phone})
  1171. # for k2 in phone_list:
  1172. # x["Basics"].append(k2)
  1173. # if len(c["fax"])!=0:
  1174. # x["Basics"].append({"title": "公司傳真:", "link": "fax:"+c["fax"], "data": c["fax"]})
  1175. # if len(c["address"])!=0:
  1176. # x["Basics"].append({"title": "公司地址:", "link": "https://www.google.com/search?q="+c["address"], "data": c["address"]})
  1177. # if len(c["mail"])!=0:
  1178. # x["Basics"].append({"title": "電子信箱:", "link": "mailto:"+c["mail"], "data": c["mail"]})
  1179. # if len(c["website"])!=0:
  1180. # x["Basics"].append({"title": "公司網址:", "link": c["website"], "data": c["website"]})
  1181. # blog_list=re.findall(r'href="(.*?)"',c["blog"])
  1182. # if len(blog_list)==0:
  1183. # blog_list=re.findall(r'http.*',c["blog"])
  1184. # if len(blog_list)!=0:
  1185. # for k3 in blog_list:
  1186. # x["Basics"].append({"title": "其他連結:", "link": k3, "data": k3})
  1187. # # x["Basics"] = [
  1188. # # {"title": "免費專線:","link": 'tel:'+c["service_phone"], "data": service_phone},
  1189. # # # {"title": "諮詢專線:", "link": c["phone"], "data": c["phone"]},
  1190. # # {"title": "諮詢專線:", "link": c["phone"], "data": c["phone"]},
  1191. # # {"title": "公司傳真:", "link": c["fax"], "data": c["fax"]},
  1192. # # {"title": "公司地址:", "link": c["address"], "data": c["address"]},
  1193. # # {"title": "電子信箱:", "link": c["mail"], "data": c["mail"]},
  1194. # # {"title": "公司網址:", "link": c["website"], "data": c["website"]}
  1195. # # ]
  1196. # x["FreeCall"] = c["service_phone"]
  1197. # x["ConsoleCall_1"] = c["phone"]
  1198. # x["ConsoleCall_2"] = c["phone"]
  1199. # x["Fax"] = c["fax"]
  1200. # x["Address"] = c["address"]
  1201. # x["Email"] = c["mail"]
  1202. # x["Web"] = c["website"]
  1203. # x["Branches"] = []
  1204. # branches = db.query("""SELECT * FROM designer_branch br
  1205. # WHERE br.designer_id = '""" + id + """' """)
  1206. # for branch in branches:
  1207. # tmpobj = {
  1208. # "title": branch["title"],
  1209. # "address": branch["address"],
  1210. # "address_link" : "https://www.google.com/search?q="+branch["address"],
  1211. # "tel": branch["tel"],
  1212. # "tel_link": "tel:"+branch["tel"],
  1213. # "fax": branch["fax"],
  1214. # "fax_link": "fax:"+branch["fax"]
  1215. # }
  1216. # x["Branches"].append(tmpobj)
  1217. # x["Budget"] = c["budget"]
  1218. # x["Square"] = c["area"]
  1219. # x["SpecialCase"] = c["special"]
  1220. # x["Charge"] = c["charge"]
  1221. # x["Pay"] = c["payment"]
  1222. # x["WorkLoc"] = c["region"]
  1223. # x["WorkType"] = c["type"]
  1224. # x["WorkStyle"] = c["style"]
  1225. # x["WorkBudget"] = c["budget"]
  1226. # x["Terms"] = []
  1227. # if c["budget"]!='':
  1228. # x["Terms"].append({"title": "接案預算:", "data": c["budget"]})
  1229. # if c["area"]!='':
  1230. # x["Terms"].append({"title": "接案坪數:", "data": c["area"]})
  1231. # if c["special"]!='':
  1232. # x["Terms"].append({"title": "特殊接案:", "data": c["special"]})
  1233. # if c["charge"]!='':
  1234. # x["Terms"].append({"title": "收費方式:", "data": c["charge"]})
  1235. # if c["payment"]!='':
  1236. # x["Terms"].append({"title": "付費方式:", "data": c["payment"]})
  1237. # if c["region"]!='':
  1238. # x["Terms"].append({"title": "接案區域:", "data": c["region"]})
  1239. # if c["type"]!='':
  1240. # x["Terms"].append({"title": "接案類型:", "data": c["type"]})
  1241. # if c["style"]!='':
  1242. # x["Terms"].append({"title": "接案風格:", "data": c["style"]})
  1243. # x["scMedia"] = [
  1244. # {"name": "Facebook", "img": "https://hhh.com.tw/assets/images/rv_web/fb.svg",
  1245. # "link": c["fbpageurl"]},
  1246. # {"name": "Line", "img": "https://hhh.com.tw/assets/images/rv_web/line.svg",
  1247. # "link": c["line_link"]},
  1248. # {"name": "Wechat", "img": "https://hhh.com.tw/assets/images/rv_web/wechat.svg",
  1249. # "link": c["fbpageurl"]},
  1250. # {"name": "email", "img": "https://hhh.com.tw/assets/images/rv_web/share.svg",
  1251. # "link": c["mail"]},
  1252. # {"name": "Like", "img": "https://hhh.com.tw/assets/images/rv_web/like-o.svg", "link": ""}
  1253. # ]
  1254. # x_info = []
  1255. # if len(c["idea"])!=0:
  1256. # x_info.append({"title": "設計理念", "data": c["idea"]})
  1257. # if len(c["taxid"])!=0:
  1258. # x_info.append( {"title": "公司統編", "data": c["taxid"]})
  1259. # if len(c["career"])!=0:
  1260. # x_info.append({"title": "相關經歷", "data": c["career"]})
  1261. # if len(c["license"])!=0:
  1262. # x_info.append( {"title": "專業證照", "data": c["license"].replace('\r\n','<br />')})
  1263. # if len(c["awards"])!=0:
  1264. # x_info.append( {"title": "獲獎紀錄", "data": c["awards"].replace('\r\n','<br />')})
  1265. # x["Content"] = [
  1266. # {
  1267. # "Title": "設計師作品",
  1268. # "mb_title": "作品",
  1269. # "Tabtag": "intro",
  1270. # "Display_mb": "true",
  1271. # "isActive": "true",
  1272. # "Carddata": [],
  1273. # "total_all":0
  1274. # },
  1275. # {
  1276. # "Title": "設計師影音",
  1277. # "mb_title": "影音",
  1278. # "Tabtag": "video",
  1279. # "Display_mb": "true",
  1280. # "isActive": "true",
  1281. # "Carddata": [],
  1282. # "total_all":0
  1283. # },
  1284. # {
  1285. # "Title": "設計師專欄",
  1286. # "mb_title": "專欄",
  1287. # "Tabtag": "columns",
  1288. # "Display_mb": "true",
  1289. # "isActive": "true",
  1290. # "Carddata": [],
  1291. # "total_all":0
  1292. # },
  1293. # {
  1294. # "Title": "VR360",
  1295. # "mb_title": "VR",
  1296. # "Tabtag": "vr360",
  1297. # "Display_mb": "false",
  1298. # "isActive": "true",
  1299. # "Carddata": [],
  1300. # "total_all":0
  1301. # },
  1302. # {
  1303. # "Title": "設計師公司簡介",
  1304. # "mb_title": "公司簡介",
  1305. # "Tabtag": "company",
  1306. # "Display_mb": "true",
  1307. # "isActive": "true",
  1308. # "Carddata": [],
  1309. # "info":x_info
  1310. # # "info": [
  1311. # # {"title": "設計理念", "data": c["idea"]},
  1312. # # {"title": "公司統編", "data": c["taxid"]},
  1313. # # {"title": "相關經歷", "data": c["career"]},
  1314. # # {"title": "專業證照", "data": c["license"]},
  1315. # # {"title": "獲獎紀錄", "data": c["awards"]}
  1316. # # ]
  1317. # }
  1318. # ]
  1319. # records = db.query("""SELECT count(1) FROM _hcase c WHERE c.hdesigner_id = '""" + id + """' AND c.onoff='1'; """ )
  1320. # for c in records:
  1321. # x["Content"][0]["total_all"] = str(c["count(1)"])
  1322. # records = db.query("""SELECT count(1) FROM _hvideo v WHERE v.hdesigner_id = '""" + id + """' AND display_datetime < NOW() and iframe<>'' ;""")
  1323. # for c in records:
  1324. # x["Content"][1]["total_all"] = str(c["count(1)"])
  1325. # 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 + """') ;""")
  1326. # for c in records:
  1327. # x["Content"][2]["total_all"] = str(c["count(1)"])
  1328. # records = db.query("""SELECT count(1) FROM _hcase c WHERE c.hdesigner_id = '""" + id + """' and istaging != '' AND c.onoff='1' ;""")
  1329. # for c in records:
  1330. # x["Content"][3]["total_all"] = str(c["count(1)"])
  1331. # # 設計師作品
  1332. # x["Content"][0]["Carddata"] = []
  1333. # cases = db.query("""SELECT tag,cover,caption,hcase_id,viewed,sdate,style,style2,type,`condition` FROM _hcase c
  1334. # WHERE c.hdesigner_id = '""" + id + """' AND c.onoff='1'
  1335. # ORDER BY """ + ("sdate" if sort == 'new' else 'corder ASC,viewed') + """ DESC
  1336. # LIMIT """ + str((int(page) - 1)*12) + """,12
  1337. # """)
  1338. # for case in cases:
  1339. # tag_use = ''
  1340. # if case['style']!='':
  1341. # tag_use += case['style'].strip()
  1342. # tag_use += ','
  1343. # if case['style2']!='':
  1344. # tag_use += case['style2'].strip()
  1345. # tag_use += ','
  1346. # if case['type']!='':
  1347. # tag_use += case['type'].strip()
  1348. # tag_use += ','
  1349. # if case['condition']!='':
  1350. # tag_use += case['condition'].strip()
  1351. # tmpobj = {
  1352. # "url": "https://hhh.com.tw/cases/detail/d/"+str(case["hcase_id"]),
  1353. # "imgURL": case["cover"].replace('/_hcase/', '/_hcase_orig/').replace('/_hcase_img/', '/_hcase_img_orig/'),
  1354. # "title": case["caption"],
  1355. # "tag": [{"name": tag, "link": "https://hhh.com.tw/search/lists/case/{}-keyword/".format(tag)} for tag in tag_use.split(',')],
  1356. # # "tag": [{"name": tag, "link": "https://hhh.com.tw/search/lists/case/{}-keyword/".format(tag)} for tag in case["tag"].split(',')],
  1357. # "views": case["viewed"],
  1358. # "dateSort": str(case["sdate"])
  1359. # }
  1360. # x["Content"][0]["Carddata"].append(tmpobj)
  1361. # # 設計師影音
  1362. # # https://i.ytimg.com/vi/y6VmaLC7O9Y/hqdefault.jpg
  1363. # x["Content"][1]["Carddata"] = []
  1364. # videos = db.query("""SELECT tag_vpattern,iframe,title,hvideo_id,viewed,display_datetime FROM _hvideo v
  1365. # WHERE v.hdesigner_id = '""" + id + """' AND display_datetime < NOW() and iframe<>''
  1366. # ORDER BY """ + ("hvideo_id" if sort == 'new' else 'viewed') + """ DESC
  1367. # LIMIT """ + str((int(page) - 1)*12) + """,12
  1368. # """)
  1369. # for video in videos:
  1370. # print(str(video['iframe']))
  1371. # tmpobj = {
  1372. # "url": "https://hhh.com.tw/video-post.php?id="+str(video['hvideo_id']),
  1373. # "imgURL": "https://i.ytimg.com/vi/" + extract.video_id(html.unescape(str(video['iframe'])))+"/hqdefault.jpg",
  1374. # "title": video["title"],
  1375. # "tag": [{"name": tag, "link": "https://hhh.com.tw/search/lists/video/{}-keyword/".format(tag)} for tag in video["tag_vpattern"].split(',')],
  1376. # "views": video["viewed"],
  1377. # "dateSort": str(video["display_datetime"])
  1378. # }
  1379. # x["Content"][1]["Carddata"].append(tmpobj)
  1380. # # 設計師專欄
  1381. # x["Content"][2]["Carddata"] = []
  1382. # columns = db.query("""SELECT Ctag,clogo,ctitle,hcolumn_id,viewed,sdate FROM _hcolumn c
  1383. # WHERE onoff=1 AND (hdesigner_ids LIKE '""" + id + """,%' OR hdesigner_ids LIKE '%,""" + id + """,%' OR hdesigner_ids LIKE '%,""" + id + """' OR hdesigner_ids = '""" + id + """')
  1384. # ORDER BY """ + ("sdate" if sort == 'new' else 'viewed') + """ DESC
  1385. # LIMIT """ + str((int(page) - 1)*12) + """,12
  1386. # """)
  1387. # for column in columns:
  1388. # tmpobj = {
  1389. # "url": "https://hhh.com.tw/columns/detail/"+str(column['hcolumn_id']),
  1390. # "imgURL": column['clogo'],
  1391. # "title": column["ctitle"],
  1392. # "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(',')],
  1393. # "views": column["viewed"],
  1394. # "dateSort": str(column["sdate"])
  1395. # }
  1396. # x["Content"][2]["Carddata"].append(tmpobj)
  1397. # # VR360
  1398. # x["Content"][3]["Carddata"] = []
  1399. # cases = db.query("""SELECT tag,cover,caption,hcase_id,viewed,sdate FROM _hcase c
  1400. # WHERE c.hdesigner_id = '""" + id + """' and istaging != '' AND c.onoff='1'
  1401. # ORDER BY """ + ("sdate" if sort == 'new' else 'viewed') + """ DESC
  1402. # LIMIT """ + str((int(page) - 1)*12) + """,12
  1403. # """)
  1404. # for case in cases:
  1405. # tmpobj = {
  1406. # "url": "https://hhh.com.tw/cases/detail/d/"+str(case["hcase_id"]),
  1407. # "imgURL": case["cover"],
  1408. # "title": case["caption"],
  1409. # "tag": [{"name": tag, "link": "https://hhh.com.tw/search/lists/column/{}-keyword/".format(tag)} for tag in case["tag"].split(',')],
  1410. # "views": case["viewed"],
  1411. # "dateSort": str(case["sdate"])
  1412. # }
  1413. # x["Content"][3]["Carddata"].append(tmpobj)
  1414. # # 設計公司簡介
  1415. # #x["Content"][4]["Carddata"] = []
  1416. # #cases = db.query("")
  1417. # """ for case in cases:
  1418. # tmpobj = {
  1419. # "imgURL":case["cover"],
  1420. # "title":case["caption"],
  1421. # "tag":[{"name": tag, "link": ""} for tag in case["tag"].split(',')],
  1422. # "views":case["viewed"],
  1423. # "dateSort":str(case["sdate"])
  1424. # }
  1425. # x["Content"][4]["Carddata"].append(tmpobj) """
  1426. # # print(x)
  1427. # # print(jData)
  1428. # """ if not os.path.exists(hhhMBPath):
  1429. # os.mkdir(hhhMBPath)
  1430. # with open(hhhMBPath+'/json/designers-' + id + '.json', 'w', encoding='utf-8') as f:
  1431. # json.dump(jData, f, ensure_ascii=False, indent=4) """