tools.js 13 KB

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