PULL_DATA.js 19 KB

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