xiaoniangao_author_scheduling.py 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304
  1. # -*- coding: utf-8 -*-
  2. # @Author: wangkun
  3. # @Time: 2023/3/13
  4. import json
  5. import os
  6. import random
  7. import shutil
  8. import sys
  9. import time
  10. from hashlib import md5
  11. import requests
  12. import urllib3
  13. from common.mq import MQ
  14. sys.path.append(os.getcwd())
  15. from common.common import Common
  16. from common.scheduling_db import MysqlHelper
  17. from common.publish import Publish
  18. from common.feishu import Feishu
  19. from common.public import get_config_from_mysql, download_rule
  20. proxies = {"http": None, "https": None}
  21. class XiaoniangaoAuthorScheduling:
  22. platform = "小年糕"
  23. @classmethod
  24. def repeat_video(cls, log_type, crawler, video_id, env):
  25. # sql = f""" select * from crawler_video where platform="{cls.platform}" and out_video_id="{video_id}"; """
  26. sql = f""" select * from crawler_video where platform in ("{crawler}","{cls.platform}") and out_video_id="{video_id}"; """
  27. repeat_video = MysqlHelper.get_values(log_type, crawler, sql, env)
  28. return len(repeat_video)
  29. # 获取个人主页视频
  30. @classmethod
  31. def get_videoList(cls, log_type, crawler, rule_dict, user_dict, env):
  32. mq = MQ(topic_name="topic_crawler_etl_" + env)
  33. next_t = -1
  34. while True:
  35. url = "https://kapi-xng-app.xiaoniangao.cn/v1/album/user_public"
  36. payload = "{\"share_width\":300,\"log\":{\"brand\":\"iPad\",\"net\":\"wifi\",\"resolution\":\"750*1334\",\"uid\":\"2F310D09-5E32-5985-8644-3BCB6920E76F\",\"app_version\":\"1.22.5\",\"channel\":\"ios_app_store\",\"page\":\"\",\"product\":\"xng\",\"os_version\":\"15.7\",\"pf\":\"4\",\"session_id\":\"47D7817B-AAB1-4E70-BA7F-B868FC9AA21F\",\"idfa\":\"\",\"device\":\"iPad Pro (12.9-inch) (3rd generation)\"},\"qs\":\"imageMogr2\\/gravity\\/center\\/rotate\\/$\\/thumbnail\\/!690x385r\\/interlace\\/1\\/format\\/jpg\",\"share_height\":240,\"start_t\":-1,\"token\":\"\",\"visited_mid\":211201301,\"limit\":20}"
  37. payload_dic = json.loads(payload)
  38. payload_dic['start_t'] = next_t
  39. payload_dic['visited_mid'] = int(user_dict['link'])
  40. payload_new = json.dumps(payload_dic)
  41. headers = {
  42. 'Host': 'kapi-xng-app.xiaoniangao.cn',
  43. 'content-type': 'application/json; charset=utf-8',
  44. 'accept': '*/*',
  45. 'authorization': 'hSNQ2s9pvPxvFn4LaQJxKQ6/7Is=',
  46. 'verb': 'POST',
  47. 'content-md5': 'c7b7f8663984e8800e3bcd9b44465083',
  48. 'x-b3-traceid': '2f9da41f960ae077',
  49. 'accept-language': 'zh-cn',
  50. 'date': 'Mon, 19 Jun 2023 06:41:17 GMT',
  51. 'x-token-id': '',
  52. 'x-signaturemethod': 'hmac-sha1',
  53. 'user-agent': 'xngapp/157 CFNetwork/1335.0.3.1 Darwin/21.6.0'
  54. }
  55. urllib3.disable_warnings()
  56. r = requests.post(url=url, headers=headers, data=payload_new, proxies=proxies, verify=False)
  57. if 'data' not in r.text or r.status_code != 200:
  58. Common.logger(log_type, crawler).info(f"get_videoList:{r.text}\n")
  59. Common.logging(log_type, crawler, env, f"get_videoList:{r.text}\n")
  60. return
  61. elif 'list' not in r.json()['data']:
  62. Common.logger(log_type, crawler).info(f"get_videoList:{r.json()}\n")
  63. Common.logging(log_type, crawler, env, f"get_videoList:{r.json()}\n")
  64. return
  65. elif len(r.json()['data']['list']) == 0:
  66. Common.logger(log_type, crawler).info(f"没有更多数据啦~\n")
  67. Common.logging(log_type, crawler, env, f"没有更多数据啦~\n")
  68. return
  69. else:
  70. next_t = r.json()["data"]["next_t"]
  71. feeds = r.json()["data"]["list"]
  72. for i in range(len(feeds)):
  73. try:
  74. # 标题,表情随机加在片头、片尾,或替代句子中间的标点符号
  75. xiaoniangao_title = feeds[i].get("title", "").strip().replace("\n", "") \
  76. .replace("/", "").replace("\r", "").replace("#", "") \
  77. .replace(".", "。").replace("\\", "").replace("&NBSP", "") \
  78. .replace(":", "").replace("*", "").replace("?", "") \
  79. .replace("?", "").replace('"', "").replace("<", "") \
  80. .replace(">", "").replace("|", "").replace(" ", "") \
  81. .replace('"', '').replace("'", '')
  82. # 随机取一个表情/符号
  83. emoji = random.choice(get_config_from_mysql(log_type, crawler, env, "emoji"))
  84. # 生成最终标题,标题list[表情+title, title+表情]随机取一个
  85. video_title = random.choice([f"{emoji}{xiaoniangao_title}", f"{xiaoniangao_title}{emoji}"])
  86. # 发布时间
  87. publish_time_stamp = int(int(feeds[i].get("t", 0)) / 1000)
  88. publish_time_str = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime(publish_time_stamp))
  89. # 用户名 / 头像
  90. user_name = feeds[i].get("user", {}).get("nick", "").strip().replace("\n", "") \
  91. .replace("/", "").replace(" ", "") \
  92. .replace(" ", "").replace("&NBSP", "").replace("\r", "")
  93. video_dict = {
  94. "video_title": video_title,
  95. "video_id": feeds[i].get("vid", ""),
  96. "duration": int(feeds[i].get("du", 0) / 1000),
  97. "play_cnt": feeds[i].get("play_pv", 0),
  98. "like_cnt": feeds[i].get("favor", {}).get("total", 0),
  99. "comment_cnt": feeds[i].get("comment_count", 0),
  100. "share_cnt": feeds[i].get("share", 0),
  101. "user_name": user_name,
  102. "publish_time_stamp": publish_time_stamp,
  103. "publish_time_str": publish_time_str,
  104. "video_width": int(feeds[i].get("w", 0)),
  105. "video_height": int(feeds[i].get("h", 0)),
  106. "avatar_url": feeds[i].get("user", {}).get("hurl", ""),
  107. "profile_id": feeds[i]["id"],
  108. "profile_mid": feeds[i].get("user", {}).get("mid", ""),
  109. "cover_url": feeds[i].get("url", ""),
  110. "video_url": feeds[i].get("v_url", ""),
  111. "session": f"xiaoniangao-author-{int(time.time())}"
  112. }
  113. for k, v in video_dict.items():
  114. Common.logger(log_type, crawler).info(f"{k}:{v}")
  115. Common.logging(log_type, crawler, env, f"{video_dict}")
  116. if int(time.time()) - publish_time_stamp > 3600 * 24 * int(rule_dict.get('period', {}).get('max', 1000)):
  117. Common.logger(log_type, crawler).info(f"发布时间超过{int(rule_dict.get('period', {}).get('max', 1000))}天\n")
  118. Common.logging(log_type, crawler, env, f"发布时间超过{int(rule_dict.get('period', {}).get('max', 1000))}天\n")
  119. return
  120. # 过滤无效视频
  121. if video_title == "" or video_dict["video_id"] == "" or video_dict["video_url"] == "":
  122. Common.logger(log_type, crawler).info("无效视频\n")
  123. Common.logging(log_type, crawler, env, "无效视频\n")
  124. # 抓取基础规则过滤
  125. elif download_rule(log_type=log_type, crawler=crawler, video_dict=video_dict, rule_dict=rule_dict) is False:
  126. Common.logger(log_type, crawler).info("不满足抓取规则\n")
  127. Common.logging(log_type, crawler, env, "不满足抓取规则\n")
  128. elif any(str(word) if str(word) in video_dict["video_title"] else False
  129. for word in get_config_from_mysql(log_type=log_type,
  130. source=crawler,
  131. env=env,
  132. text="filter",
  133. action="")) is True:
  134. Common.logger(log_type, crawler).info('已中过滤词\n')
  135. Common.logging(log_type, crawler, env, '已中过滤词\n')
  136. elif cls.repeat_video(log_type, crawler, video_dict['video_id'], env) != 0:
  137. Common.logger(log_type, crawler).info('视频已下载\n')
  138. Common.logging(log_type, crawler, env, '视频已下载\n')
  139. else:
  140. # cls.download_publish(log_type=log_type,
  141. # crawler=crawler,
  142. # video_dict=video_dict,
  143. # rule_dict=rule_dict,
  144. # user_dict=user_dict,
  145. # env=env)
  146. video_dict["out_user_id"] = video_dict["profile_id"]
  147. video_dict["platform"] = crawler
  148. video_dict["strategy"] = log_type
  149. video_dict["out_video_id"] = video_dict["video_id"]
  150. video_dict["width"] = video_dict["video_width"]
  151. video_dict["height"] = video_dict["video_height"]
  152. video_dict["crawler_rule"] = json.dumps(rule_dict)
  153. video_dict["user_id"] = user_dict["uid"]
  154. video_dict["publish_time"] = video_dict["publish_time_str"]
  155. mq.send_msg(video_dict)
  156. except Exception as e:
  157. Common.logger(log_type, crawler).error(f"抓取单条视频异常:{e}\n")
  158. Common.logging(log_type, crawler, env, f"抓取单条视频异常:{e}\n")
  159. # 下载/上传
  160. @classmethod
  161. def download_publish(cls, log_type, crawler, video_dict, rule_dict, user_dict, env):
  162. # 下载视频
  163. Common.download_method(log_type=log_type, crawler=crawler, text="video", title=video_dict["video_title"], url=video_dict["video_url"])
  164. md_title = md5(video_dict['video_title'].encode('utf8')).hexdigest()
  165. try:
  166. if os.path.getsize(f"./{crawler}/videos/{md_title}/video.mp4") == 0:
  167. # 删除视频文件夹
  168. shutil.rmtree(f"./{crawler}/videos/{md_title}")
  169. Common.logger(log_type, crawler).info("视频size=0,删除成功\n")
  170. Common.logging(log_type, crawler, env, "视频size=0,删除成功\n")
  171. return
  172. except FileNotFoundError:
  173. # 删除视频文件夹
  174. shutil.rmtree(f"./{crawler}/videos/{md_title}")
  175. Common.logger(log_type, crawler).info("视频文件不存在,删除文件夹成功\n")
  176. Common.logging(log_type, crawler, env, "视频文件不存在,删除文件夹成功\n")
  177. return
  178. # 下载封面
  179. Common.download_method(log_type=log_type, crawler=crawler, text="cover", title=video_dict["video_title"], url=video_dict["cover_url"])
  180. # 保存视频信息至 "./videos/{download_video_title}/info.txt"
  181. Common.save_video_info(log_type=log_type, crawler=crawler, video_dict=video_dict)
  182. # 上传视频
  183. Common.logger(log_type, crawler).info("开始上传视频...")
  184. Common.logging(log_type, crawler, env, "开始上传视频...")
  185. if env == "dev":
  186. oss_endpoint = "out"
  187. our_video_id = Publish.upload_and_publish(log_type=log_type,
  188. crawler=crawler,
  189. strategy="定向抓取策略",
  190. our_uid=user_dict["uid"],
  191. env=env,
  192. oss_endpoint=oss_endpoint)
  193. our_video_link = f"https://testadmin.piaoquantv.com/cms/post-detail/{our_video_id}/info"
  194. else:
  195. oss_endpoint = "inner"
  196. our_video_id = Publish.upload_and_publish(log_type=log_type,
  197. crawler=crawler,
  198. strategy="定向抓取策略",
  199. our_uid=user_dict["uid"],
  200. env=env,
  201. oss_endpoint=oss_endpoint)
  202. our_video_link = f"https://admin.piaoquantv.com/cms/post-detail/{our_video_id}/info"
  203. if our_video_id is None:
  204. try:
  205. # 删除视频文件夹
  206. shutil.rmtree(f"./{crawler}/videos/{md_title}")
  207. return
  208. except FileNotFoundError:
  209. return
  210. insert_sql = f""" insert into crawler_video(video_id,
  211. out_user_id,
  212. platform,
  213. strategy,
  214. out_video_id,
  215. video_title,
  216. cover_url,
  217. video_url,
  218. duration,
  219. publish_time,
  220. play_cnt,
  221. crawler_rule,
  222. width,
  223. height)
  224. values({our_video_id},
  225. "{video_dict['profile_id']}",
  226. "{cls.platform}",
  227. "定向抓取策略",
  228. "{video_dict['video_id']}",
  229. "{video_dict['video_title']}",
  230. "{video_dict['cover_url']}",
  231. "{video_dict['video_url']}",
  232. {int(video_dict['duration'])},
  233. "{video_dict['publish_time_str']}",
  234. {int(video_dict['play_cnt'])},
  235. '{json.dumps(rule_dict)}',
  236. {int(video_dict['video_width'])},
  237. {int(video_dict['video_height'])}) """
  238. Common.logger(log_type, crawler).info(f"insert_sql:{insert_sql}")
  239. Common.logging(log_type, crawler, env, f"insert_sql:{insert_sql}")
  240. MysqlHelper.update_values(log_type, crawler, insert_sql, env)
  241. Common.logger(log_type, crawler).info('视频信息些入数据库成功')
  242. Common.logging(log_type, crawler, env, '视频信息些入数据库成功')
  243. # 视频写入飞书
  244. Feishu.insert_columns(log_type, crawler, "Wu0CeL", "ROWS", 1, 2)
  245. # 视频ID工作表,首行写入数据
  246. upload_time = int(time.time())
  247. values = [[time.strftime("%Y-%m-%d %H:%M:%S", time.localtime(upload_time)),
  248. "用户主页",
  249. str(video_dict['video_id']),
  250. str(video_dict['video_title']),
  251. our_video_link,
  252. video_dict['play_cnt'],
  253. video_dict['comment_cnt'],
  254. video_dict['like_cnt'],
  255. video_dict['share_cnt'],
  256. video_dict['duration'],
  257. f"{video_dict['video_width']}*{video_dict['video_height']}",
  258. str(video_dict['publish_time_str']),
  259. str(video_dict['user_name']),
  260. str(video_dict['profile_id']),
  261. str(video_dict['profile_mid']),
  262. str(video_dict['avatar_url']),
  263. str(video_dict['cover_url']),
  264. str(video_dict['video_url'])]]
  265. time.sleep(1)
  266. Feishu.update_values(log_type, crawler, "Wu0CeL", "F2:Z2", values)
  267. Common.logger(log_type, crawler).info('视频信息写入飞书成功\n')
  268. Common.logging(log_type, crawler, env, '视频信息写入飞书成功\n')
  269. # 获取所有关注列表的用户视频
  270. @classmethod
  271. def get_author_videos(cls, log_type, crawler, user_list, rule_dict, env):
  272. for user_dict in user_list:
  273. try:
  274. Common.logger(log_type, crawler).info(f"获取 {user_dict['nick_name']} 主页视频")
  275. Common.logging(log_type, crawler, env, f"获取 {user_dict['nick_name']} 主页视频")
  276. cls.get_videoList(log_type=log_type,
  277. crawler=crawler,
  278. rule_dict=rule_dict,
  279. user_dict=user_dict,
  280. env=env)
  281. except Exception as e:
  282. Common.logger(log_type, crawler).error(f"抓取{user_dict['nick_name']}主页时异常:{e}\n")
  283. Common.logging(log_type, crawler, env, f"抓取{user_dict['nick_name']}主页时异常:{e}\n")
  284. if __name__ == "__main__":
  285. pass