PULL_DATA.js 20 KB

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