settings.py 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586
  1. # -*- coding: utf-8 -*-
  2. # Author : Charley
  3. # Python : 3.10.8
  4. # Date : 2025/3/24 15:05
  5. import inspect
  6. import requests
  7. from loguru import logger
  8. from bs4 import BeautifulSoup
  9. from tenacity import retry, stop_after_attempt, wait_fixed
  10. logger.remove()
  11. logger.add("./logs/{time:YYYYMMDD}.log", encoding='utf-8', rotation="00:00",
  12. format="[{time:YYYY-MM-DD HH:mm:ss.SSS}] {level} {message}",
  13. level="DEBUG", retention="7 day")
  14. HEADERS = {
  15. "User-Agent": "Dart/3.5 (dart:io)",
  16. "Accept-Encoding": "gzip",
  17. "Content-Type": "application/json",
  18. "deviceid": "110bec91-951f-4346-8195-95700fdb8c1d",
  19. "brand": "google",
  20. "channel": "JC",
  21. "os": "android",
  22. "content-type": "application/json; charset=utf-8",
  23. # "authori-zation": "a-209a2707889f473688a742c4bac06eed",
  24. "systemversion": "30",
  25. "theme": "light",
  26. "lang": "zh",
  27. "verse-ua": "ed5866264fee2419a78abd8f0feabd6f",
  28. "version": "1.1.1",
  29. "isphysicaldevice": "true",
  30. "sktime": "1770608542291",
  31. "cid": "08295441",
  32. "sk": "0ac56318c28de85c57fe74995ed6678d" # 每次版本变化 也需要修改
  33. }
  34. # headers = {
  35. # "User-Agent": "Dart/3.5 (dart:io)",
  36. # "Accept-Encoding": "gzip",
  37. # "deviceid": "110bec91-951f-4346-8195-95700fdb8c1d",
  38. # "brand": "google",
  39. # "channel": "JC",
  40. # "os": "android",
  41. # "content-type": "application/json; charset=utf-8",
  42. # "authori-zation": "a-e22bdf9887a846e0ab04fa45fad22396",
  43. # "systemversion": "30",
  44. # "theme": "light",
  45. # "lang": "zh",
  46. # "verse-ua": "ed5866264fee2419a78abd8f0feabd6f",
  47. # "version": "1.1.1",
  48. # "isphysicaldevice": "true",
  49. # "sktime": "1770608542291",
  50. # "cid": "08295441",
  51. # "sk": "0ac56318c28de85c57fe74995ed6678d"
  52. # }
  53. def after_log(retry_state):
  54. """
  55. retry 回调
  56. :param retry_state: RetryCallState 对象
  57. """
  58. # 检查 args 是否存在且不为空
  59. if retry_state.args and len(retry_state.args) > 0:
  60. log = retry_state.args[0] # 获取传入的 logger
  61. else:
  62. log = logger # 使用全局 logger
  63. if retry_state.outcome.failed:
  64. log.warning(
  65. f"Function '{retry_state.fn.__name__}', Attempt {retry_state.attempt_number} Times")
  66. else:
  67. log.info(f"Function '{retry_state.fn.__name__}', Attempt {retry_state.attempt_number} succeeded")
  68. @retry(stop=stop_after_attempt(5), wait=wait_fixed(1), after=after_log)
  69. def get_proxys(log):
  70. """
  71. 获取代理
  72. :return: 代理
  73. """
  74. tunnel = "x371.kdltps.com:15818"
  75. kdl_username = "t13753103189895"
  76. kdl_password = "o0yefv6z"
  77. try:
  78. proxies = {
  79. "http": "http://%(user)s:%(pwd)s@%(proxy)s/" % {"user": kdl_username, "pwd": kdl_password, "proxy": tunnel},
  80. "https": "http://%(user)s:%(pwd)s@%(proxy)s/" % {"user": kdl_username, "pwd": kdl_password, "proxy": tunnel}
  81. }
  82. return proxies
  83. except Exception as e:
  84. log.error(f"Error getting proxy: {e}")
  85. raise e
  86. @retry(stop=stop_after_attempt(5), wait=wait_fixed(1), after=after_log)
  87. def make_request(log, method, url, params=None, data=None, headers=None, proxies=None, timeout=22, token=None):
  88. """
  89. 通用请求函数
  90. :param log: logger对象
  91. :param method: 请求方法 ('GET' 或 'POST')
  92. :param url: 请求的URL
  93. :param params: GET请求的查询参数
  94. :param data: POST请求的数据
  95. :param headers: 请求头
  96. :param proxies: 代理
  97. :param timeout: 请求超时时间
  98. :param token: token
  99. :return: 响应的JSON数据
  100. """
  101. if headers is None:
  102. headers = HEADERS
  103. if 'getHitCardReport' or 'getCardPublicly' or 'productDetailDynamics' or 'productShowList' in url:
  104. if not token:
  105. token = "a-87768ad775bf4513bec14f2c4fd2cd0c"
  106. headers["authori-zation"] = token
  107. if proxies is None:
  108. proxies = get_proxys(log)
  109. try:
  110. with requests.Session() as session:
  111. if method.upper() == 'GET':
  112. if proxies is None:
  113. response = session.get(url, headers=headers, params=params, timeout=timeout)
  114. else:
  115. response = session.get(url, headers=headers, params=params, proxies=proxies, timeout=timeout)
  116. elif method.upper() == 'POST':
  117. if proxies is None:
  118. response = session.post(url, headers=headers, json=data, timeout=timeout)
  119. # print(response.text)
  120. else:
  121. response = session.post(url, headers=headers, json=data, proxies=proxies, timeout=timeout)
  122. else:
  123. log.error(f"Unsupported request method: {method}")
  124. return None
  125. response.raise_for_status()
  126. data = response.json()
  127. # print(response.text)
  128. if data["code"] == 200:
  129. log.info(f"Successfully fetched {method} request to {url}")
  130. return data
  131. else:
  132. log.warning(f"Warning {inspect.currentframe().f_code.co_name}: {data['message']}")
  133. return {}
  134. except requests.exceptions.RequestException as e:
  135. log.error(f"Error making {method} request to {url}: {e}")
  136. raise e
  137. except ValueError as e:
  138. log.error(f"Error parsing JSON for {method} request to {url}: {e}")
  139. raise e
  140. except Exception as e:
  141. log.error(f"Error making {method} request to {url}: {e}")
  142. raise e
  143. def get_play_back(log, product_id, token):
  144. """
  145. 获取 视频回放链接
  146. :param log: logger对象
  147. :param product_id: product_id
  148. :param token: token
  149. """
  150. log.info(f"Starting to fetch playback for product_id {product_id}")
  151. url = "https://api.joycard.xyz/api/front/c/product/productDetailDynamics"
  152. params = {
  153. # "code": "LCS1254174"
  154. "code": product_id
  155. }
  156. try:
  157. response = make_request(log, 'GET', url, params=params, token=token)
  158. if response:
  159. items = response.get("data", {})
  160. normalLiving = items.get("normalLiving", {})
  161. playback = normalLiving.get("playback")
  162. return playback
  163. else:
  164. return None
  165. except Exception as e:
  166. log.error(f"Error fetching playback {product_id}: {e}")
  167. return None
  168. def clean_texts(html_text):
  169. """
  170. 使用 BeautifulSoup 解析并获取纯文本
  171. :param html_text: 待解析的HTML格式的数据
  172. :return: clean_text -> 解析后的数据
  173. """
  174. if not html_text:
  175. return ""
  176. soup = BeautifulSoup(html_text, 'html.parser')
  177. # clean_text = soup.get_text(separator=' ', strip=True)
  178. clean_text = soup.get_text(strip=True)
  179. # 替换   为普通空格
  180. clean_text = clean_text.replace(' ', ' ')
  181. return clean_text
  182. def parse_product_items(log, items, sql_pool, product_id, token):
  183. """
  184. 解析 产品信息
  185. :param log: logger对象
  186. :param items: 请求response
  187. :param sql_pool: MySQL连接池对象
  188. :param product_id: product_id
  189. :param token: token
  190. """
  191. if not items:
  192. log.warning(f"Warning {inspect.currentframe().f_code.co_name}: No items found")
  193. return
  194. no = items.get("id")
  195. create_time = items.get("publishTime")
  196. title = items.get("productName")
  197. img = items.get("productImageIndex")
  198. price_sale = items.get("unitPriceStr")
  199. total_price = items.get("totalSalePrice")
  200. sale_num = items.get("saleCount") # 售出数量
  201. spec_config = items.get("hitCardStandard") # 规格
  202. sort = items.get("series") # 分类 0:全部 1:原盒 2:幸运盒 3:福盒?
  203. state = items.get("status")
  204. shop_id = items.get("merchantCode")
  205. shop_name = items.get("merchantName")
  206. category = items.get("brandId")
  207. on_sale_time = items.get("onlineTime")
  208. end_time = items.get("endTime")
  209. finish_time = items.get("finishTime")
  210. # content = items.get("purchaseNotes")
  211. # if content:
  212. # content = content.replace("<p>", "").replace("</p>", "")
  213. # brief = items.get("brief")
  214. product_detail = items.get("productDetail")
  215. if product_detail:
  216. product_detail = clean_texts(product_detail)
  217. # print('product_detail:',product_detail)
  218. video_url = get_play_back(log, product_id, token)
  219. hit_card_desc = items.get("hitCardDesc") # 赠品介绍
  220. open_mode = items.get("openMode") # 随机球队
  221. open_mode_comment = items.get("openModeComment") # 随机球队 说明
  222. random_mode = items.get("randomMode") # 即买即随
  223. random_mode_comment = items.get("randomModeComment") # 即买即随 说明
  224. info_dict = {
  225. "no": no,
  226. "create_time": create_time,
  227. "title": title,
  228. "img": img,
  229. "price_sale": price_sale,
  230. "total_price": total_price,
  231. "sale_num": sale_num,
  232. "spec_config": spec_config,
  233. "sort": sort,
  234. "state": state,
  235. "shop_id": shop_id,
  236. "shop_name": shop_name,
  237. "category": category,
  238. "on_sale_time": on_sale_time,
  239. "end_time": end_time,
  240. "finish_time": finish_time,
  241. "product_detail": product_detail,
  242. "video_url": video_url,
  243. "hit_card_desc": hit_card_desc,
  244. "open_mode": open_mode,
  245. "open_mode_comment": open_mode_comment,
  246. "random_mode": random_mode,
  247. "random_mode_comment": random_mode_comment,
  248. }
  249. # print(info_dict)
  250. # sql_pool.insert_one_or_dict(table="yueka_product_record", data=info_dict)
  251. sql_pool.update_one_or_dict(table="yueka_product_record", data=info_dict, condition={"product_id": product_id})
  252. @retry(stop=stop_after_attempt(5), wait=wait_fixed(1), after=after_log)
  253. def get_product_details(log, product_id, sql_pool, token):
  254. """
  255. 获取 商品详情 单条 信息
  256. :param log: logger对象
  257. :param product_id: product_id
  258. :param sql_pool: MySQL连接池对象
  259. :param token: token
  260. """
  261. log.debug(f"Getting product details for {product_id}")
  262. url = "https://api.joycard.xyz/api/front/c/product/productDetail"
  263. params = {
  264. # "code": "LCS1254079"
  265. "code": product_id
  266. }
  267. try:
  268. response = make_request(log, 'GET', url, params=params, token=token)
  269. if response:
  270. parse_product_items(log, response.get("data"), sql_pool, product_id, token)
  271. else:
  272. log.error(f"Error getting product details for {product_id}: {response.get('msg')}")
  273. except Exception as e:
  274. log.error(f"Error getting product details for {product_id}: {e}")
  275. def get_product_detail_list(log, sql_pool, token):
  276. """
  277. 获取 商品详情 列表 信息
  278. :param log: logger对象
  279. :param sql_pool: MySQL连接池对象
  280. :param token: token
  281. """
  282. sql_product_id_list = sql_pool.select_all("SELECT product_id FROM yueka_product_record WHERE no IS NULL")
  283. sql_product_id_list = [item[0] for item in sql_product_id_list]
  284. for product_id in sql_product_id_list:
  285. try:
  286. get_product_details(log, product_id, sql_pool, token)
  287. except Exception as e:
  288. log.error(f"Error get_product_detail_list fetching product {product_id}: {e}")
  289. continue
  290. def parse_player_items(log, items, sql_pool, product_id):
  291. """
  292. 解析 卡密公示 信息
  293. :param log: logger对象
  294. :param items: 请求response
  295. :param product_id: product_id
  296. :param sql_pool: MySQL连接池对象
  297. """
  298. if not items:
  299. log.warning(f"Warning {inspect.currentframe().f_code.co_name}: No items found")
  300. return
  301. player_list = []
  302. for item in items:
  303. # print(item)
  304. user_code = item.get("userCode")
  305. user_id = item.get("userId")
  306. user_name = item.get("nickName")
  307. num = item.get("cardCount")
  308. # info = (product_id, user_code, num, user_id, user_name)
  309. info_dict = {
  310. "product_id": product_id,
  311. "user_code": user_code,
  312. "num": num,
  313. "user_id": user_id,
  314. "user_name": user_name
  315. }
  316. # print(info_dict)
  317. player_list.append(info_dict)
  318. sql_pool.insert_many(table='yueka_player_record', data_list=player_list)
  319. sql_pool.update_one("update yueka_product_record set km_state = 1 where product_id = %s", (product_id,))
  320. @retry(stop=stop_after_attempt(5), wait=wait_fixed(1), after=after_log)
  321. def get_player_list(log, product_id, sql_pool, token):
  322. """
  323. 抓取 kami公示 信息
  324. :param log: logger对象
  325. :param product_id: product_id
  326. :param sql_pool: MySQL连接池对象
  327. :param token: token
  328. """
  329. log.debug(f"Getting player list for {product_id}")
  330. url = "https://api.joycard.xyz/api/front/c/card/getCardPublicly"
  331. last_id = 0 # 初始lastId为0
  332. total_players = 0
  333. while True:
  334. data = {
  335. "keyword": "",
  336. "lastUserId": last_id,
  337. "productCode": product_id,
  338. "publiclyType": 2, # 1:赠品维度 2:玩家维度
  339. }
  340. # print(data)
  341. try:
  342. response = make_request(log, 'POST', url, data=data, token=token)
  343. if not response:
  344. log.error(f"Error getting player list for {product_id}: Empty response")
  345. break
  346. items = response.get("data", [])
  347. if not items:
  348. log.info(f"No more players found for product {product_id}")
  349. sql_pool.update_one("update yueka_product_record set km_state = 3 where product_id = %s", (product_id,))
  350. break
  351. # 处理当前页数据
  352. parse_player_items(log, items, sql_pool, product_id)
  353. total_players += len(items)
  354. # 如果获取数量超过50条,说明已经获取到所有数据,结束循环
  355. if total_players > 50:
  356. log.debug(f"Total players found for product {product_id}: {total_players}")
  357. break
  358. # 如果获取数量不足20条,说明是最后一页
  359. if len(items) < 20:
  360. log.info(f"Last page detected for product {product_id} (got {len(items)} items)")
  361. break
  362. # 更新lastId为最后一条的userId
  363. last_id = items[-1].get("userId")
  364. # print(last_id)
  365. if not last_id:
  366. log.error("API response missing userId in last item, cannot paginate")
  367. break
  368. # 避免频繁请求
  369. # time.sleep(0.5)
  370. except Exception as e:
  371. log.error(f"Error getting player list for {product_id} at lastId {last_id}: {e}")
  372. break
  373. log.info(f"Finished fetching players for product {product_id}, total: {total_players}")
  374. def get_players(log, sql_pool, token):
  375. """
  376. 抓取 kami公示 信息
  377. :param log: logger对象
  378. :param sql_pool: MySQL连接池对象
  379. :param token: token
  380. """
  381. product_list = sql_pool.select_all("SELECT product_id FROM yueka_product_record WHERE km_state IN (0, 3)")
  382. product_list = [product_id[0] for product_id in product_list]
  383. # token = sql_pool.select_one("SELECT token FROM yueka_token")
  384. # token = token[0]
  385. if not product_list:
  386. log.warning(f"Warning {inspect.currentframe().f_code.co_name}: No product_id found")
  387. return
  388. else:
  389. log.info(f"Start fetching players data. Total products: {len(product_list)}")
  390. for product_id in product_list:
  391. try:
  392. get_player_list(log, product_id, sql_pool, token)
  393. except Exception as e:
  394. log.error(f"Error fetching product {product_id}: {e}")
  395. continue
  396. @retry(stop=stop_after_attempt(5), wait=wait_fixed(1), after=after_log)
  397. def get_report_one_page(log, sql_pool, productCode, page, last_id, token):
  398. """
  399. 获取 拆卡报告 单页的信息
  400. :param log: logger对象
  401. :param sql_pool: MySQL连接池对象
  402. :param productCode: product_id
  403. :param page: 页码
  404. :param last_id: last_id
  405. :param token: token
  406. """
  407. url = "https://api.joycard.xyz/api/front/c/card/getHitCardReport"
  408. data = {
  409. "keyword": "",
  410. "page": page,
  411. "lastId": last_id,
  412. # "productCode": "LCS1254213"
  413. "productCode": productCode
  414. }
  415. log.info(f"Getting report data for: {productCode}, Page: {page}")
  416. try:
  417. response = make_request(log, 'POST', url, data=data, token=token)
  418. # print(response)
  419. if response:
  420. items = response.get("data", [])
  421. if items:
  422. info_list = []
  423. for item in items:
  424. card_id = item.get("orderNo")
  425. card_name = item.get("cardSecret")
  426. create_time = item.get("drawTime")
  427. imgs = item.get("hitPic")
  428. user_id = item.get("userCode")
  429. user_name = item.get("nickName")
  430. shop_id = item.get("merchantCode")
  431. shop_name = item.get("merchantName")
  432. card_desc = item.get("hitCardDesc")
  433. # info = (card_id, card_name, create_time, imgs, user_id, user_name, shop_id, shop_name, card_desc)
  434. info_dict = {
  435. "product_id": productCode,
  436. "card_id": card_id,
  437. "card_name": card_name,
  438. "create_time": create_time,
  439. "imgs": imgs,
  440. "user_id": user_id,
  441. "user_name": user_name,
  442. "shop_id": shop_id,
  443. "shop_name": shop_name,
  444. "card_desc": card_desc
  445. }
  446. # print(info_dict)
  447. info_list.append(info_dict)
  448. sql_pool.insert_many(table='yueka_report_record', data_list=info_list)
  449. log.info(f"Successfully saved {len(items)} report items")
  450. return items[-1].get("userCode"), len(items)
  451. else:
  452. log.warning(f"Warning {inspect.currentframe().f_code.co_name}: No items found")
  453. sql_pool.update_one("update yueka_product_record set report_state = 3 where product_id = %s",
  454. (productCode,))
  455. return 0, 0
  456. else:
  457. log.error(f"Error getting report data: {response.get('msg')}")
  458. return 0
  459. except Exception as e:
  460. log.error(f"Error getting report data: {e}")
  461. raise e
  462. def get_report_list(log, sql_pool, product_id, token):
  463. """
  464. 抓取 拆卡报告 单个product_id 所有页码的 信息
  465. :param log: logger对象
  466. :param sql_pool: MySQL连接池对象
  467. :param product_id: product_id
  468. :param token: token
  469. """
  470. # log.info(f"Start fetching report data. Product id: {product_id}")
  471. page = 1
  472. last_id = 0
  473. # while True:
  474. try:
  475. last_d, len_item = get_report_one_page(log, sql_pool, product_id, page, last_id, token)
  476. # if len_item != 0 and len_item < 20:
  477. log.info(f"Finished fetching report data for product {product_id}, total: {len_item}")
  478. sql_pool.update_one("update yueka_product_record set report_state = 1 where product_id = %s", (product_id,))
  479. # # 如果获取数量不足20条,说明是最后一页 ***暂时没找到第二页的***
  480. # if len_item < 20:
  481. # log.info(f"Last page detected for product {product_id} (got {len_item} items)")
  482. # break
  483. #
  484. # # 更新lastId为最后一条的userId
  485. # last_id = last_d
  486. # if not last_id:
  487. # log.error("API response missing userId in last item, cannot paginate")
  488. # break
  489. #
  490. # page += 1
  491. except Exception as e:
  492. log.error(f"Error getting report data: {e}")
  493. # break
  494. def get_reports(log, sql_pool, token):
  495. """
  496. 抓取 拆卡报告 信息
  497. :param log: logger对象
  498. :param sql_pool: MySQL连接池对象
  499. :param token: token
  500. """
  501. product_list = sql_pool.select_all("SELECT product_id FROM yueka_product_record WHERE report_state IN (0, 3)")
  502. product_list = [product_id[0] for product_id in product_list]
  503. # token = sql_pool.select_one("SELECT token FROM yueka_token")
  504. # token = token[0]
  505. if not product_list:
  506. log.warning(f"Warning {inspect.currentframe().f_code.co_name}: No product_id found")
  507. return
  508. else:
  509. log.info(f"Start fetching report data. Total products: {len(product_list)}")
  510. for product_id in product_list:
  511. try:
  512. get_report_list(log, sql_pool, product_id, token)
  513. except Exception as e:
  514. log.error(f"Error fetching product {product_id}: {e}")
  515. continue
  516. if __name__ == '__main__':
  517. pass
  518. # pid = 'LCS1254213'
  519. # pid = 'LCS1253418'
  520. # pid = 'LCS1256332'
  521. # from mysql_pool import MySQLConnectionPool
  522. # sql_pool_ = MySQLConnectionPool(log=logger)
  523. # get_reports(logger, None)
  524. # get_player_list(logger, pid, None)
  525. # get_product_details(logger, 'LCS1255968', sql_pool_)