File size: 3,387 Bytes
cb3fcd8
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
import axios from 'axios';
import fetch from 'node-fetch';
import iconv from 'iconv-lite';
import fs from 'fs-extra';
import { wrapper } from 'axios-cookiejar-support';
import { CookieJar, Cookie } from 'tough-cookie';
import {SocksProxyAgent} from 'socks-proxy-agent';
const proxyAgent = new SocksProxyAgent(`socks5://127.0.0.1:9909`);

export const jar = fs.existsSync("./cookies.json")
  ? CookieJar.fromJSON(JSON.parse(fs.readFileSync("./cookies.json").toString()))
  : new CookieJar();
jar.rejectPublicSuffixes = false;
jar.looseMode = true;
jar.prefixSecurity ='unsafe-disabled';
jar.allowSpecialUseDomain = true;

const client = wrapper(axios.create({ jar }));

export function reset_cookie_jar() {
  jar.removeAllCookiesSync();
}

client.interceptors.request.use(function (config) {
  if (config.method === 'get') {
    console.log('Get ', config.url);
  } else if (config.method === 'post') {
    console.log('Post ', config.url, config.data);
  }
  config.headers['User-Agent']='Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/123.0.0.0 Safari/537.36';
  config.maxRedirects = 5;

  return config;
}, function (error) {
  return Promise.reject(error);
});

export function gb2312UrlEncode(str) {
  const encoded = iconv.encode(str, 'GB2312');
  let result = '';
  for (let i = 0; i < encoded.length; i++) {
    result += `%${encoded[i].toString(16)}`;
  }
  return result.toUpperCase();

}

export function chineseToUnicode(str, toUpper = false) {
  let result = "";
  for (let i = 0; i < str.length; i++) {
    let charCode = str.charCodeAt(i).toString(16).padStart(4, '0');
    result += "%u" + (toUpper ? charCode.toUpperCase() : charCode);
  }
  return result;
} 

export function unicodeToChinese(str) {
  return unescape(str);
} 


export const get = async (url, from_gb2312 = false) => {
  const res = await axios.get(url, {
    httpAgent: proxyAgent,
    httpsAgent: proxyAgent,
  });
  return res;
}

export const post = async (url, data) => {
  const res = await axios.post(url, data, {
    httpAgent: proxyAgent,
    httpsAgent: proxyAgent,
  }).catch((e) => {
    debugger;
  });
  return res;
};

export const downloadFile = async (url, filePath, maxRetries) => {
  let t = 0;
  while (t < maxRetries) {
    try {
      const res = await axios({
        httpAgent: proxyAgent,
        httpsAgent: proxyAgent,
        method: "get",
        url: url,
        responseType: "arraybuffer",
      });
      if (!res.data.length) {
        throw Error("0byte");
      }
      if (res.status !== 200) {
        throw Error("error status");
      }
      if (res.data.toString().indexOf('The system is busy. Please retry later') != -1) {
        throw Error("busy");
      }
      fs.writeFileSync(filePath, res.data);
      return;
    } catch (e) {
      console.error("Error downloading file:", e, url);
      if (fs.existsSync(filePath)) fs.unlinkSync(filePath);
    }
    ++t;
    console.log('retry', t);
    await sleep(3000);
  }
  throw new Error('max retries exceeded');
};

export function parseCookies(cookie_raw) {
  return cookie_raw.split(";").reduce((m, i) => {
    i = i.trim();
    const idx = i.indexOf("=");
    const name = i.substr(0, idx);
    const value = i.substr(idx + 1);
    m[name] = value;
    return m;
  }, {});
}

export const sleep = (t) => new Promise((resolve) => setTimeout(resolve, t));