PULL_DATA.js 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557
  1. const CMD = {}
  2. const time_count = 1000;
  3. const redis_help = require('../src/use_redis');
  4. const origin_data_controllers = require('../src/data_manager/Controllers/origin_data_controllers');
  5. const axios = require('axios')
  6. const config = require('../etc/config.json');
  7. const DailyRecordManager = require('./daily_records');
  8. const schedule = require('node-schedule');
  9. const manager = new DailyRecordManager();
  10. const rabbitMq = require('../src/mq/rabbit-mq');
  11. const helper = require('../src/helper');
  12. const PullDataService = require('../src/PullDataService');
  13. var _24HourRanges = []
  14. var jobs = []
  15. var cur_day_data = new Map()
  16. var cur_timeRange = null
  17. var pullDataService = new PullDataService(redis_help)
  18. var cur_page = 0
  19. const messageHandler = async (msg) => {
  20. let PullDataConfig = await redis_help.getKeyValue("PullDataConfig")
  21. PullDataConfig = JSON.parse(PullDataConfig)
  22. _24HourRanges = PullDataConfig
  23. CMD.startScheduler(taskCallback)
  24. };
  25. const taskCallback = async (context) => {
  26. var { timeRange, executionTime } = context;
  27. console.log('执行任务:', {
  28. 时间区间: timeRange.name,
  29. 开始时间: timeRange.start,
  30. 执行时间: executionTime
  31. });
  32. const today = helper.getLocalDate();
  33. cur_day_data.forEach((v,k)=>{
  34. if(k==today){
  35. }else{
  36. cur_day_data.set(k, {})
  37. }
  38. })
  39. if(!cur_day_data.has(today)){
  40. cur_day_data.set(today,{})
  41. }
  42. if(!cur_day_data.get(today)[timeRange.start]){
  43. cur_day_data.get(today)[timeRange.start] = {name:timeRange.name,interval_minute:timeRange.interval_minute,finish_count:0}
  44. }
  45. console.log("cur_day_data[today]:",cur_day_data.get(today),today)
  46. const existingRecord = await manager.getRecord(today);
  47. if (existingRecord) {
  48. // 如果存在今天的记录,则更新
  49. const result = await manager.updateRecord(today, cur_day_data.get(today));
  50. console.log("更新记录结果:", result);
  51. } else {
  52. // 如果不存在今天的记录,则创建新记录
  53. const result = await manager.createRecord(today, cur_day_data.get(today));
  54. console.log("创建新记录结果:", result);
  55. }
  56. cur_timeRange = timeRange
  57. cur_timeRange.finish_count = 0
  58. cur_page = 0
  59. await processTask();
  60. };
  61. // 启动消费者
  62. async function startConsumer() {
  63. try {
  64. await rabbitMq.consumerDirectMsg(messageHandler,"exchange_update_pull_config","updatePullConig");
  65. } catch (error) {
  66. console.error('启动消费者失败:', error);
  67. }
  68. }
  69. function generate_pull_time_data(list){
  70. sendPullDataMQMessage(JSON.stringify({cmd:"on_recv_pull_data",data:list}))
  71. }
  72. async function processDetailTask(task_item) {
  73. try{
  74. console.log(" start processDetailTask")
  75. let materialId_list = task_item.materialId_list
  76. let materialId_data_list = task_item.materialId_data_list
  77. let response = await pullDataService.get_detail(task_item.id_list)
  78. if(!response.success){
  79. console.log("get_detail:",response)
  80. throw {msg:response,timeRange:cur_timeRange,fun:"get_detail",materialId_list:materialId_list}
  81. }
  82. if(cur_timeRange!=null){
  83. cur_timeRange.finish_count+=materialId_list.length
  84. const today = helper.getLocalDate();
  85. cur_day_data.get(today)[cur_timeRange.start].finish_count = cur_timeRange.finish_count
  86. await manager.updateRecord(today,cur_day_data.get(today));
  87. }
  88. for (let j = 0; j < materialId_list.length; j++) {
  89. const materialId = materialId_list[j];
  90. for (let index = 0; index < response.data.list.length; index++) {
  91. const element = response.data.list[index];
  92. if(element.materialId==materialId){
  93. const info = materialId_data_list[element.materialId]
  94. if(element.hasAnchorInfo){
  95. await origin_data_controllers.createOriginData(
  96. {
  97. video_id:element.awemeId,
  98. materialId:element.materialId,
  99. video_link:element.awemeUrl,
  100. title:CMD.subTitle(element.title),
  101. publish_time:new Date(element.publishTime),
  102. kepp_num:info.kepp_num,
  103. comment_num:info.comment_num,
  104. like_num:info.like_num,
  105. shared_num:info.shared_num,
  106. is_guajian:1,
  107. guajian_link:element.landingUrl,
  108. status:0,
  109. createTime_new:new Date(element.createTime),
  110. updateTime_new:new Date(element.updateTime)
  111. }
  112. )
  113. }
  114. break
  115. }
  116. }
  117. }
  118. generate_pull_time_data(response.data.list)
  119. console.log(" finish processDetailTask")
  120. }catch (error) {
  121. console.error("processDetailTask:",error)
  122. }finally{
  123. // global.setTimeout(processDetailTask,500)
  124. }
  125. }
  126. async function process_material_list(response,page) {
  127. try{
  128. let FilterConfig = await redis_help.getKeyValue("FilterConfig")
  129. FilterConfig = JSON.parse(FilterConfig)
  130. let materialId_list = []
  131. let materialId_data_list = []
  132. if(!response.success){
  133. throw {msg:response,timeRange:cur_timeRange,fun:"get_novel_material_list"}
  134. }
  135. if(response.data == undefined||response.data == null){
  136. throw {msg:response,timeRange:cur_timeRange,fun:"get_novel_material_list"}
  137. }
  138. if(response.data.list == undefined||response.data.list == null){
  139. throw "没有数据了"
  140. }
  141. if(response.data.list.length<=0){
  142. throw "没有数据了"
  143. }
  144. if(cur_timeRange!=null){ //统计
  145. const today = helper.getLocalDate();
  146. // console.log("response.data:",response.data,today)
  147. if(cur_day_data.get(today)[cur_timeRange.start]){
  148. console.log("response.data.count:",response.data.count)
  149. console.log("(cur_day_data[today][timeRange.start]:",cur_day_data.get(today)[cur_timeRange.start])
  150. cur_timeRange.count = cur_timeRange.count + response.data.list.length
  151. cur_timeRange.cur_page = page
  152. cur_day_data.get(today)[cur_timeRange.start].start_time = cur_timeRange.start_time
  153. cur_day_data.get(today)[cur_timeRange.start].pull_day = cur_timeRange.pull_day
  154. cur_day_data.get(today)[cur_timeRange.start].pull_time = cur_timeRange.pull_time ||{}
  155. cur_day_data.get(today)[cur_timeRange.start].count = response.data.count
  156. cur_day_data.get(today)[cur_timeRange.start].cur_page = page
  157. }else{
  158. console.log("cur_day_data空")
  159. }
  160. manager.updateRecord(today,cur_day_data.get(today));
  161. }
  162. for (let index = 0; index < response.data.list.length; index++) {
  163. const origin_element = response.data.list[index];
  164. materialId_list.push(origin_element.materialId)
  165. materialId_data_list[origin_element.materialId] = {
  166. kepp_num:0,
  167. comment_num:0,
  168. like_num:0,
  169. shared_num:0
  170. }
  171. }
  172. let result = await origin_data_controllers.findNonExistentMaterialIds(materialId_list)
  173. return {id_list:materialId_list,materialId_list:result.data.nonExistentIds,materialId_data_list:materialId_data_list,count:response.data.list.length}
  174. }catch(e){
  175. console.log("materialId_list:",e)
  176. return null
  177. }
  178. }
  179. async function processTask(){
  180. try{
  181. let FilterConfig = await redis_help.getKeyValue("FilterConfig")
  182. FilterConfig = JSON.parse(FilterConfig)
  183. let response = await pullDataService.get_novel_material_list(cur_timeRange,cur_page,500)
  184. if(response.success){
  185. if(response.data.list.length<=0){
  186. cur_page = -1;
  187. throw response
  188. }
  189. }else{
  190. cur_page = -1;
  191. throw response
  192. }
  193. let detail_item = await process_material_list(response,cur_page,cur_timeRange)
  194. await processDetailTask(detail_item)
  195. // if(detail_item.materialId_list.length<=0){
  196. // }else{
  197. // await processDetailTask(detail_item)
  198. // }
  199. console.log("processTask over!")
  200. }catch(e){
  201. console.error("PULL_DATA: error:",e)
  202. }finally{
  203. if(cur_page!=-1){
  204. cur_page++;
  205. global.setTimeout(processTask,1000)
  206. }
  207. }
  208. }
  209. CMD.subTitle = function(title){
  210. if(title.length>299){
  211. return title.substring(0, 299);
  212. }
  213. return title
  214. }
  215. CMD.isRight = function(FilterConfig,origin_element){
  216. if(origin_element.likeCount.count < FilterConfig.like_num){// console.log("点赞数正确")
  217. return false
  218. }
  219. if(origin_element.favoriteCount.count < FilterConfig.kepp_num){ // console.log("收藏数正确")
  220. return false
  221. }
  222. if(origin_element.shareCount.count < FilterConfig.shared_num){ // console.log("分享数正确")
  223. return false
  224. }
  225. if(origin_element.commentCount.count < FilterConfig.comment_num){ // console.log("评论")
  226. return false
  227. }
  228. return true
  229. }
  230. CMD.init = async function(){
  231. // await startConsumer();
  232. redis_help.connect(async ()=>{
  233. startConsumer()
  234. let PullDataConfig = await redis_help.getKeyValue("PullDataConfig")
  235. PullDataConfig = JSON.parse(PullDataConfig)
  236. // processTask()
  237. _24HourRanges = PullDataConfig
  238. // 定义任务回调函数
  239. let key = helper.getLocalDate();
  240. let record_res = await manager.getRecord(key);
  241. if(record_res!=null){
  242. if(!cur_day_data.has(key)){
  243. cur_day_data.set(key,record_res.content)
  244. }
  245. }
  246. await pullDataService.getToken()
  247. // 启动调度器
  248. CMD.startScheduler(taskCallback);
  249. })
  250. }
  251. // 生成24小时的时间区间
  252. CMD.generate24HourRanges = function() {
  253. // const ranges = [];
  254. // const today = new Date();
  255. // today.setMinutes(0);
  256. // today.setSeconds(0);
  257. // today.setMilliseconds(0);
  258. // for (let hour = 0; hour < 24; hour++) {
  259. // const timeString = `${hour.toString().padStart(2, '0')}:00`;
  260. // let periodName = '';
  261. // // 设置当天的小时
  262. // today.setHours(hour);
  263. // const timestamp = today.getTime();
  264. // // 根据时间划分时段
  265. // if (hour >= 0 && hour < 6) {
  266. // periodName = '凌晨区间';
  267. // } else if (hour >= 6 && hour < 9) {
  268. // periodName = '早晨区间';
  269. // } else if (hour >= 9 && hour < 12) {
  270. // periodName = '上午区间';
  271. // } else if (hour >= 12 && hour < 14) {
  272. // periodName = '中午区间';
  273. // } else if (hour >= 14 && hour < 18) {
  274. // periodName = '下午区间';
  275. // } else if (hour >= 18 && hour < 22) {
  276. // periodName = '晚上区间';
  277. // } else {
  278. // periodName = '深夜区间';
  279. // }
  280. // ranges.push({
  281. // name: periodName,
  282. // start: timeString,
  283. // timestamp: timestamp,
  284. // hour:hour,
  285. // timeFormat: new Date(timestamp).toLocaleString() // 可读的时间格式
  286. // });
  287. // }
  288. let ranges = [
  289. {
  290. name: '凌晨区间',
  291. start: '00:00',
  292. timestamp: 1733760000000,
  293. hour: 0,
  294. timeFormat: '12/10/2024, 12:00:00 AM'
  295. },
  296. {
  297. name: '凌晨区间',
  298. start: '01:00',
  299. timestamp: 1733763600000,
  300. hour: 1,
  301. timeFormat: '12/10/2024, 1:00:00 AM'
  302. },
  303. {
  304. name: '凌晨区间',
  305. start: '02:00',
  306. timestamp: 1733767200000,
  307. hour: 2,
  308. timeFormat: '12/10/2024, 2:00:00 AM'
  309. },
  310. {
  311. name: '凌晨区间',
  312. start: '03:00',
  313. timestamp: 1733770800000,
  314. hour: 3,
  315. timeFormat: '12/10/2024, 3:00:00 AM'
  316. },
  317. {
  318. name: '凌晨区间',
  319. start: '04:00',
  320. timestamp: 1733774400000,
  321. hour: 4,
  322. timeFormat: '12/10/2024, 4:00:00 AM'
  323. },
  324. {
  325. name: '凌晨区间',
  326. start: '05:00',
  327. timestamp: 1733778000000,
  328. hour: 5,
  329. timeFormat: '12/10/2024, 5:00:00 AM'
  330. },
  331. {
  332. name: '早晨区间',
  333. start: '06:00',
  334. timestamp: 1733781600000,
  335. hour: 6,
  336. timeFormat: '12/10/2024, 6:00:00 AM'
  337. },
  338. {
  339. name: '早晨区间',
  340. start: '07:00',
  341. timestamp: 1733785200000,
  342. hour: 7,
  343. timeFormat: '12/10/2024, 7:00:00 AM'
  344. },
  345. {
  346. name: '早晨区间',
  347. start: '08:00',
  348. timestamp: 1733788800000,
  349. hour: 8,
  350. timeFormat: '12/10/2024, 8:00:00 AM'
  351. },
  352. {
  353. name: '上午区间',
  354. start: '09:00',
  355. timestamp: 1733792400000,
  356. hour: 9,
  357. timeFormat: '12/10/2024, 9:00:00 AM'
  358. },
  359. {
  360. name: '上午区间',
  361. start: '10:00',
  362. timestamp: 1733796000000,
  363. hour: 10,
  364. timeFormat: '12/10/2024, 10:00:00 AM'
  365. },
  366. {
  367. name: '上午区间',
  368. start: '11:00',
  369. timestamp: 1733799600000,
  370. hour: 11,
  371. timeFormat: '12/10/2024, 11:00:00 AM'
  372. },
  373. {
  374. name: '中午区间',
  375. start: '12:00',
  376. timestamp: 1733803200000,
  377. hour: 12,
  378. timeFormat: '12/10/2024, 12:00:00 PM'
  379. },
  380. {
  381. name: '中午区间',
  382. start: '13:00',
  383. timestamp: 1733806800000,
  384. hour: 13,
  385. timeFormat: '12/10/2024, 1:00:00 PM'
  386. },
  387. {
  388. name: '下午区间',
  389. start: '14:00',
  390. timestamp: 1733810400000,
  391. hour: 14,
  392. timeFormat: '12/10/2024, 2:00:00 PM'
  393. },
  394. {
  395. name: '下午区间',
  396. start: '15:00',
  397. timestamp: 1733814000000,
  398. hour: 15,
  399. timeFormat: '12/10/2024, 3:00:00 PM'
  400. },
  401. {
  402. name: '下午区间',
  403. start: '16:00',
  404. timestamp: 1733817600000,
  405. hour: 16,
  406. timeFormat: '12/10/2024, 4:00:00 PM'
  407. },
  408. {
  409. name: '下午区间',
  410. start: '17:00',
  411. timestamp: 1733821200000,
  412. hour: 17,
  413. timeFormat: '12/10/2024, 5:00:00 PM'
  414. },
  415. {
  416. name: '晚上区间',
  417. start: '18:00',
  418. timestamp: 1733824800000,
  419. hour: 18,
  420. timeFormat: '12/10/2024, 6:00:00 PM'
  421. },
  422. {
  423. name: '晚上区间',
  424. start: '19:00',
  425. timestamp: 1733828400000,
  426. hour: 19,
  427. timeFormat: '12/10/2024, 7:00:00 PM'
  428. },
  429. {
  430. name: '晚上区间',
  431. start: '20:45',
  432. timestamp: 1733832000000,
  433. hour: 20,
  434. timeFormat: '12/10/2024, 8:00:00 PM'
  435. },
  436. {
  437. name: '晚上区间',
  438. start: '21:00',
  439. timestamp: 1733835600000,
  440. hour: 21,
  441. timeFormat: '12/10/2024, 9:00:00 PM'
  442. },
  443. {
  444. name: '深夜区间',
  445. start: '22:00',
  446. timestamp: 1733839200000,
  447. hour: 22,
  448. timeFormat: '12/10/2024, 10:00:00 PM'
  449. },
  450. {
  451. name: '深夜区间',
  452. start: '23:00',
  453. timestamp: 1733842800000,
  454. hour: 23,
  455. timeFormat: '12/10/2024, 11:00:00 PM'
  456. }
  457. ]
  458. return ranges;
  459. }
  460. CMD.stopScheduler = function() {
  461. jobs.forEach(({ job }) => job.cancel());
  462. jobs = [];
  463. console.log('调度器已停止,所有任务已清除');
  464. }
  465. CMD.startScheduler = function(taskCallback) {
  466. CMD.stopScheduler()
  467. // 为每个时间点创建定时任务
  468. _24HourRanges.forEach(timeRange => {
  469. // 解析小时
  470. const hour = parseInt(timeRange.start.split(':')[0]);
  471. const minute = parseInt(timeRange.start.split(':')[1]);
  472. // 创建定时任务 - 在每天的指定小时整点执行
  473. const job = schedule.scheduleJob(`${minute} ${hour} * * *`, async () => {
  474. try {
  475. console.log(`开始执行任务: ${timeRange.name} ${timeRange.start}`);
  476. await pullDataService.getToken()
  477. // 执行回调函数
  478. await taskCallback({
  479. timeRange,
  480. executionTime: new Date()
  481. });
  482. } catch (error) {
  483. // 记录失败
  484. console.error('任务执行错误:', error);
  485. }
  486. });
  487. jobs.push({
  488. job,
  489. timeRange
  490. });
  491. console.log(`已安排任务: ${timeRange.name} ${timeRange.start}`);
  492. });
  493. console.log(`调度器已启动,共设置 ${jobs.length} 个定时任务`);
  494. }
  495. async function sendPullDataMQMessage(message,routingKey = "on_recv_pull_data") {
  496. try {
  497. if(routingKey!=null){
  498. await rabbitMq.producerDirectMsg( message,"exchange_pull_data_system",routingKey);
  499. }else{
  500. await rabbitMq.producerDirectMsg( message,"exchange_pull_data_system");
  501. }
  502. console.log('消息发送成功');
  503. } catch (error) {
  504. console.error('发送消息失败:', error);
  505. }
  506. }
  507. if(!config.isDebug){
  508. CMD.init()
  509. }