PULL_DATA.js 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589
  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. }
  143. )
  144. }
  145. break
  146. }
  147. }
  148. }
  149. generate_pull_time_data(response.data.list,task_item.list)
  150. console.log(" finish processDetailTask")
  151. }catch (error) {
  152. console.error("processDetailTask:",error)
  153. }finally{
  154. // global.setTimeout(processDetailTask,500)
  155. }
  156. }
  157. async function process_material_list(response,page) {
  158. try{
  159. let FilterConfig = await redis_help.getKeyValue("FilterConfig")
  160. FilterConfig = JSON.parse(FilterConfig)
  161. let materialId_list = []
  162. let materialId_data_list = []
  163. if(!response.success){
  164. throw {msg:response,timeRange:cur_timeRange,fun:"get_novel_material_list"}
  165. }
  166. if(response.data == undefined||response.data == null){
  167. throw {msg:response,timeRange:cur_timeRange,fun:"get_novel_material_list"}
  168. }
  169. if(response.data.list == undefined||response.data.list == null){
  170. throw "没有数据了"
  171. }
  172. if(response.data.list.length<=0){
  173. throw "没有数据了"
  174. }
  175. if(cur_timeRange!=null){ //统计
  176. const today = cur_timeRange.today;
  177. // console.log("response.data:",response.data,today)
  178. if(cur_day_data.get(today)[cur_timeRange.start]){
  179. console.log("response.data.count:",response.data.count)
  180. console.log("(cur_day_data[today][timeRange.start]:",cur_day_data.get(today)[cur_timeRange.start])
  181. cur_timeRange.count = cur_timeRange.count + response.data.list.length
  182. cur_timeRange.cur_page = page
  183. cur_day_data.get(today)[cur_timeRange.start].start_time = cur_timeRange.start_time
  184. cur_day_data.get(today)[cur_timeRange.start].pull_day = cur_timeRange.pull_day
  185. cur_day_data.get(today)[cur_timeRange.start].pull_time = cur_timeRange.pull_time ||{}
  186. cur_day_data.get(today)[cur_timeRange.start].count = response.data.count
  187. cur_day_data.get(today)[cur_timeRange.start].cur_page = page
  188. }else{
  189. console.log("cur_day_data空")
  190. }
  191. manager.updateRecord(today,cur_day_data.get(today));
  192. }
  193. for (let index = 0; index < response.data.list.length; index++) {
  194. const origin_element = response.data.list[index];
  195. materialId_list.push(origin_element.materialId)
  196. materialId_data_list[origin_element.materialId] = {
  197. kepp_num:origin_element.favoriteCount.count,
  198. comment_num:origin_element.commentCount.count,
  199. like_num:origin_element.likeCount.count,
  200. shared_num:origin_element.shareCount.count
  201. }
  202. }
  203. let result = await origin_data_controllers.findNonExistentMaterialIds(materialId_list)
  204. 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}
  205. }catch(e){
  206. console.log("materialId_list:",e)
  207. return null
  208. }
  209. }
  210. async function processTask(){
  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,cur_page,500)
  215. if(response.success){
  216. if(response.data.list.length<=0){
  217. cur_page = -1;
  218. throw response
  219. }
  220. }else{
  221. cur_page = -1;
  222. throw response
  223. }
  224. let detail_item = await process_material_list(response,cur_page,cur_timeRange)
  225. await processDetailTask(detail_item)
  226. // if(detail_item.materialId_list.length<=0){
  227. // }else{
  228. // await processDetailTask(detail_item)
  229. // }
  230. console.log("processTask over!")
  231. }catch(e){
  232. console.error("PULL_DATA: error:",e)
  233. }finally{
  234. if(cur_page!=-1){
  235. cur_page++;
  236. global.setTimeout(processTask,1000)
  237. }
  238. }
  239. }
  240. CMD.subTitle = function(title){
  241. if(title.length>299){
  242. return title.substring(0, 299);
  243. }
  244. return title
  245. }
  246. CMD.isRight = function(FilterConfig,origin_element){
  247. if(origin_element.likeCount.count < FilterConfig.like_num){// console.log("点赞数正确")
  248. return false
  249. }
  250. if(origin_element.favoriteCount.count < FilterConfig.kepp_num){ // console.log("收藏数正确")
  251. return false
  252. }
  253. if(origin_element.shareCount.count < FilterConfig.shared_num){ // console.log("分享数正确")
  254. return false
  255. }
  256. if(origin_element.commentCount.count < FilterConfig.comment_num){ // console.log("评论")
  257. return false
  258. }
  259. return true
  260. }
  261. CMD.init = async function(){
  262. // await startConsumer();
  263. redis_help.connect(async ()=>{
  264. startConsumer()
  265. let PullDataConfig = await redis_help.getKeyValue("PullDataConfig")
  266. PullDataConfig = JSON.parse(PullDataConfig)
  267. // processTask()
  268. _24HourRanges = PullDataConfig
  269. // 定义任务回调函数
  270. let key = helper.getLocalDate();
  271. let record_res = await manager.getRecord(key);
  272. if(record_res!=null){
  273. if(!cur_day_data.has(key)){
  274. cur_day_data.set(key,record_res.content)
  275. }
  276. }
  277. await pullDataService.getToken()
  278. // 启动调度器
  279. CMD.startScheduler(taskCallback);
  280. })
  281. }
  282. // 生成24小时的时间区间
  283. CMD.generate24HourRanges = function() {
  284. // const ranges = [];
  285. // const today = new Date();
  286. // today.setMinutes(0);
  287. // today.setSeconds(0);
  288. // today.setMilliseconds(0);
  289. // for (let hour = 0; hour < 24; hour++) {
  290. // const timeString = `${hour.toString().padStart(2, '0')}:00`;
  291. // let periodName = '';
  292. // // 设置当天的小时
  293. // today.setHours(hour);
  294. // const timestamp = today.getTime();
  295. // // 根据时间划分时段
  296. // if (hour >= 0 && hour < 6) {
  297. // periodName = '凌晨区间';
  298. // } else if (hour >= 6 && hour < 9) {
  299. // periodName = '早晨区间';
  300. // } else if (hour >= 9 && hour < 12) {
  301. // periodName = '上午区间';
  302. // } else if (hour >= 12 && hour < 14) {
  303. // periodName = '中午区间';
  304. // } else if (hour >= 14 && hour < 18) {
  305. // periodName = '下午区间';
  306. // } else if (hour >= 18 && hour < 22) {
  307. // periodName = '晚上区间';
  308. // } else {
  309. // periodName = '深夜区间';
  310. // }
  311. // ranges.push({
  312. // name: periodName,
  313. // start: timeString,
  314. // timestamp: timestamp,
  315. // hour:hour,
  316. // timeFormat: new Date(timestamp).toLocaleString() // 可读的时间格式
  317. // });
  318. // }
  319. let ranges = [
  320. {
  321. name: '凌晨区间',
  322. start: '00:00',
  323. timestamp: 1733760000000,
  324. hour: 0,
  325. timeFormat: '12/10/2024, 12:00:00 AM'
  326. },
  327. {
  328. name: '凌晨区间',
  329. start: '01:00',
  330. timestamp: 1733763600000,
  331. hour: 1,
  332. timeFormat: '12/10/2024, 1:00:00 AM'
  333. },
  334. {
  335. name: '凌晨区间',
  336. start: '02:00',
  337. timestamp: 1733767200000,
  338. hour: 2,
  339. timeFormat: '12/10/2024, 2:00:00 AM'
  340. },
  341. {
  342. name: '凌晨区间',
  343. start: '03:00',
  344. timestamp: 1733770800000,
  345. hour: 3,
  346. timeFormat: '12/10/2024, 3:00:00 AM'
  347. },
  348. {
  349. name: '凌晨区间',
  350. start: '04:00',
  351. timestamp: 1733774400000,
  352. hour: 4,
  353. timeFormat: '12/10/2024, 4:00:00 AM'
  354. },
  355. {
  356. name: '凌晨区间',
  357. start: '05:00',
  358. timestamp: 1733778000000,
  359. hour: 5,
  360. timeFormat: '12/10/2024, 5:00:00 AM'
  361. },
  362. {
  363. name: '早晨区间',
  364. start: '06:00',
  365. timestamp: 1733781600000,
  366. hour: 6,
  367. timeFormat: '12/10/2024, 6:00:00 AM'
  368. },
  369. {
  370. name: '早晨区间',
  371. start: '07:00',
  372. timestamp: 1733785200000,
  373. hour: 7,
  374. timeFormat: '12/10/2024, 7:00:00 AM'
  375. },
  376. {
  377. name: '早晨区间',
  378. start: '08:00',
  379. timestamp: 1733788800000,
  380. hour: 8,
  381. timeFormat: '12/10/2024, 8:00:00 AM'
  382. },
  383. {
  384. name: '上午区间',
  385. start: '09:00',
  386. timestamp: 1733792400000,
  387. hour: 9,
  388. timeFormat: '12/10/2024, 9:00:00 AM'
  389. },
  390. {
  391. name: '上午区间',
  392. start: '10:00',
  393. timestamp: 1733796000000,
  394. hour: 10,
  395. timeFormat: '12/10/2024, 10:00:00 AM'
  396. },
  397. {
  398. name: '上午区间',
  399. start: '11:00',
  400. timestamp: 1733799600000,
  401. hour: 11,
  402. timeFormat: '12/10/2024, 11:00:00 AM'
  403. },
  404. {
  405. name: '中午区间',
  406. start: '12:00',
  407. timestamp: 1733803200000,
  408. hour: 12,
  409. timeFormat: '12/10/2024, 12:00:00 PM'
  410. },
  411. {
  412. name: '中午区间',
  413. start: '13:00',
  414. timestamp: 1733806800000,
  415. hour: 13,
  416. timeFormat: '12/10/2024, 1:00:00 PM'
  417. },
  418. {
  419. name: '下午区间',
  420. start: '14:00',
  421. timestamp: 1733810400000,
  422. hour: 14,
  423. timeFormat: '12/10/2024, 2:00:00 PM'
  424. },
  425. {
  426. name: '下午区间',
  427. start: '15:00',
  428. timestamp: 1733814000000,
  429. hour: 15,
  430. timeFormat: '12/10/2024, 3:00:00 PM'
  431. },
  432. {
  433. name: '下午区间',
  434. start: '16:00',
  435. timestamp: 1733817600000,
  436. hour: 16,
  437. timeFormat: '12/10/2024, 4:00:00 PM'
  438. },
  439. {
  440. name: '下午区间',
  441. start: '17:00',
  442. timestamp: 1733821200000,
  443. hour: 17,
  444. timeFormat: '12/10/2024, 5:00:00 PM'
  445. },
  446. {
  447. name: '晚上区间',
  448. start: '18:00',
  449. timestamp: 1733824800000,
  450. hour: 18,
  451. timeFormat: '12/10/2024, 6:00:00 PM'
  452. },
  453. {
  454. name: '晚上区间',
  455. start: '19:00',
  456. timestamp: 1733828400000,
  457. hour: 19,
  458. timeFormat: '12/10/2024, 7:00:00 PM'
  459. },
  460. {
  461. name: '晚上区间',
  462. start: '20:45',
  463. timestamp: 1733832000000,
  464. hour: 20,
  465. timeFormat: '12/10/2024, 8:00:00 PM'
  466. },
  467. {
  468. name: '晚上区间',
  469. start: '21:00',
  470. timestamp: 1733835600000,
  471. hour: 21,
  472. timeFormat: '12/10/2024, 9:00:00 PM'
  473. },
  474. {
  475. name: '深夜区间',
  476. start: '22:00',
  477. timestamp: 1733839200000,
  478. hour: 22,
  479. timeFormat: '12/10/2024, 10:00:00 PM'
  480. },
  481. {
  482. name: '深夜区间',
  483. start: '23:00',
  484. timestamp: 1733842800000,
  485. hour: 23,
  486. timeFormat: '12/10/2024, 11:00:00 PM'
  487. }
  488. ]
  489. return ranges;
  490. }
  491. CMD.stopScheduler = function() {
  492. jobs.forEach(({ job }) => job.cancel());
  493. jobs = [];
  494. console.log('调度器已停止,所有任务已清除');
  495. }
  496. CMD.startScheduler = function(taskCallback) {
  497. CMD.stopScheduler()
  498. // 为每个时间点创建定时任务
  499. _24HourRanges.forEach(timeRange => {
  500. // 解析小时
  501. const hour = parseInt(timeRange.start.split(':')[0]);
  502. const minute = parseInt(timeRange.start.split(':')[1]);
  503. // 创建定时任务 - 在每天的指定小时整点执行
  504. const job = schedule.scheduleJob(`${minute} ${hour} * * *`, async () => {
  505. try {
  506. console.log(`开始执行任务: ${timeRange.name} ${timeRange.start}`);
  507. await pullDataService.getToken()
  508. // 执行回调函数
  509. await taskCallback({
  510. timeRange,
  511. executionTime: new Date()
  512. });
  513. } catch (error) {
  514. // 记录失败
  515. console.error('任务执行错误:', error);
  516. }
  517. });
  518. jobs.push({
  519. job,
  520. timeRange
  521. });
  522. console.log(`已安排任务: ${timeRange.name} ${timeRange.start}`);
  523. });
  524. console.log(`调度器已启动,共设置 ${jobs.length} 个定时任务`);
  525. }
  526. async function sendPullDataMQMessage(message,routingKey = "on_recv_pull_data") {
  527. try {
  528. if(routingKey!=null){
  529. await rabbitMq.producerDirectMsg( message,"exchange_pull_data_system",routingKey);
  530. }else{
  531. await rabbitMq.producerDirectMsg( message,"exchange_pull_data_system");
  532. }
  533. console.log('消息发送成功');
  534. } catch (error) {
  535. console.error('发送消息失败:', error);
  536. }
  537. }
  538. if(!config.isDebug){
  539. CMD.init()
  540. }