PULL_DATA.js 20 KB

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