tools.js 10 KB

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