tools.js 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404
  1. const crypto = require('crypto');
  2. const config = require('./etc/config.json');
  3. const { default: axios } = require('axios');
  4. const http = require('http');
  5. const moment = require('moment');
  6. const mysql = require('mysql2/promise');
  7. const JSONbig = require('json-bigint')
  8. const { HttpsProxyAgent } = require('https-proxy-agent');
  9. class tools {
  10. constructor(redis_help){
  11. this.redis_help = redis_help
  12. }
  13. init(){
  14. }
  15. distributorId = 1814786227164169;
  16. secretKey = 'CN6KQ8Bauo8JXg5fFPk86EHdRFIUVnyV';
  17. heiyan_config(){
  18. return { //黑岩配置
  19. chang_pian_user:{
  20. userName:"康帅",
  21. password:"Ks25666"
  22. },
  23. duan_pian_user:{
  24. userName:"王海泉",
  25. password:"My20240088"
  26. },
  27. default_user:{
  28. userName:"zhuoyue003",
  29. password:"Xuan2026@123"
  30. },
  31. }
  32. }
  33. unixTimestampToDate = function(timestamp) {
  34. const date = new Date(timestamp * 1000); // Unix时间戳是秒,JavaScript的Date对象需要毫秒
  35. return date.getTime();
  36. }
  37. dateToUnixTimestamp = function (date) {
  38. return Math.floor(date.getTime() / 1000); // 将毫秒转换为秒
  39. }
  40. calculateTimestampDifference = function(timestamp1, timestamp2) {
  41. return Math.abs(timestamp1 - timestamp2);
  42. }
  43. formatUnixTimestamp = function(timestamp, format = 'YYYY-MM-DD HH:mm:ss') {
  44. const date = new Date(timestamp * 1000);
  45. const year = date.getFullYear();
  46. const month = String(date.getMonth() + 1).padStart(2, '0'); // 月份从0开始,需要+1
  47. const day = String(date.getDate()).padStart(2, '0');
  48. const hours = String(date.getHours()).padStart(2, '0');
  49. const minutes = String(date.getMinutes()).padStart(2, '0');
  50. const seconds = String(date.getSeconds()).padStart(2, '0');
  51. const formattedDate = format
  52. .replace('YYYY', year)
  53. .replace('MM', month)
  54. .replace('DD', day)
  55. .replace('HH', hours)
  56. .replace('mm', minutes)
  57. .replace('ss', seconds);
  58. return formattedDate;
  59. }
  60. getCurrentUnixTimestamp = function() {
  61. return Math.floor(Date.now() / 1000)
  62. }
  63. getCurrentUnixTimestamp = function() {
  64. return Math.floor(Date.now() / 1000)
  65. }
  66. generateCryptoNumericUUID= function(length = 10) {
  67. return crypto.randomInt(Math.pow(10, length - 1), Math.pow(10, length)).toString();
  68. }
  69. generateQMSignature = function(url, secretKey) {
  70. const urlObj = new URL(url);
  71. const params = Array.from(urlObj.searchParams.entries())
  72. .sort(([keyA], [keyB]) => keyA.localeCompare(keyB))
  73. .map(([key, value]) => `${key}=${value}`)
  74. .join('&');
  75. // 拼接secret key
  76. const stringToSign = params + secretKey;
  77. console.log("stringToSign:",stringToSign)
  78. // 计算MD5
  79. const md5Hash = crypto.createHash('md5')
  80. .update(stringToSign)
  81. .digest('hex');
  82. return md5Hash;
  83. }
  84. getSign = function(distributorId,secretKey) {
  85. const params = [distributorId, secretKey, tools.getCurrentUnixTimestamp()];
  86. // 将参数数组中的每个元素转换为字符串并连接成一个单一的字符串
  87. const paramStr = params.map(String).join('');
  88. // 使用 MD5 算法生成哈希值
  89. const hash = crypto.createHash('md5');
  90. hash.update(paramStr);
  91. // 返回哈希值的十六进制表示
  92. return hash.digest('hex');
  93. }
  94. setHyToken(token){
  95. this.redis_help.setKeyValue("hei_yan_token",token)
  96. }
  97. async getHyToken (){
  98. return await this.redis_help.getKeyValue("hei_yan_token")
  99. }
  100. async getQMToken (){
  101. return await this.redis_help.getKeyValue("qi_mao_token")
  102. }
  103. async getQMMFToken (){
  104. return await this.redis_help.getKeyValue("qi_mao_mf_token")
  105. }
  106. getSupdate(){ //插入素材域名
  107. return config.isDebug?config.debug_supdate_config:config.release_supdate_config
  108. }
  109. getCheckDataBaseConfig(){
  110. return config.isDebug?config.debug_check_mysql:config.release_chekc_mysql
  111. }
  112. getDataBaseConfig(){
  113. return config.isDebug?config.debug_mysql:config.release_mysql
  114. }
  115. getTaskDataBaseConfig(){
  116. return config.isDebug?config.debug_task_mysql:config.release_task_mysql
  117. }
  118. getRandomElement(array) {
  119. const randomIndex = Math.floor(Math.random() * array.length);
  120. return array[randomIndex];
  121. }
  122. async getFqSidtt() {
  123. let sidtt = '01e060d0cc506bf1340dcb004aea1161'
  124. let list = await this.redis_help.getKeyValue("all_fq_key")
  125. if(list == null){
  126. return sidtt
  127. }
  128. list = JSON.parse(list)
  129. if(list.length<=0){
  130. return sidtt
  131. }
  132. let temp = []
  133. for (let index = 0; index < list.length; index++) {
  134. const sidtt = list[index];
  135. if(sidtt.canUse==1){
  136. temp.push(sidtt.sid_tt)
  137. }
  138. }
  139. return this.getRandomElement(temp)
  140. }
  141. async getFqMfSidtt() {
  142. let sidtt = '01e060d0cc506bf1340dcb004aea1161'
  143. let list = await this.redis_help.getKeyValue("all_fq_mf_key")
  144. if(list == null){
  145. return sidtt
  146. }
  147. list = JSON.parse(list)
  148. if(list.length<=0){
  149. return sidtt
  150. }
  151. let temp = []
  152. for (let index = 0; index < list.length; index++) {
  153. const sidtt = list[index];
  154. if(sidtt.canUse==1){
  155. temp.push(sidtt.sid_tt)
  156. }
  157. }
  158. return this.getRandomElement(temp)
  159. }
  160. async getYwOPENSESSID() {
  161. let open_sessid = '9077ffcc5ca974e2c0e78502a24c9053'
  162. let list = await this.redis_help.getKeyValue("all_yw_key")
  163. if(list == null){
  164. return open_sessid
  165. }
  166. list = JSON.parse(list)
  167. if(list.length<=0){
  168. return open_sessid
  169. }
  170. for (let index = 0; index < list.length; index++) {
  171. const yw_data = list[index];
  172. const old_time = yw_data.create_time;
  173. const current_time = moment();
  174. const past_time = moment(old_time);
  175. // 计算时间差(小时)
  176. const diff_hours = current_time.diff(past_time, 'hours');
  177. // 判断是否小于7小时
  178. const isLessThan7Hours = diff_hours < 7;
  179. if(isLessThan7Hours){
  180. this.redis_help.setKeyValue("OPENSESSID",yw_data.open_sessid)
  181. }else{
  182. this.redis_help.setKeyValue("OPENSESSID","")
  183. }
  184. return open_sessid
  185. }
  186. }
  187. getOneNewClinetBuffer(headers=null){
  188. return axios.create({
  189. timeout: 30000,
  190. headers:headers||{},
  191. responseType:"arraybuffer",
  192. // 使用独立的 agent,不影响其他连接
  193. httpAgent: new http.Agent({
  194. keepAlive: true,
  195. maxSockets: 5, // 允许适度的并发
  196. maxFreeSockets: 2,
  197. timeout: 30000
  198. }),
  199. validateStatus: function (status) {
  200. return status >= 200 && status < 300;
  201. }
  202. });
  203. }
  204. getOneProxyNewClinet(headers=null){
  205. let proxyConfig = {
  206. host: 'd528.kdltps.com',
  207. port: '15818',
  208. username: 't13322192973984',
  209. password: '7ntreedr'
  210. };
  211. let proxyAgent = new HttpsProxyAgent(`http://${proxyConfig.username}:${proxyConfig.password}@${proxyConfig.host}:${proxyConfig.port}`);
  212. return axios.create({
  213. timeout: 30000,
  214. headers:headers||{},
  215. // 使用独立的 agent,不影响其他连接
  216. httpAgent: proxyAgent,
  217. validateStatus: function (status) {
  218. return status >= 200 && status < 300;
  219. },
  220. transformResponse: [data => {
  221. try {
  222. // 将大数字存储为字符串
  223. return JSONbig({ storeAsString: true }).parse(data);
  224. // 或者使用 BigInt 类型(需要环境支持)
  225. // return JSONbig({ useNativeBigInt: true }).parse(data);
  226. } catch (e) {
  227. console.error('JSON 解析错误:', e);
  228. return data;
  229. }
  230. }]
  231. });
  232. }
  233. getOneNewClinet(headers=null){
  234. return axios.create({
  235. timeout: 30000,
  236. headers:headers||{},
  237. // 使用独立的 agent,不影响其他连接
  238. httpAgent: new http.Agent({
  239. keepAlive: true,
  240. maxSockets: 5, // 允许适度的并发
  241. maxFreeSockets: 2,
  242. timeout: 30000
  243. }),
  244. validateStatus: function (status) {
  245. return status >= 200 && status < 300;
  246. },
  247. transformResponse: [data => {
  248. try {
  249. // 将大数字存储为字符串
  250. return JSONbig({ storeAsString: true }).parse(data);
  251. // 或者使用 BigInt 类型(需要环境支持)
  252. // return JSONbig({ useNativeBigInt: true }).parse(data);
  253. } catch (e) {
  254. console.error('JSON 解析错误:', e);
  255. return data;
  256. }
  257. }]
  258. });
  259. }
  260. async getAppletProductDataByButlerId(butler_id,product_id,main_id){
  261. const taskdbConfig = config.isDebug?config.debug_task_mysql:config.release_task_mysql
  262. let connection = null
  263. try{
  264. connection = await mysql.createConnection({
  265. ...taskdbConfig,
  266. multipleStatements: true
  267. });
  268. const [rows] = await connection.execute(
  269. `SELECT * FROM video_applet_product_${butler_id} WHERE product_id = '${product_id}' AND main_id = ${main_id} LIMIT 1`
  270. );
  271. if(rows.length<=0){
  272. return null
  273. }
  274. return rows[0]
  275. }catch(e){
  276. console.error(e)
  277. return null
  278. }finally{
  279. if(connection!=null){
  280. await connection.end();
  281. }
  282. }
  283. }
  284. async setDzCookie(cookit){
  285. return this.redis_help.setKeyValue("DZ_COOKIT",cookit)
  286. }
  287. async getDzCookit(){
  288. return this.redis_help.getKeyValue("DZ_COOKIT")
  289. }
  290. zh_sign(body, app_secret) {
  291. // 1. 处理输入参数
  292. let requestBody = body;
  293. if (typeof body === 'string') {
  294. try {
  295. requestBody = JSON.parse(body);
  296. } catch (e) {
  297. throw new Error('Invalid JSON string');
  298. }
  299. }
  300. // 2. 获取所有参数名并排序
  301. const keys = Object.keys(requestBody).sort();
  302. // 3. 拼接键值对
  303. let s1 = '';
  304. keys.forEach(key => {
  305. // 处理值:如果是对象/数组则转为JSON字符串,否则直接使用
  306. const value = typeof requestBody[key] === 'object'
  307. ? JSON.stringify(requestBody[key])
  308. : String(requestBody[key]);
  309. s1 += key + value;
  310. });
  311. // 4. 追加app_secret
  312. const x1 = s1 + app_secret;
  313. console.log('拼接后的字符串 x1:', x1); // 调试用
  314. // 5. HmacSha256 签名
  315. const hmac = crypto.createHmac('sha256', app_secret);
  316. hmac.update(x1);
  317. const b1 = hmac.digest();
  318. // 6. Base64 编码
  319. const s2 = b1.toString('base64');
  320. // 7. 转为大写
  321. const signature = s2.toUpperCase();
  322. return signature;
  323. }
  324. isObject(value) {
  325. return typeof value === 'object' && value !== null;
  326. }
  327. getOriginVideoId(url){
  328. const match = url.match(/\/video\/(\d+)/);
  329. // 2. 提取结果
  330. const videoId = match ? match[1] : null;
  331. return videoId
  332. }
  333. getPreviousDay(dateString) {
  334. // 将传入的字符串转换为 Date 对象
  335. const date = new Date(dateString);
  336. // 获取前一天的日期
  337. const previousDay = new Date(date);
  338. previousDay.setDate(date.getDate() - 1);
  339. // 格式化为 YYYY-MM-DD 字符串
  340. const year = previousDay.getFullYear();
  341. const month = String(previousDay.getMonth() + 1).padStart(2, '0');
  342. const day = String(previousDay.getDate()).padStart(2, '0');
  343. return `${year}-${month}-${day}`;
  344. }
  345. }
  346. module.exports = new tools(require('./src/use_redis'));