PULL_DATA.js 16 KB

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