PULL_DATA.js 18 KB

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