updatePublishedMsgDaily.py 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613
  1. """
  2. @author: luojunhui
  3. @description: update daily information into official articles v2
  4. """
  5. import time
  6. import json
  7. import traceback
  8. import urllib.parse
  9. from tqdm import tqdm
  10. from datetime import datetime
  11. from applications import PQMySQL, WeixinSpider, Functions, log, bot, aiditApi
  12. ARTICLE_TABLE = "official_articles_v2"
  13. ARTICLE_DELETE_CODE = 25005
  14. ARTICLE_SUCCESS_CODE = 0
  15. DEFAULT_STATUS = 0
  16. REQUEST_FAIL_STATUS = -1
  17. DELETE_STATUS = -2
  18. UNKNOWN_STATUS = -3
  19. def get_accounts_v1():
  20. """
  21. 获取账号信息
  22. :return: [{}, {},...], [{}, {}, {}...]
  23. """
  24. with open("config/accountInfoV0914.json", encoding="utf-8") as f:
  25. account_list = json.loads(f.read())
  26. subscription_account = [i for i in account_list if i['type'] == '订阅号']
  27. server_account = [i for i in account_list if i['type'] == '服务号']
  28. return subscription_account, server_account
  29. def get_account_using_status():
  30. """
  31. 获取正在 using 的 ghid
  32. :return:
  33. """
  34. sql = "SELECT gh_id FROM long_articles_publishing_accounts WHERE is_using = 1;"
  35. gh_id_tuple = PQMySQL().select(sql)
  36. gh_id_list = [
  37. i[0] for i in gh_id_tuple
  38. ]
  39. return set(gh_id_list)
  40. def get_accounts():
  41. """
  42. 从 aigc 数据库中获取目前处于发布状态的账号
  43. :return:
  44. "name": line[0],
  45. "ghId": line[1],
  46. "follower_count": line[2],
  47. "account_init_time": int(line[3] / 1000),
  48. "account_type": line[4],
  49. "account_auth": line[5]
  50. """
  51. using_account_set = get_account_using_status()
  52. account_list_with_out_using_status = aiditApi.get_publish_account_from_aigc()
  53. account_list = []
  54. for item in account_list_with_out_using_status:
  55. if item['ghId'] in using_account_set:
  56. item['using_status'] = 1
  57. else:
  58. item['using_status'] = 0
  59. account_list.append(item)
  60. subscription_account = [i for i in account_list if i['account_type'] in {0, 1}]
  61. server_account = [i for i in account_list if i['account_type'] == 2]
  62. return subscription_account, server_account
  63. def insert_each_msg(db_client, account_info, account_name, msg_list):
  64. """
  65. 把消息数据更新到数据库中
  66. :param account_info:
  67. :param db_client:
  68. :param account_name:
  69. :param msg_list:
  70. :return:
  71. """
  72. gh_id = account_info['ghId']
  73. for info in msg_list:
  74. baseInfo = info.get("BaseInfo", {})
  75. appMsgId = info.get("AppMsg", {}).get("BaseInfo", {}).get("AppMsgId", None)
  76. createTime = info.get("AppMsg", {}).get("BaseInfo", {}).get("CreateTime", None)
  77. updateTime = info.get("AppMsg", {}).get("BaseInfo", {}).get("UpdateTime", None)
  78. Type = info.get("AppMsg", {}).get("BaseInfo", {}).get("Type", None)
  79. detail_article_list = info.get("AppMsg", {}).get("DetailInfo", [])
  80. if detail_article_list:
  81. for article in detail_article_list:
  82. title = article.get("Title", None)
  83. Digest = article.get("Digest", None)
  84. ItemIndex = article.get("ItemIndex", None)
  85. ContentUrl = article.get("ContentUrl", None)
  86. SourceUrl = article.get("SourceUrl", None)
  87. CoverImgUrl = article.get("CoverImgUrl", None)
  88. CoverImgUrl_1_1 = article.get("CoverImgUrl_1_1", None)
  89. CoverImgUrl_235_1 = article.get("CoverImgUrl_235_1", None)
  90. ItemShowType = article.get("ItemShowType", None)
  91. IsOriginal = article.get("IsOriginal", None)
  92. ShowDesc = article.get("ShowDesc", None)
  93. show_stat = Functions().show_desc_to_sta(ShowDesc)
  94. ori_content = article.get("ori_content", None)
  95. show_view_count = show_stat.get("show_view_count", 0)
  96. show_like_count = show_stat.get("show_like_count", 0)
  97. show_zs_count = show_stat.get("show_zs_count", 0)
  98. show_pay_count = show_stat.get("show_pay_count", 0)
  99. wx_sn = ContentUrl.split("&sn=")[1].split("&")[0] if ContentUrl else None
  100. status = account_info['using_status']
  101. info_tuple = (
  102. gh_id,
  103. account_name,
  104. appMsgId,
  105. title,
  106. Type,
  107. createTime,
  108. updateTime,
  109. Digest,
  110. ItemIndex,
  111. ContentUrl,
  112. SourceUrl,
  113. CoverImgUrl,
  114. CoverImgUrl_1_1,
  115. CoverImgUrl_235_1,
  116. ItemShowType,
  117. IsOriginal,
  118. ShowDesc,
  119. ori_content,
  120. show_view_count,
  121. show_like_count,
  122. show_zs_count,
  123. show_pay_count,
  124. wx_sn,
  125. json.dumps(baseInfo, ensure_ascii=False),
  126. Functions().str_to_md5(title),
  127. status
  128. )
  129. try:
  130. insert_sql = f"""
  131. INSERT INTO {ARTICLE_TABLE}
  132. (ghId, accountName, appMsgId, title, Type, createTime, updateTime, Digest, ItemIndex, ContentUrl, SourceUrl, CoverImgUrl, CoverImgUrl_1_1, CoverImgUrl_255_1, ItemShowType, IsOriginal, ShowDesc, ori_content, show_view_count, show_like_count, show_zs_count, show_pay_count, wx_sn, baseInfo, title_md5, status)
  133. values
  134. (%s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s);
  135. """
  136. db_client.update(sql=insert_sql, params=info_tuple)
  137. log(
  138. task="updatePublishedMsgDaily",
  139. function="insert_each_msg",
  140. message="插入文章数据成功",
  141. data={
  142. "info": info_tuple
  143. }
  144. )
  145. except Exception as e:
  146. try:
  147. update_sql = f"""
  148. UPDATE {ARTICLE_TABLE}
  149. SET show_view_count = %s, show_like_count=%s
  150. WHERE wx_sn = %s;
  151. """
  152. db_client.update(sql=update_sql,
  153. params=(show_view_count, show_like_count, wx_sn))
  154. log(
  155. task="updatePublishedMsgDaily",
  156. function="insert_each_msg",
  157. message="更新文章数据成功",
  158. data={
  159. "wxSn": wx_sn,
  160. "likeCount": show_like_count,
  161. "viewCount": show_view_count
  162. }
  163. )
  164. except Exception as e:
  165. log(
  166. task="updatePublishedMsgDaily",
  167. function="insert_each_msg",
  168. message="更新文章失败, 报错原因是: {}".format(e),
  169. status="fail"
  170. )
  171. continue
  172. def update_each_account(db_client, account_info, account_name, latest_update_time, cursor=None):
  173. """
  174. 更新每一个账号信息
  175. :param account_info:
  176. :param account_name:
  177. :param cursor:
  178. :param latest_update_time: 最新更新时间
  179. :param db_client: 数据库连接信息
  180. :return: None
  181. """
  182. gh_id = account_info['ghId']
  183. response = WeixinSpider().update_msg_list(ghId=gh_id, index=cursor)
  184. msg_list = response.get("data", {}).get("data", {})
  185. if msg_list:
  186. # do
  187. last_article_in_this_msg = msg_list[-1]
  188. last_time_stamp_in_this_msg = last_article_in_this_msg['AppMsg']['BaseInfo']['UpdateTime']
  189. last_url = last_article_in_this_msg['AppMsg']['DetailInfo'][0]['ContentUrl']
  190. resdata = WeixinSpider().get_account_by_url(last_url)
  191. check_id = resdata['data'].get('data', {}).get('wx_gh')
  192. if check_id == gh_id:
  193. insert_each_msg(
  194. db_client=db_client,
  195. account_info=account_info,
  196. account_name=account_name,
  197. msg_list=msg_list
  198. )
  199. if last_time_stamp_in_this_msg > latest_update_time:
  200. next_cursor = response['data']['next_cursor']
  201. return update_each_account(
  202. db_client=db_client,
  203. account_info=account_info,
  204. account_name=account_name,
  205. latest_update_time=latest_update_time,
  206. cursor=next_cursor
  207. )
  208. log(
  209. task="updatePublishedMsgDaily",
  210. function="update_each_account",
  211. message="账号文章更新成功",
  212. data=response
  213. )
  214. else:
  215. log(
  216. task="updatePublishedMsgDaily",
  217. function="update_each_account",
  218. message="账号文章更新失败",
  219. status="fail",
  220. data=response
  221. )
  222. return
  223. def check_account_info(db_client, gh_id, account_name):
  224. """
  225. 通过 gh_id查询视频信息
  226. :param account_name:
  227. :param db_client:
  228. :param gh_id:
  229. :return:
  230. """
  231. sql = f"""
  232. SELECT accountName, updateTime
  233. FROM {ARTICLE_TABLE}
  234. WHERE ghId = '{gh_id}'
  235. ORDER BY updateTime DESC LIMIT 1;
  236. """
  237. result = db_client.select(sql)
  238. if result:
  239. old_account_name, update_time = result[0]
  240. return {
  241. "account_name": old_account_name,
  242. "update_time": update_time,
  243. "account_type": "history"
  244. }
  245. else:
  246. return {
  247. "account_name": account_name,
  248. "update_time": int(time.time()) - 30 * 24 * 60 * 60,
  249. "account_type": "new"
  250. }
  251. def update_single_account(db_client, account_info):
  252. """
  253. :param account_info:
  254. :param db_client:
  255. :return:
  256. """
  257. gh_id = account_info['ghId']
  258. account_name = account_info['name']
  259. account_detail = check_account_info(db_client, gh_id, account_name)
  260. account_name = account_detail['account_name']
  261. update_time = account_detail['update_time']
  262. update_each_account(
  263. db_client=db_client,
  264. account_info=account_info,
  265. account_name=account_name,
  266. latest_update_time=update_time
  267. )
  268. def check_single_account(db_client, account_item):
  269. """
  270. 校验每个账号是否更新
  271. :param db_client:
  272. :param account_item:
  273. :return: True / False
  274. """
  275. gh_id = account_item['ghId']
  276. account_type = account_item['account_type']
  277. today_str = datetime.today().strftime("%Y-%m-%d")
  278. today_date_time = datetime.strptime(today_str, "%Y-%m-%d")
  279. today_timestamp = today_date_time.timestamp()
  280. sql = f"""
  281. SELECT updateTime
  282. FROM {ARTICLE_TABLE}
  283. WHERE ghId = '{gh_id}'
  284. ORDER BY updateTime
  285. DESC
  286. LIMIT 1;
  287. """
  288. try:
  289. latest_update_time = db_client.select(sql)[0][0]
  290. # 判断该账号当天发布的文章是否被收集
  291. if account_type in {0, 1}:
  292. if int(latest_update_time) > int(today_timestamp):
  293. return True
  294. else:
  295. return False
  296. else:
  297. if int(latest_update_time) > int(today_timestamp) - 7 * 24 * 3600:
  298. return True
  299. else:
  300. return False
  301. except Exception as e:
  302. print("updateTime Error -- {}".format(e))
  303. return False
  304. def update_job():
  305. """
  306. 更新任务
  307. :return:
  308. """
  309. try:
  310. db_client = PQMySQL()
  311. except Exception as e:
  312. error_msg = traceback.format_exc()
  313. bot(
  314. title="更新文章任务连接数据库失败",
  315. detail={
  316. "error": e,
  317. "msg": error_msg
  318. }
  319. )
  320. return
  321. sub_accounts, server_accounts = get_accounts()
  322. s_count = 0
  323. f_count = 0
  324. for sub_item in tqdm(sub_accounts):
  325. try:
  326. update_single_account(db_client, sub_item)
  327. s_count += 1
  328. time.sleep(5)
  329. except Exception as e:
  330. f_count += 1
  331. log(
  332. task="updatePublishedMsgDaily",
  333. function="update_job",
  334. message="单个账号文章更新失败, 报错信息是: {}".format(e),
  335. status="fail",
  336. )
  337. log(
  338. task="updatePublishedMsgDaily",
  339. function="update_job",
  340. message="订阅号更新完成",
  341. data={
  342. "success": s_count,
  343. "fail": f_count
  344. }
  345. )
  346. if f_count / (s_count + f_count) > 0.3:
  347. bot(
  348. title="订阅号超过 30% 的账号更新失败",
  349. detail={
  350. "success": s_count,
  351. "fail": f_count,
  352. "failRate": f_count / (s_count + f_count)
  353. }
  354. )
  355. bot(
  356. title="更新每日发布文章任务完成通知",
  357. detail={
  358. "msg": "订阅号更新完成",
  359. "finish_time": datetime.today().__str__()
  360. },
  361. mention=False
  362. )
  363. for sub_item in tqdm(server_accounts):
  364. try:
  365. update_single_account(db_client, sub_item)
  366. time.sleep(5)
  367. except Exception as e:
  368. print(e)
  369. bot(
  370. title="更新每日发布文章任务完成通知",
  371. detail={
  372. "msg": "服务号更新完成",
  373. "finish_time": datetime.today().__str__()
  374. },
  375. mention=False
  376. )
  377. def check_job():
  378. """
  379. 校验任务
  380. :return:
  381. """
  382. try:
  383. db_client = PQMySQL()
  384. except Exception as e:
  385. error_msg = traceback.format_exc()
  386. bot(
  387. title="校验更新文章任务连接数据库失败",
  388. detail={
  389. "job": "check_job",
  390. "error": e,
  391. "msg": error_msg
  392. }
  393. )
  394. return
  395. sub_accounts, server_accounts = get_accounts()
  396. fail_list = []
  397. # account_list = sub_accounts + server_accounts
  398. account_list = sub_accounts
  399. # check and rework if fail
  400. for sub_item in tqdm(account_list):
  401. res = check_single_account(db_client, sub_item)
  402. if not res:
  403. update_single_account(db_client, sub_item)
  404. # check whether success and bot if fails
  405. for sub_item in tqdm(account_list):
  406. res = check_single_account(db_client, sub_item)
  407. if not res:
  408. fail_list.append(sub_item)
  409. if fail_list:
  410. try:
  411. bot(
  412. title="日常报警, 存在账号更新失败",
  413. detail=fail_list
  414. )
  415. except Exception as e:
  416. print("Timeout Error: {}".format(e))
  417. else:
  418. bot(
  419. title="校验完成通知",
  420. mention=False,
  421. detail={
  422. "msg": "校验任务完成",
  423. "finish_time": datetime.today().__str__()
  424. }
  425. )
  426. def get_articles(db_client):
  427. """
  428. :return:
  429. """
  430. sql = f"""
  431. SELECT ContentUrl, wx_sn
  432. FROM official_articles_v2
  433. WHERE publish_timestamp in {(DEFAULT_STATUS, REQUEST_FAIL_STATUS)};"""
  434. response = db_client.select(sql)
  435. return response
  436. def update_publish_timestamp(db_client, row):
  437. """
  438. 更新发布时间戳 && minigram 信息
  439. :param db_client:
  440. :param row:
  441. :return:
  442. """
  443. url = row[0]
  444. wx_sn = row[1]
  445. try:
  446. response = WeixinSpider().get_article_text(url)
  447. response_code = response['code']
  448. if response_code == ARTICLE_DELETE_CODE:
  449. publish_timestamp_s = DELETE_STATUS
  450. root_source_id_list = []
  451. elif response_code == ARTICLE_SUCCESS_CODE:
  452. data = response['data']['data']
  453. publish_timestamp_ms = data['publish_timestamp']
  454. publish_timestamp_s = int(publish_timestamp_ms / 1000)
  455. mini_program = data.get('mini_program', [])
  456. if mini_program:
  457. root_source_id_list = [
  458. urllib.parse.parse_qs(
  459. urllib.parse.unquote(i['path'])
  460. )['rootSourceId'][0]
  461. for i in mini_program
  462. ]
  463. else:
  464. root_source_id_list = []
  465. else:
  466. publish_timestamp_s = UNKNOWN_STATUS
  467. root_source_id_list = []
  468. except Exception as e:
  469. publish_timestamp_s = REQUEST_FAIL_STATUS
  470. root_source_id_list = []
  471. error_msg = traceback.format_exc()
  472. print(e, error_msg)
  473. update_sql = f"""
  474. UPDATE official_articles_v2
  475. SET publish_timestamp = %s, root_source_id_list = %s
  476. WHERE wx_sn = %s;
  477. """
  478. db_client.update(
  479. sql=update_sql,
  480. params=(
  481. publish_timestamp_s,
  482. json.dumps(root_source_id_list, ensure_ascii=False),
  483. wx_sn
  484. ))
  485. if publish_timestamp_s == REQUEST_FAIL_STATUS:
  486. return row
  487. else:
  488. return None
  489. def get_article_detail_job():
  490. """
  491. 获取发布文章详情
  492. :return:
  493. """
  494. try:
  495. db_client = PQMySQL()
  496. except Exception as e:
  497. error_msg = traceback.format_exc()
  498. bot(
  499. title="获取文章详情任务连接数据库失败",
  500. detail={
  501. "job": "get_article_detail_job",
  502. "error": e,
  503. "msg": error_msg
  504. }
  505. )
  506. return
  507. article_tuple = get_articles(db_client)
  508. for article in tqdm(article_tuple):
  509. try:
  510. update_publish_timestamp(db_client=db_client, row=article)
  511. except Exception as e:
  512. print(e)
  513. error_msg = traceback.format_exc()
  514. print(error_msg)
  515. # check 一遍存在请求失败-1 && 0 的文章
  516. process_failed_articles = get_articles(db_client)
  517. fail_list = []
  518. if process_failed_articles:
  519. for article in tqdm(process_failed_articles):
  520. try:
  521. res = update_publish_timestamp(db_client=db_client, row=article)
  522. fail_list.append({"wx_sn": res[1], "url": res[0]})
  523. except Exception as e:
  524. print(e)
  525. error_msg = traceback.format_exc()
  526. print(error_msg)
  527. # 通过msgId 来修改publish_timestamp
  528. update_sql = f"""
  529. UPDATE official_articles_v2 oav
  530. JOIN (
  531. SELECT appMsgId, MAX(publish_timestamp) AS publish_timestamp
  532. FROM official_articles_v2
  533. WHERE publish_timestamp > %s
  534. GROUP BY appMsgId
  535. ) vv
  536. ON oav.appMsgId = vv.appMsgId
  537. SET oav.publish_timestamp = vv.publish_timestamp
  538. WHERE oav.publish_timestamp <= %s;
  539. """
  540. affected_rows = db_client.update(
  541. sql=update_sql,
  542. params=(0, 0)
  543. )
  544. # 若还是无 publish_timestamp,用update_time当作 publish_timestamp
  545. update_sql_2 = f"""
  546. UPDATE official_articles_v2
  547. SET publish_timestamp = update_time
  548. WHERE publish_timestamp <= %s;
  549. """
  550. db_client.update(
  551. sql=update_sql_2,
  552. params=0
  553. )
  554. if fail_list:
  555. bot(
  556. title="更新文章任务,请求detail失败",
  557. detail=fail_list
  558. )
  559. def main():
  560. """
  561. main
  562. :return:
  563. """
  564. update_job()
  565. check_job()
  566. get_article_detail_job()
  567. if __name__ == '__main__':
  568. main()