PULL_DATA.js 17 KB

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