updatePublishedMsgDaily.py 19 KB

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