gen_json_alone.py 40 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813
  1. import itertools
  2. import os
  3. from typing import Optional
  4. from dataset.util import ResultIter
  5. from datetime import tzinfo
  6. import datetime
  7. # import mysql.connector
  8. # from mysql.connector import Error
  9. import dataset
  10. import json
  11. from pytube import extract
  12. hhhMBPath = '../hhh-home-mb'
  13. hhhPCPath = '../hhh-home-pc'
  14. connstr = 'mysql://hhh7796hhh:lYmWsu^ujcA1@hhh-v57.cmab1ctkglka.ap-northeast-2.rds.amazonaws.com:3306/xoops?charset=utf8mb4'
  15. # charset='utf8',
  16. # collation='utf8_unicode_ci'
  17. # @app.get("/genjson")
  18. def genjson(filename: str = "realtime.json"):
  19. with dataset.connect(connstr) as db:
  20. jData = json.load(open(hhhMBPath+'/json/data.json', encoding='utf8'))
  21. records = db.query("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 '首八大%' ")
  22. for x in jData:
  23. # 頂部輪播區-新刊頭
  24. if x['id'] == 0:
  25. records = db.query("""SELECT adlogo lo,adlogo_mobile mlo, adhref lk, adlogo_mobile_webp lomwebp, adlogo_webp dwebp FROM _had
  26. WHERE adtype LIKE '新刊頭%'
  27. AND onoff='1'
  28. 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))
  29. ORDER BY cast(SUBSTR(adtype,4) AS DECIMAL)""")
  30. x["data"] = []
  31. for c in records:
  32. a = {'imgUrl': c['mlo'], 'link': str(
  33. c['lk']), 'DimgUrl': c['lo'], 'webp': str(c['lomwebp']), 'Dwebp': str(c['dwebp'])}
  34. x["data"].append(a)
  35. # print(x["data"])
  36. # 主要輪播區-首八大
  37. if x['id'] == 1:
  38. records = db.query("""SELECT adlogo lo,adlogo_mobile mlo, adhref lk, adlogo_mobile_webp lomwebp, adlogo_webp dwebp FROM _had
  39. WHERE adtype LIKE '首八大%'
  40. AND onoff='1'
  41. 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))
  42. ORDER BY cast(SUBSTR(adtype,4) AS DECIMAL)""")
  43. x["data"] = []
  44. for c in records:
  45. a = {'imgUrl': c['mlo'], 'link': str(
  46. c['lk']), 'DimgUrl': c['lo'], 'webp': str(c['lomwebp']), 'Dwebp': str(c['dwebp'])}
  47. x["data"].append(a)
  48. # print(x["data"])
  49. # tab區塊-最夯設計, 影音實錄, 專欄文章
  50. if x['id'] == 2:
  51. x["data"] = []
  52. records = db.query("""SELECT caption TT ,cover IMG, CONCAT('https://hhh.com.tw/cases/detail/',hcase_id,'/') LK, short_desc txt
  53. from _hcase
  54. left join _hdesigner ON _hcase.hdesigner_id=_hdesigner.hdesigner_id
  55. WHERE
  56. _hcase.onoff='1' AND _hdesigner.onoff='1'
  57. AND(NOW() > sdate)
  58. ORDER BY hcase_id DESC
  59. LIMIT 3""")
  60. a = {'tab': '最夯設計', 'data': []}
  61. for c in records:
  62. ad = {'imgUrl': c['IMG'], 'link': c['LK'],
  63. 'title': c['TT'], 'description': c['txt']}
  64. a['data'].append(ad)
  65. x["data"].append(a)
  66. records = db.query("""SELECT title TT,iframe IMG , CONCAT('https://hhh.com.tw/video-post.php?id=',hvideo_id) LK , name
  67. from _hvideo
  68. where display_datetime < now()
  69. ORDER BY hvideo_id DESC
  70. LIMIT 4""")
  71. a = {'tab': '影音實錄', 'data': []}
  72. cnt = 0
  73. for c in records:
  74. if cnt == 0:
  75. cnt += 1
  76. continue
  77. tid = extract.video_id(c['IMG'])
  78. timg = "https://img.youtube.com/vi/" + tid+"/hqdefault.jpg"
  79. ad = {'imgUrl': timg, 'link': c['LK'],
  80. 'title': c['name'], 'description': c['TT']}
  81. a['data'].append(ad)
  82. x["data"].append(a)
  83. records = db.query("""SELECT ctitle TT,clogo IMG, CONCAT('https://hhh.com.tw/columns/detail/',hcolumn_id,'/') LK, cdesc
  84. from _hcolumn
  85. WHERE onoff='1'
  86. AND NOW() > sdate
  87. ORDER BY hcolumn_id DESC
  88. LIMIT 3""")
  89. a = {'tab': '專欄文章', 'data': []}
  90. for c in records:
  91. ad = {'imgUrl': c['IMG'], 'link': c['LK'],
  92. 'title': c['TT'], 'description': c['cdesc']}
  93. a['data'].append(ad)
  94. x["data"].append(a)
  95. # print(x["data"])
  96. # 主題企劃區
  97. if x['id'] == 3:
  98. records = db.query("""SELECT logo lo, CONCAT('https://hhh.com.tw/topic/detail/',htopic_id,'/') lk, `desc`, title FROM _htopic
  99. WHERE onoff = '1'
  100. ORDER BY htopic_id DESC limit 3""")
  101. x["data"] = []
  102. for c in records:
  103. a = {'imgUrl': c['lo'], 'link': str(
  104. c['lk']), 'video': 'false', 'description': c['desc'], 'title': c['title']}
  105. x["data"].append(a)
  106. # print(x["data"])
  107. # 編輯精選
  108. if x['id'] == 4:
  109. records = db.query("""SELECT hcolumn_id, ctitle, clogo,cdesc
  110. FROM homepage_set
  111. LEFT JOIN _hcolumn ON mapping_id = hcolumn_id
  112. WHERE outer_set=8
  113. AND homepage_set.onoff='Y'
  114. 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))
  115. ORDER BY inner_sort""")
  116. x["data"] = []
  117. for c in records:
  118. a = {'imgUrl': c['clogo'], 'link': "https://hhh.com.tw/columns/detail/" + str(
  119. c['hcolumn_id']) + "/", 'title': c['ctitle'], 'video': 'false', 'description': c['cdesc']}
  120. x["data"].append(a)
  121. # print(x["data"])
  122. # 首列表廣告
  123. if x['id'] == 5:
  124. records = db.query("""SELECT adlogo lo,adlogo_mobile mlo, adhref lk, adlogo_mobile_webp lomwebp, adlogo_webp dwebp FROM _had
  125. WHERE adtype LIKE '首列表廣告%'
  126. AND onoff='1'
  127. 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))
  128. ORDER BY adtype""")
  129. x["data"] = []
  130. for c in records:
  131. a = {'imgUrl': c['mlo'], 'link': str(
  132. c['lk']), 'DimgUrl': c['lo'], 'webp': str(c['lomwebp']), 'Dwebp': str(c['dwebp'])}
  133. x["data"].append(a)
  134. # print(x["data"])
  135. # 來選好物區
  136. if x['id'] == 6:
  137. records = db.query(
  138. "SELECT max_row from outer_site_set WHERE title='來選好貨'")
  139. maxrow = 1
  140. for c in records:
  141. maxrow = c['max_row']
  142. records = db.query("""(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
  143. , (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
  144. -- SELECT *
  145. FROM homepage_set
  146. left join _hcase ON _hcase.hcase_id=homepage_set.mapping_id AND theme_type='case'-- AND _hcase.onoff = '1'
  147. LEFT JOIN _hproduct ON mapping_id = _hproduct.id AND theme_type='product'-- AND _hproduct.onoff = '1'
  148. LEFT JOIN _hcolumn ON mapping_id = _hcolumn.hcolumn_id AND theme_type='column'-- AND _hcolumn.onoff = '1'
  149. LEFT JOIN _hvideo ON mapping_id = _hvideo.hvideo_id AND theme_type='video'
  150. WHERE homepage_set.onoff='Y'
  151. AND outer_set = (SELECT oss_id from outer_site_set WHERE title='來選好貨')
  152. 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))
  153. ORDER BY outer_set, inner_sort)
  154. UNION
  155. (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) + """)
  156. LIMIT """ + str(maxrow))
  157. x["data"] = []
  158. for c in records:
  159. #print(c)
  160. if c['iframe'] is None:
  161. if isinstance(c['J'], bytearray) or isinstance(c['J'], bytes):
  162. c['J'] = c['J'].decode('utf8')
  163. if isinstance(c['caption'], bytearray) or isinstance(c['caption'], bytes):
  164. c['caption'] = c['caption'].decode('utf8')
  165. if isinstance(c['short_desc'], bytearray) or isinstance(c['short_desc'], bytes):
  166. c['short_desc'] = c['short_desc'].decode('utf8')
  167. a = {'imgUrl': c['J'], 'link': c['url'], 'title': c['caption'],
  168. 'description': c['short_desc'], 'video': 'false'}
  169. else:
  170. tid = extract.video_id(str(c['iframe']))
  171. timg = "https://img.youtube.com/vi/" + tid+"/hqdefault.jpg"
  172. ccaption = ""
  173. cdescription = ""
  174. if isinstance(c['caption'], bytearray):
  175. ccaption = str(c['caption'].decode('utf8'))
  176. else:
  177. ccaption = str(c['caption'])
  178. if c['short_desc'] is not None:
  179. if isinstance(c['short_desc'], bytes):
  180. cdescription = str(c['short_desc'].decode('utf8'))
  181. else:
  182. cdescription = str(c['short_desc'])
  183. a = {'imgUrl': timg, 'link': c['url'], 'title': ccaption,
  184. 'description': cdescription, 'video': tid}
  185. x["data"].append(a)
  186. # print(x["data"])
  187. # 本週推薦
  188. if x['id'] == 7:
  189. records = db.query(
  190. "SELECT max_row from outer_site_set WHERE title='本週推薦'")
  191. maxrow = 1
  192. for c in records:
  193. maxrow = c['max_row']
  194. records = db.query("""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
  195. , (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
  196. -- SELECT *
  197. FROM homepage_set
  198. left join _hcase ON _hcase.hcase_id=homepage_set.mapping_id AND theme_type='case'-- AND _hcase.onoff = '1'
  199. LEFT JOIN _hproduct ON mapping_id = _hproduct.id AND theme_type='product'-- AND _hproduct.onoff = '1'
  200. LEFT JOIN _hcolumn ON mapping_id = _hcolumn.hcolumn_id AND theme_type='column'-- AND _hcolumn.onoff = '1'
  201. LEFT JOIN _hvideo ON mapping_id = _hvideo.hvideo_id AND theme_type='video'
  202. WHERE homepage_set.onoff='Y'
  203. AND outer_set = (SELECT oss_id from outer_site_set WHERE title='本週推薦')
  204. 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))
  205. ORDER BY outer_set, inner_sort
  206. LIMIT """ + str(maxrow))
  207. x["data"] = []
  208. for c in records:
  209. if c['iframe'] is None:
  210. if isinstance(c['J'], bytearray) or isinstance(c['J'], bytes):
  211. c['J'] = c['J'].decode('utf8')
  212. if isinstance(c['caption'], bytearray) or isinstance(c['caption'], bytes):
  213. c['caption'] = c['caption'].decode('utf8')
  214. if isinstance(c['short_desc'], bytearray) or isinstance(c['short_desc'], bytes):
  215. c['short_desc'] = c['short_desc'].decode('utf8')
  216. a = {'imgUrl': c['J'], 'link': c['url'], 'title': c['caption'],
  217. 'description': c['short_desc'], 'video': 'false'}
  218. else:
  219. tid = extract.video_id(str(c['iframe']))
  220. timg = "https://img.youtube.com/vi/" + tid+"/hqdefault.jpg"
  221. ccaption = ""
  222. cdescription = ""
  223. if isinstance(c['caption'], bytearray):
  224. ccaption = str(c['caption'].decode('utf8'))
  225. else:
  226. ccaption = str(c['caption'])
  227. if c['short_desc'] is not None:
  228. if isinstance(c['short_desc'], bytes):
  229. cdescription = str(c['short_desc'].decode('utf8'))
  230. else:
  231. cdescription = str(c['short_desc'])
  232. a = {'imgUrl': timg, 'link': c['url'], 'title': ccaption,
  233. 'description': cdescription, 'video': tid}
  234. x["data"].append(a)
  235. # print(x["data"])
  236. # 粉絲推薦
  237. if x['id'] == 8:
  238. records = db.query(
  239. "SELECT max_row from outer_site_set WHERE title='粉絲推薦'")
  240. maxrow = 1
  241. for c in records:
  242. maxrow = c['max_row']
  243. records = db.query("""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
  244. , (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
  245. -- SELECT *
  246. FROM homepage_set
  247. left join _hcase ON _hcase.hcase_id=homepage_set.mapping_id AND theme_type='case'-- AND _hcase.onoff = '1'
  248. LEFT JOIN _hproduct ON mapping_id = _hproduct.id AND theme_type='product'-- AND _hproduct.onoff = '1'
  249. LEFT JOIN _hcolumn ON mapping_id = _hcolumn.hcolumn_id AND theme_type='column'-- AND _hcolumn.onoff = '1'
  250. LEFT JOIN _hvideo ON mapping_id = _hvideo.hvideo_id AND theme_type='video'
  251. WHERE homepage_set.onoff='Y'
  252. AND outer_set = (SELECT oss_id from outer_site_set WHERE title='粉絲推薦')
  253. 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))
  254. ORDER BY outer_set, inner_sort
  255. LIMIT """ + str(maxrow))
  256. x["data"] = []
  257. for c in records:
  258. if c['iframe'] is None:
  259. if isinstance(c['J'], bytearray) or isinstance(c['J'], bytes):
  260. c['J'] = c['J'].decode('utf8')
  261. if isinstance(c['caption'], bytearray) or isinstance(c['caption'], bytes):
  262. c['caption'] = c['caption'].decode('utf8')
  263. if isinstance(c['short_desc'], bytearray) or isinstance(c['short_desc'], bytes):
  264. c['short_desc'] = c['short_desc'].decode('utf8')
  265. a = {'imgUrl': c['J'], 'link': c['url'], 'title': c['caption'],
  266. 'description': c['short_desc'], 'video': 'false'}
  267. else:
  268. tid = extract.video_id(str(c['iframe']))
  269. timg = "https://img.youtube.com/vi/" + tid+"/hqdefault.jpg"
  270. ccaption = ""
  271. cdescription = ""
  272. if isinstance(c['caption'], bytearray):
  273. ccaption = str(c['caption'].decode('utf8'))
  274. else:
  275. ccaption = str(c['caption'])
  276. if c['short_desc'] is not None:
  277. if isinstance(c['short_desc'], bytes):
  278. cdescription = str(c['short_desc'].decode('utf8'))
  279. else:
  280. cdescription = str(c['short_desc'])
  281. a = {'imgUrl': timg, 'link': c['url'], 'title': ccaption,
  282. 'description': cdescription, 'video': tid}
  283. x["data"].append(a)
  284. # print(x["data"])
  285. if x['id'] == 9:
  286. records = db.query(
  287. "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")
  288. for c in records:
  289. x['title'] = ""
  290. if isinstance(c['T'], bytearray):
  291. x['title'] = str(c['T'].decode('utf8'))
  292. else:
  293. x['title'] = str(c['T'])
  294. x['yt'] = extract.video_id(str(c['Y']))
  295. # print(id)
  296. if x['id'] == 10:
  297. records = db.query(
  298. "SELECT all_search_tag ast FROM site_setup")
  299. x["data"] = []
  300. for c in records:
  301. x["data"] = c['ast'].split(',')
  302. # print(id)
  303. # print(jData)
  304. if not os.path.exists(hhhMBPath):
  305. os.mkdir(hhhMBPath)
  306. with open(hhhMBPath+'/json/' + filename, 'w', encoding='utf-8') as f:
  307. json.dump(jData, f, ensure_ascii=False, indent=4)
  308. if not os.path.exists(hhhPCPath):
  309. os.mkdir(hhhPCPath)
  310. with open(hhhPCPath+'/json/' + filename, 'w', encoding='utf-8') as f:
  311. json.dump(jData, f, ensure_ascii=False, indent=4)
  312. return jData
  313. # @app.get("/gencase")
  314. def gencase(id: str = "12257", sort: str = "new", page: str = "1"):
  315. with dataset.connect(connstr) as db:
  316. jData = json.load(open(hhhMBPath+'/json/cases.json', encoding='utf8'))
  317. records = db.query("""SELECT *, c.style cstyle, c.style2 cstyle2 FROM _hcase c
  318. LEFT JOIN _hdesigner d ON c.hdesigner_id = d.hdesigner_id
  319. WHERE c.hcase_id = '""" + id + """' AND c.onoff='1' AND d.onoff='1' and c.sdate < now() """)
  320. # print(jData)
  321. for x in jData:
  322. tmpCaseDetail = []
  323. icount = 0
  324. for c in records:
  325. icount += 1
  326. #tmpCaseDetail.append({"CaseDetailImg": c["cimg"]})
  327. #x["CaseDetail"] = tmpCaseDetail
  328. if c != None:
  329. x["designerid"] = str(c["hdesigner_id"])
  330. x["CaseId"] = str(c["hcase_id"])
  331. x["Casetitle"] = c["caption"]
  332. x["CaseTeamName"] = c["name"]
  333. x["CaseCompany"] = c["title"]
  334. x["CaseCompanyAddress"] = c["address"]
  335. x["CaseCompanyTel"] = c["phone"]
  336. x["CaseCompanyEmail"] = c["mail"]
  337. x["CaseCompanyWeb"] = c["website"]
  338. x["CaseDate"] = str(c["sdate"])
  339. x["CaseViews"] = c["viewed"]
  340. x["CaseCoverImg"] = c["cover"]
  341. x["CaseImgAmount"] = icount
  342. x["CaseStyle"] = c["cstyle"]
  343. x["CaseHouse"] = c["layout"]
  344. x["CaseSize"] = c["area"]
  345. x["CaseProject"] = ""
  346. x["CaseDataMember"] = c["member"]
  347. x["CaseDataSize"] = c["area"]
  348. x["CaseDataStyle"] = c["cstyle"] + c["cstyle2"]
  349. x["CaseDataType"] = c["type"]
  350. x["CaseDataSituation"] = c["condition"]
  351. x["CaseDataImgProvide"] = c["provider"]
  352. x["CaseDataSpace"] = c["layout"]
  353. x["CaseDataMaterial"] = c["materials"]
  354. x["ContactFreeTel"] = c["service_phone"]
  355. x["ContactDesignerImg"] = c["img_path"]
  356. x["CasePageLink"] = ""
  357. x["CasePageprev"] = ""
  358. #x["CaseTag"]= []
  359. # 相同設計師的個案
  360. sql = """SELECT * FROM _hcase c
  361. WHERE hdesigner_id = '""" + x["designerid"] + """' and hcase_id <> '""" + x["CaseId"] + """' and sdate < now() AND c.onoff='1'
  362. ORDER BY """ + ("sdate" if sort == 'new' else 'viewed') + """ DESC
  363. LIMIT """ + str((int(page) - 1)*12) + """,12
  364. """
  365. cases = db.query(sql)
  366. tmpOtherCases = []
  367. for other in cases:
  368. tmpOtherCase = {}
  369. tmpOtherCase["designerid"] = str(other["hdesigner_id"])
  370. tmpOtherCase["casesid"] = str(other["hcase_id"])
  371. tmpOtherCase["Views"] = other["viewed"]
  372. tmpOtherCase["ProfileImg"] = other["cover"]
  373. tmpTags = []
  374. for tag in other["tag"].split(','):
  375. tmpTags.append({"Tag": tag, "TagLink": ""})
  376. tmpOtherCase["ProfileTag"] = tmpTags
  377. tmpOtherCases.append(tmpOtherCase)
  378. x["DesignerProfile"] = tmpOtherCases
  379. # 相同風格的個案
  380. sql = """SELECT * FROM _hcase c
  381. WHERE style = '""" + x["CaseStyle"] + """' and hcase_id <> '""" + x["CaseId"] + """' and sdate < now() AND c.onoff='1'
  382. ORDER BY """ + ("sdate" if sort == 'new' else 'viewed') + """ DESC
  383. LIMIT """ + str((int(page) - 1)*12) + """,12
  384. """
  385. cases = db.query(sql)
  386. tmpOtherCases = []
  387. for other in cases:
  388. tmpOtherCase = {}
  389. tmpOtherCase["designerid"] = str(other["hdesigner_id"])
  390. tmpOtherCase["casesid"] = str(other["hcase_id"])
  391. tmpOtherCase["Views"] = other["viewed"]
  392. tmpOtherCase["ProfileImg"] = other["cover"]
  393. tmpTags = []
  394. for tag in other["tag"].split(','):
  395. tmpTags.append({"Tag": tag, "TagLink": ""})
  396. tmpOtherCase["ProfileTag"] = tmpTags
  397. tmpOtherCases.append(tmpOtherCase)
  398. x["StyleProfile"] = tmpOtherCases
  399. # 相同風格的RANDOM 10筆
  400. # cases = db.query("""SELECT * FROM _hcase c
  401. # WHERE style = '""" + x["CaseStyle"] + """' and hcase_id <> '""" + x["CaseId"] + """' and sdate < now() AND c.onoff='1'
  402. # ORDER BY RAND()
  403. # LIMIT 10
  404. # """)
  405. """ tmpOtherCases = []
  406. for other in cases:
  407. tmpOtherCase = {}
  408. tmpOtherCase["designerid"] = str(other["hdesigner_id"])
  409. tmpOtherCase["casesid"] = str(other["hcase_id"])
  410. tmpOtherCase["PortfoliolImg"] = other["cover"]
  411. tmpOtherCase["PortfoliolLink"] = ""
  412. tmpOtherCase["PortfoliolImgAlt"] = other["caption"]
  413. tmpOtherCases.append(tmpOtherCase)
  414. x["OtherStylePortfolio"]= tmpOtherCases """
  415. # print(x)
  416. # print(jData)
  417. if not os.path.exists(hhhMBPath):
  418. os.mkdir(hhhMBPath)
  419. with open(hhhMBPath+'/json/cases-' + id + '.json', 'w', encoding='utf-8') as f:
  420. json.dump(jData, f, ensure_ascii=False, indent=4)
  421. return jData
  422. def gendesigner(id: str = "14151", sort: str = "new", page: str = "1"):
  423. with dataset.connect(connstr) as db:
  424. jData = json.load(open(hhhMBPath+'/json/designers.json', encoding='utf8'))
  425. records = db.query("""SELECT * FROM _hdesigner d
  426. WHERE d.hdesigner_id = '""" + id + """' AND d.onoff='1' """)
  427. # print(jData)
  428. for x in jData:
  429. tmpCaseDetail = []
  430. icount = 0
  431. for c in records:
  432. icount += 1
  433. # tmpCaseDetail.append({"CaseDetailImg":c["cimg"]})
  434. if page == "1":
  435. x["id"] = c["hdesigner_id"]
  436. x["BannerImg"] = c["background"]
  437. x["CompanyName"] = c["title"]
  438. x["DesignerName"] = c["name"]
  439. x["Designerimg"] = c["img_path"]
  440. x["Description"] = c["seo"]
  441. x["Approve"] = c["position"]
  442. x["FB_link"] = c["fbpageurl"]
  443. x["Basics"] = [
  444. {"title": "免費專線:",
  445. "link": c["service_phone"], "data": c["service_phone"]},
  446. {"title": "諮詢專線:", "link": c["phone"], "data": c["phone"]},
  447. {"title": "諮詢專線:", "link": c["phone"], "data": c["phone"]},
  448. {"title": "公司傳真:", "link": c["fax"], "data": c["fax"]},
  449. {"title": "公司地址:", "link": c["address"], "data": c["address"]},
  450. {"title": "電子信箱:", "link": c["mail"], "data": c["mail"]},
  451. {"title": "公司網址:", "link": c["website"], "data": c["website"]}
  452. ]
  453. x["FreeCall"] = c["service_phone"]
  454. x["ConsoleCall_1"] = c["phone"]
  455. x["ConsoleCall_2"] = c["phone"]
  456. x["Fax"] = c["fax"]
  457. x["Address"] = c["address"]
  458. x["Email"] = c["mail"]
  459. x["Web"] = c["website"]
  460. x["Branches"] = []
  461. branches = db.query("""SELECT * FROM designer_branch br
  462. WHERE br.designer_id = '""" + id + """' """)
  463. for branch in branches:
  464. tmpobj = {
  465. "title": branch["title"],
  466. "address": branch["address"],
  467. "tel": branch["tel"],
  468. "fax": branch["fax"]
  469. }
  470. x["Branches"].append(tmpobj)
  471. x["Budget"] = c["budget"]
  472. x["Square"] = c["area"]
  473. x["SpecialCase"] = c["special"]
  474. x["Charge"] = c["charge"]
  475. x["Pay"] = c["payment"]
  476. x["WorkLoc"] = c["region"]
  477. x["WorkType"] = c["type"]
  478. x["WorkStyle"] = c["style"]
  479. x["WorkBudget"] = c["budget"]
  480. x["Terms"] = [
  481. {"title": "接案預算:", "data": c["budget"]},
  482. {"title": "接案坪數:", "data": c["area"]},
  483. {"title": "特殊接案:", "data": c["special"]},
  484. {"title": "收費方式:", "data": c["charge"]},
  485. {"title": "付費方式:", "data": c["payment"]},
  486. {"title": "接案區域:", "data": c["region"]},
  487. {"title": "接案類型:", "data": c["type"]},
  488. {"title": "接案風格:", "data": c["style"]}
  489. ]
  490. x["scMedia"] = [
  491. {"name": "Facebook", "img": "https://hhh.com.tw/assets/images/rv_web/fb.svg",
  492. "link": c["fbpageurl"]},
  493. {"name": "Line", "img": "https://hhh.com.tw/assets/images/rv_web/line.svg",
  494. "link": c["line_link"]},
  495. {"name": "Wechat", "img": "https://hhh.com.tw/assets/images/rv_web/wechat.svg",
  496. "link": c["fbpageurl"]},
  497. {"name": "email", "img": "https://hhh.com.tw/assets/images/rv_web/share.svg",
  498. "link": c["mail"]},
  499. {"name": "Like", "img": "https://hhh.com.tw/assets/images/rv_web/like-o.svg", "link": ""}
  500. ]
  501. x["Content"] = [
  502. {
  503. "Title": "設計師作品",
  504. "mb_title": "作品",
  505. "Tabtag": "intro",
  506. "Display_mb": "true",
  507. "isActive": "true",
  508. "Carddata": []
  509. },
  510. {
  511. "Title": "設計師影音",
  512. "mb_title": "影音",
  513. "Tabtag": "video",
  514. "Display_mb": "true",
  515. "isActive": "true",
  516. "Carddata": []
  517. },
  518. {
  519. "Title": "設計師專欄",
  520. "mb_title": "專欄",
  521. "Tabtag": "columns",
  522. "Display_mb": "true",
  523. "isActive": "true",
  524. "Carddata": []
  525. },
  526. {
  527. "Title": "VR360",
  528. "mb_title": "",
  529. "Tabtag": "vr360",
  530. "Display_mb": "false",
  531. "isActive": "true",
  532. "Carddata": []
  533. },
  534. {
  535. "Title": "設計師公司簡介",
  536. "mb_title": "公司簡介",
  537. "Tabtag": "company",
  538. "Display_mb": "true",
  539. "isActive": "true",
  540. "Carddata": [],
  541. "info": [
  542. {"title": "設計理念", "data": c["idea"]},
  543. {"title": "公司統編", "data": c["taxid"]},
  544. {"title": "相關經歷", "data": c["career"]},
  545. {"title": "專業證照", "data": c["license"]},
  546. {"title": "獲獎紀錄", "data": c["awards"]}
  547. ]
  548. }
  549. ]
  550. # 設計師作品
  551. x["Content"][0]["Carddata"] = []
  552. cases = db.query("""SELECT tag,cover,caption,hcase_id,viewed,sdate FROM _hcase c
  553. WHERE c.hdesigner_id = '""" + id + """' AND c.onoff='1'
  554. ORDER BY """ + ("sdate" if sort == 'new' else 'viewed') + """ DESC
  555. LIMIT """ + str((int(page) - 1)*12) + """,12
  556. """)
  557. for case in cases:
  558. tmpobj = {
  559. "url": "https://hhh.com.tw/cases/detail/d/"+str(case["hcase_id"]),
  560. "imgURL": case["cover"],
  561. "title": case["caption"],
  562. "tag": [{"name": tag, "link": ""} for tag in case["tag"].split(',')],
  563. "views": case["viewed"],
  564. "dateSort": str(case["sdate"])
  565. }
  566. x["Content"][0]["Carddata"].append(tmpobj)
  567. # 設計師影音
  568. # https://i.ytimg.com/vi/y6VmaLC7O9Y/hqdefault.jpg
  569. x["Content"][1]["Carddata"] = []
  570. videos = db.query("""SELECT tag_vpattern,iframe,title,hvideo_id,viewed,display_datetime FROM _hvideo v
  571. WHERE v.hdesigner_id = '""" + id + """' AND display_datetime < NOW()
  572. ORDER BY """ + ("display_datetime" if sort == 'new' else 'viewed') + """ DESC
  573. LIMIT """ + str((int(page) - 1)*12) + """,12
  574. """)
  575. for video in videos:
  576. tmpobj = {
  577. "url": "https://hhh.com.tw/video-post.php?id="+str(video['hvideo_id']),
  578. "imgURL": "https://i.ytimg.com/vi/" + extract.video_id(str(video['iframe']))+"/hqdefault.jpg",
  579. "title": video["title"],
  580. "tag": [{"name": tag, "link": ""} for tag in video["tag_vpattern"].split(',')],
  581. "views": video["viewed"],
  582. "dateSort": str(video["display_datetime"])
  583. }
  584. x["Content"][1]["Carddata"].append(tmpobj)
  585. # 設計師專欄
  586. x["Content"][2]["Carddata"] = []
  587. columns = db.query("""SELECT tag,clogo,ctitle,hcolumn_id,viewed,sdate FROM _hcolumn c
  588. WHERE onoff=1 AND (hdesigner_ids LIKE '""" + id + """,%' OR hdesigner_ids LIKE '%,""" + id + """,%' OR hdesigner_ids LIKE '%,""" + id + """' OR hdesigner_ids = '""" + id + """')
  589. ORDER BY """ + ("sdate" if sort == 'new' else 'viewed') + """ DESC
  590. LIMIT """ + str((int(page) - 1)*12) + """,12
  591. """)
  592. for column in columns:
  593. tmpobj = {
  594. "url": "https://hhh.com.tw/video-post.php?id="+str(video['hvideo_id']),
  595. "imgURL": column['clogo'],
  596. "title": column["ctitle"],
  597. "tag": [] if not column["tag"] else [{"name": tag, "link": ""} for tag in column["tag"].split(',')],
  598. "views": column["viewed"],
  599. "dateSort": str(column["sdate"])
  600. }
  601. x["Content"][2]["Carddata"].append(tmpobj)
  602. # VR360
  603. x["Content"][3]["Carddata"] = []
  604. cases = db.query("""SELECT tag,cover,caption,hcase_id,viewed,sdate FROM _hcase c
  605. WHERE c.hdesigner_id = '""" + id + """' and istaging != '' AND c.onoff='1'
  606. ORDER BY """ + ("sdate" if sort == 'new' else 'viewed') + """ DESC
  607. LIMIT """ + str((int(page) - 1)*12) + """,12
  608. """)
  609. for case in cases:
  610. tmpobj = {
  611. "url": "https://hhh.com.tw/cases/detail/d/"+str(case["hcase_id"]),
  612. "imgURL": case["cover"],
  613. "title": case["caption"],
  614. "tag": [{"name": tag, "link": ""} for tag in case["tag"].split(',')],
  615. "views": case["viewed"],
  616. "dateSort": str(case["sdate"])
  617. }
  618. x["Content"][3]["Carddata"].append(tmpobj)
  619. # 設計公司簡介
  620. #x["Content"][4]["Carddata"] = []
  621. #cases = db.query("")
  622. """ for case in cases:
  623. tmpobj = {
  624. "imgURL":case["cover"],
  625. "title":case["caption"],
  626. "tag":[{"name": tag, "link": ""} for tag in case["tag"].split(',')],
  627. "views":case["viewed"],
  628. "dateSort":str(case["sdate"])
  629. }
  630. x["Content"][4]["Carddata"].append(tmpobj) """
  631. # print(x)
  632. # print(jData)
  633. if not os.path.exists(hhhMBPath):
  634. os.mkdir(hhhMBPath)
  635. with open(hhhMBPath+'/json/designers-' + id + '.json', 'w', encoding='utf-8') as f:
  636. json.dump(jData, f, ensure_ascii=False, indent=4)
  637. return jData
  638. def gencolumn(id: str = "6392", sort: str = "new", page: str = "1"):
  639. with dataset.connect(connstr) as db:
  640. jData = json.load(open(hhhMBPath+'/json/Columns.json', encoding='utf8'))
  641. records = db.query("""SELECT * FROM _hcolumn c
  642. WHERE c.hcolumn_id = '""" + id + """' AND c.onoff='1' """)
  643. # print(id)
  644. for x in jData:
  645. icount = 0
  646. c = None
  647. for c in records:
  648. icount += 1
  649. if c != None:
  650. x["Columnsid"] = str(c["hcolumn_id"])
  651. x["Columnstitle"] = c["ctitle"]
  652. x["ColumnsCoverImg"] = c["clogo"]
  653. x["ColumnsDate"] = str(c["sdate"])
  654. x["ColumnsViews"] = str(c["viewed"])
  655. # 只有第一頁時有內容,以免資料過大
  656. if page == "1":
  657. x["ColumnsContent"] = c["page_content"]
  658. tmpTags = []
  659. for tag in c["ctag"].split(','):
  660. tmpTags.append({"Tag": tag})
  661. x["ColumnsTag"] = tmpTags
  662. # 相同類別的最新12筆
  663. sql = """SELECT * FROM _hcolumn c
  664. 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'
  665. ORDER BY """ + ("sdate" if sort == 'new' else 'viewed') + """ DESC
  666. LIMIT """ + str((int(page) - 1)*12) + """,12
  667. """
  668. ctypes = db.query(sql)
  669. tmpOtherCols = []
  670. for other in ctypes:
  671. tmpOtherCol = {}
  672. tmpOtherCol["Columnsid"] = str(other["hcolumn_id"])
  673. tmpOtherCol["ColumnsCoverImg"] = other["clogo"]
  674. tmpOtherCol["Views"] = other["viewed"]
  675. tmpOtherCol["Columnstitle"] = other["ctitle"]
  676. tmpTags = []
  677. for tag in other["ctag"].split(','):
  678. tmpTags.append({"Tag": tag})
  679. tmpOtherCol["ColumnsTag"] = tmpTags
  680. tmpOtherCols.append(tmpOtherCol)
  681. x["OtherColumns"] = tmpOtherCols
  682. # print(x)
  683. # print(jData)
  684. if not os.path.exists(hhhMBPath):
  685. os.mkdir(hhhMBPath)
  686. with open(hhhMBPath+'/json/Columns-' + id + '.json', 'w', encoding='utf-8') as f:
  687. json.dump(jData, f, ensure_ascii=False, indent=4)
  688. return jData
  689. # genjson("realtime.json")
  690. #cmd="""curl -X POST "https://api.cloudflare.com/client/v4/zones/8cb58022ad5743cfd9f088d5e3a261eb/purge_cache" -H "X-Auth-Email: web.dept.hhh@gmail.com" -H "X-Auth-Key:63e51d9a1638d66afcbfc3320aabec52304de" -H "Content-Type: application/json" --data '{"files":["https://m.hhh.com.tw/hhh-home-mb/json/realtime.json"]}'"""
  691. # os.system(cmd)
  692. with dataset.connect(connstr) as db:
  693. genjson()
  694. """ gencase("14151")
  695. gendesigner("788")
  696. gencolumn("6392") """
  697. """ gencolumn("6349")
  698. gencolumn("6476")
  699. gencolumn("6392") """
  700. """ gencase("421")
  701. gencase("12257")
  702. gencase("14305") """
  703. """ gendesigner("312") """
  704. cases = db.query("""SELECT DISTINCT hcase_id FROM _hcase c
  705. WHERE c.onoff='1' """)
  706. """ for sc in cases:
  707. gencase(str(sc['hcase_id'])) """
  708. columns = db.query("""SELECT DISTINCT hcolumn_id FROM _hcolumn c
  709. WHERE c.onoff='1' and sdate < now() """)
  710. """ for sc in columns:
  711. gencolumn(str(sc['hcolumn_id'])) """
  712. # """ if __name__ == "__main__":
  713. # uvicorn.run(app, host="0.0.0.0", port=8000) """