twitter.js 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450
  1. "use strict";
  2. var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
  3. function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
  4. return new (P || (P = Promise))(function (resolve, reject) {
  5. function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
  6. function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
  7. function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
  8. step((generator = generator.apply(thisArg, _arguments || [])).next());
  9. });
  10. };
  11. Object.defineProperty(exports, "__esModule", { value: true });
  12. exports.sendPost = exports.getPostOwner = exports.WebshotHelpers = exports.ScreenNameNormalizer = exports.SessionManager = exports.urlSegmentToId = exports.idToUrlSegment = exports.isValidUrlSegment = exports.parseLink = exports.linkBuilder = void 0;
  13. const crypto = require("crypto");
  14. const fs = require("fs");
  15. const http = require("http");
  16. const path = require("path");
  17. const url_1 = require("url");
  18. const util_1 = require("util");
  19. const instagram_id_to_url_segment_1 = require("instagram-id-to-url-segment");
  20. Object.defineProperty(exports, "idToUrlSegment", { enumerable: true, get: function () { return instagram_id_to_url_segment_1.instagramIdToUrlSegment; } });
  21. Object.defineProperty(exports, "urlSegmentToId", { enumerable: true, get: function () { return instagram_id_to_url_segment_1.urlSegmentToInstagramId; } });
  22. const instagram_private_api_1 = require("instagram-private-api");
  23. const socks_proxy_agent_1 = require("socks-proxy-agent");
  24. const loggers_1 = require("./loggers");
  25. const koishi_1 = require("./koishi");
  26. const utils_1 = require("./utils");
  27. const webshot_1 = require("./webshot");
  28. const parseLink = (link) => {
  29. let match = /instagram\.com\/p\/([A-Za-z0-9\-_]+)/.exec(link);
  30. if (match)
  31. return { postUrlSegment: match[1] };
  32. match =
  33. /instagram\.com\/([^\/?#]+)/.exec(link) ||
  34. /^([^\/?#]+)$/.exec(link);
  35. if (match)
  36. return { userName: ScreenNameNormalizer.normalize(match[1]).split(':')[0] };
  37. return;
  38. };
  39. exports.parseLink = parseLink;
  40. const isValidUrlSegment = (input) => /^[A-Za-z0-9\-_]+$/.test(input);
  41. exports.isValidUrlSegment = isValidUrlSegment;
  42. const linkBuilder = (config) => {
  43. if (config.userName)
  44. return `https://www.instagram.com/${config.userName}/`;
  45. if (config.postUrlSegment)
  46. return `https://www.instagram.com/p/${config.postUrlSegment}/`;
  47. };
  48. exports.linkBuilder = linkBuilder;
  49. class SessionManager {
  50. constructor(client, file, credentials, codeServicePort) {
  51. this.init = () => {
  52. this.ig.state.generateDevice(this.username);
  53. this.ig.request.end$.subscribe(() => { this.save(); });
  54. const filePath = path.resolve(this.lockfile);
  55. if (fs.existsSync(filePath)) {
  56. try {
  57. const serialized = JSON.parse(fs.readFileSync(filePath, 'utf8'));
  58. return this.ig.state.deserialize(serialized).then(() => {
  59. logger.info(`successfully loaded client session cookies for user ${this.username}`);
  60. });
  61. }
  62. catch (err) {
  63. logger.error(`failed to load client session cookies from file ${this.lockfile}: `, err);
  64. return Promise.resolve();
  65. }
  66. }
  67. else {
  68. return this.login().catch((err) => {
  69. logger.error(`error while trying to log in as user ${this.username}, error: ${err}`);
  70. logger.warn('attempting to retry after 1 minute...');
  71. if (fs.existsSync(filePath))
  72. fs.unlinkSync(filePath);
  73. util_1.promisify(setTimeout)(60000).then(this.init);
  74. });
  75. }
  76. };
  77. this.handle2FA = (submitter) => new Promise((resolve, reject) => {
  78. const token = crypto.randomBytes(20).toString('hex');
  79. logger.info('please submit the code with a one-time token from your browser with this path:');
  80. logger.info(`/confirm-2fa?code=<the code you received>&token=${token}`);
  81. let working;
  82. const server = http.createServer((req, res) => {
  83. const { pathname, query } = url_1.parse(req.url, true);
  84. if (!working && pathname === '/confirm-2fa' && query.token === token &&
  85. typeof (query.code) === 'string' && /^\d{6}$/.test(query.code)) {
  86. const code = query.code;
  87. logger.debug(`received code: ${code}`);
  88. working = true;
  89. submitter(code)
  90. .then(response => { res.write('OK'); res.end(); server.close(() => resolve(response)); })
  91. .catch(err => { res.write('Error'); res.end(); reject(err); })
  92. .finally(() => { working = false; });
  93. }
  94. });
  95. server.listen(this.codeServicePort);
  96. });
  97. this.login = () => this.ig.simulate.preLoginFlow()
  98. .then(() => this.ig.account.login(this.username, this.password))
  99. .catch((err) => {
  100. if (err instanceof instagram_private_api_1.IgLoginTwoFactorRequiredError) {
  101. const { two_factor_identifier, totp_two_factor_on } = err.response.body.two_factor_info;
  102. logger.debug(`2FA info: ${JSON.stringify(err.response.body.two_factor_info)}`);
  103. logger.info(`login is requesting two-factor authentication via ${totp_two_factor_on ? 'TOTP' : 'SMS'}`);
  104. return this.handle2FA(code => this.ig.account.twoFactorLogin({
  105. username: this.username,
  106. verificationCode: code,
  107. twoFactorIdentifier: two_factor_identifier,
  108. verificationMethod: totp_two_factor_on ? '0' : '1',
  109. }));
  110. }
  111. throw err;
  112. })
  113. .then(user => new Promise(resolve => {
  114. logger.info(`successfully logged in as ${this.username}`);
  115. process.nextTick(() => resolve(this.ig.simulate.postLoginFlow().then(() => user)));
  116. }));
  117. this.save = () => this.ig.state.serialize()
  118. .then((serialized) => {
  119. delete serialized.constants;
  120. return fs.writeFileSync(path.resolve(this.lockfile), JSON.stringify(serialized, null, 2), 'utf-8');
  121. });
  122. this.ig = client;
  123. this.lockfile = file;
  124. [this.username, this.password] = credentials;
  125. this.codeServicePort = codeServicePort;
  126. }
  127. }
  128. exports.SessionManager = SessionManager;
  129. class ScreenNameNormalizer {
  130. static normalizeLive(username) {
  131. return __awaiter(this, void 0, void 0, function* () {
  132. if (this._queryUser) {
  133. return yield this._queryUser(username)
  134. .catch((err) => {
  135. if (!(err instanceof instagram_private_api_1.IgExactUserNotFoundError)) {
  136. logger.warn(`error looking up user: ${err.message}`);
  137. return `${username}:`;
  138. }
  139. return null;
  140. });
  141. }
  142. return this.normalize(username);
  143. });
  144. }
  145. }
  146. exports.ScreenNameNormalizer = ScreenNameNormalizer;
  147. ScreenNameNormalizer.normalize = (username) => `${username.toLowerCase().replace(/^@/, '')}:`;
  148. let browserLogin = (page) => Promise.reject();
  149. let browserSaveCookies = browserLogin;
  150. let isWaitingForLogin = false;
  151. const acceptCookieConsent = (page) => page.click('button:has-text("すべて許可")', { timeout: 5000 })
  152. .then(() => logger.info('accepted cookie consent'))
  153. .catch((err) => { if (err.name !== 'TimeoutError')
  154. throw err; });
  155. exports.WebshotHelpers = {
  156. handleLogin: browserLogin,
  157. handleCookieConsent: acceptCookieConsent,
  158. get isWaitingForLogin() { return isWaitingForLogin; },
  159. };
  160. let getPostOwner = (segmentId) => Promise.reject();
  161. exports.getPostOwner = getPostOwner;
  162. let sendPost = (segmentId, receiver) => {
  163. throw Error();
  164. };
  165. exports.sendPost = sendPost;
  166. const logger = loggers_1.getLogger('instagram');
  167. const maxTrials = 3;
  168. const retryInterval = 1500;
  169. const ordinal = (n) => {
  170. switch ((Math.trunc(n / 10) % 10 === 1) ? 0 : n % 10) {
  171. case 1:
  172. return `${n}st`;
  173. case 2:
  174. return `${n}nd`;
  175. case 3:
  176. return `${n}rd`;
  177. default:
  178. return `${n}th`;
  179. }
  180. };
  181. const retryOnError = (doWork, onRetry) => new Promise(resolve => {
  182. const retry = (reason, count) => {
  183. setTimeout(() => {
  184. let terminate = false;
  185. onRetry(reason, count, defaultValue => { terminate = true; resolve(defaultValue); });
  186. if (!terminate)
  187. doWork().then(resolve).catch(error => retry(error, count + 1));
  188. }, retryInterval);
  189. };
  190. doWork().then(resolve).catch(error => retry(error, 1));
  191. });
  192. class default_1 {
  193. constructor(opt) {
  194. this.webshotCookies = [];
  195. this.launch = () => {
  196. this.webshot = new webshot_1.default(this.wsUrl, this.mode, () => this.webshotCookies, doOnNewPage => {
  197. this.queryUserMedia = ((userName, targetId) => {
  198. let page;
  199. const url = linkBuilder({ userName });
  200. logger.debug(`pulling ${targetId !== '0' ? `feed ${url} up to ${targetId}` : `top of feed ${url}`}...`);
  201. return doOnNewPage(newPage => {
  202. page = newPage;
  203. let timeout = this.workInterval * 1000;
  204. const startTime = new Date().getTime();
  205. const getTimerTime = () => new Date().getTime() - startTime;
  206. const getTimeout = () => isWaitingForLogin ? 0 : Math.max(90000, timeout - getTimerTime());
  207. return page.context().addCookies(this.webshotCookies)
  208. .then(() => page.goto(url, { waitUntil: 'load', timeout: getTimeout() }))
  209. .then(response => {
  210. if (response.status() !== 200) {
  211. const err = new Error(`error navigating to user page, error was: ${response.status()} ${response.statusText()}`);
  212. throw Object.defineProperty(err, 'name', {
  213. value: 'ResponseError',
  214. });
  215. }
  216. }).then(() => acceptCookieConsent(page))
  217. .then(() => (next => Promise.race([
  218. browserLogin(page)
  219. .catch((err) => {
  220. if (err.name === 'TimeoutError') {
  221. logger.warn('navigation timed out, assuming login has failed');
  222. isWaitingForLogin = false;
  223. }
  224. throw err;
  225. })
  226. .then(() => browserSaveCookies(page))
  227. .then(() => page.goto(url)).then(next),
  228. next(),
  229. ]))(() => util_1.promisify(setTimeout)(2000).then(() => page.waitForSelector('article', { timeout: getTimeout() })))).then(handle => {
  230. const postHandler = () => {
  231. const toId = (href) => { var _a; return instagram_id_to_url_segment_1.urlSegmentToInstagramId(((_a = /\/p\/(.*)\/$/.exec(href)) !== null && _a !== void 0 ? _a : [, ''])[1]); };
  232. if (targetId === '0') {
  233. return handle.$$eval('a', as => as.filter(a => !a.querySelector('[aria-label="IGTV"]'))[0].href).then(href => Number(toId(href)) > 0 ? [toId(href)] : []);
  234. }
  235. return handle.$$eval('a', as => as.filter(a => !a.querySelector('[aria-label="IGTV"]')).map(a => a.href)).then(hrefs => {
  236. let id;
  237. const itemIds = [];
  238. for (const href of hrefs) {
  239. id = toId(href);
  240. if (id && utils_1.BigNumOps.compare(id, targetId) > 0)
  241. itemIds.push(id);
  242. else
  243. return itemIds;
  244. }
  245. logger.info('unable to find a smaller id than target, trying on next page...');
  246. return null;
  247. });
  248. };
  249. return postHandler().then(itemIds => {
  250. if (itemIds)
  251. return itemIds;
  252. timeout += this.workInterval * 500;
  253. return handle.$$('a')
  254. .then(as => { as.pop().scrollIntoViewIfNeeded(); return as.length + 1; })
  255. .then(loadedCount => page.waitForFunction(count => document.querySelectorAll('article a').length > count, loadedCount))
  256. .then(postHandler);
  257. });
  258. }).catch((err) => {
  259. if (err.name !== 'TimeoutError' && err.name !== 'ResponseError')
  260. throw err;
  261. if (err.name === 'ResponseError') {
  262. logger.warn(`error while fetching tweets for ${userName}: ${err.message}`);
  263. }
  264. else
  265. logger.warn(`navigation timed out at ${getTimerTime()} ms`);
  266. return [];
  267. }).then(itemIds => util_1.promisify(setTimeout)(getTimeout()).then(() => itemIds.map(id => this.lazyGetMediaById(id))));
  268. }).finally(() => { page.close(); });
  269. });
  270. setTimeout(this.work, this.workInterval * 1000);
  271. });
  272. };
  273. this.queryUser = (username) => this.client.user.searchExact(username)
  274. .then(user => `${user.username}:${user.pk}`);
  275. this.workOnMedia = (lazyMediaItems, sendMedia) => this.webshot(lazyMediaItems, sendMedia, this.webshotDelay);
  276. this.urlSegmentToId = instagram_id_to_url_segment_1.urlSegmentToInstagramId;
  277. this.lazyGetMediaById = (id) => ({
  278. pk: id,
  279. item: () => this.client.media.info(id).then(media => {
  280. const mediaItem = media.items[0];
  281. logger.debug(`api returned media post ${JSON.stringify(mediaItem)} for query id=${id}`);
  282. return mediaItem;
  283. }),
  284. });
  285. this.getMedia = (segmentId, sender) => this.workOnMedia([this.lazyGetMediaById(instagram_id_to_url_segment_1.urlSegmentToInstagramId(segmentId))], sender);
  286. this.sendMedia = (source, ...to) => (msg, text, author) => {
  287. to.forEach(subscriber => {
  288. logger.info(`pushing data${source ? ` of ${koishi_1.Message.ellipseBase64(source)}` : ''} to ${JSON.stringify(subscriber)}`);
  289. retryOnError(() => this.bot.sendTo(subscriber, msg), (_, count, terminate) => {
  290. if (count <= maxTrials) {
  291. logger.warn(`retry sending to ${subscriber.chatID} for the ${ordinal(count)} time...`);
  292. }
  293. else {
  294. logger.warn(`${count - 1} consecutive failures while sending` +
  295. 'message chain, trying plain text instead...');
  296. terminate(this.bot.sendTo(subscriber, author + text));
  297. }
  298. });
  299. });
  300. };
  301. this.work = () => {
  302. const lock = this.lock;
  303. if (this.workInterval < 1)
  304. this.workInterval = 1;
  305. if (lock.feed.length === 0) {
  306. setTimeout(() => {
  307. this.work();
  308. }, this.workInterval * 1000);
  309. return;
  310. }
  311. if (lock.workon >= lock.feed.length)
  312. lock.workon = 0;
  313. if (!lock.threads[lock.feed[lock.workon]] ||
  314. !lock.threads[lock.feed[lock.workon]].subscribers ||
  315. lock.threads[lock.feed[lock.workon]].subscribers.length === 0) {
  316. logger.warn(`nobody subscribes thread ${lock.feed[lock.workon]}, removing from feed`);
  317. delete lock.threads[lock.feed[lock.workon]];
  318. lock.feed.splice(lock.workon, 1);
  319. fs.writeFileSync(path.resolve(this.lockfile), JSON.stringify(lock));
  320. this.work();
  321. return;
  322. }
  323. const currentFeed = lock.feed[lock.workon];
  324. const promise = new Promise(resolve => {
  325. const match = /https:\/\/www\.instagram\.com\/([^\/]+)/.exec(currentFeed);
  326. if (!match)
  327. resolve([]);
  328. this.queryUserMedia(match[1], this.lock.threads[currentFeed].offset)
  329. .then(resolve)
  330. .catch((error) => {
  331. console.error(`error scraping media off profile page of ${match[1]}, error: ${error}`);
  332. resolve([]);
  333. });
  334. });
  335. promise.then((mediaItems) => {
  336. const currentThread = lock.threads[currentFeed];
  337. const updateDate = () => currentThread.updatedAt = new Date().toString();
  338. if (!mediaItems || mediaItems.length === 0) {
  339. updateDate();
  340. return;
  341. }
  342. const topOfFeed = mediaItems[0].pk;
  343. const updateOffset = () => currentThread.offset = topOfFeed;
  344. if (currentThread.offset === '-1') {
  345. updateOffset();
  346. return;
  347. }
  348. if (currentThread.offset === '0')
  349. mediaItems.splice(1);
  350. return this.workOnMedia(mediaItems, this.sendMedia(`thread ${currentFeed}`, ...currentThread.subscribers))
  351. .then(updateDate).then(updateOffset);
  352. })
  353. .then(() => {
  354. lock.workon++;
  355. let timeout = this.workInterval * 1000 / lock.feed.length;
  356. if (timeout < 1000)
  357. timeout = 1000;
  358. fs.writeFileSync(path.resolve(this.lockfile), JSON.stringify(lock));
  359. setTimeout(() => {
  360. this.work();
  361. }, timeout);
  362. });
  363. };
  364. this.client = new instagram_private_api_1.IgApiClient();
  365. if (opt.proxyUrl) {
  366. try {
  367. const url = new URL(opt.proxyUrl);
  368. if (!/^socks(?:4a?|5h?)?:$/.test(url.protocol))
  369. throw Error();
  370. if (!url.port)
  371. url.port = '1080';
  372. this.client.request.defaults.agent = new socks_proxy_agent_1.SocksProxyAgent({
  373. hostname: url.hostname,
  374. port: url.port,
  375. userId: url.username,
  376. password: url.password,
  377. });
  378. }
  379. catch (e) {
  380. logger.warn(`invalid socks proxy url: ${opt.proxyUrl}, ignoring`);
  381. }
  382. }
  383. this.session = new SessionManager(this.client, opt.sessionLockfile, opt.credentials, opt.codeServicePort);
  384. this.lockfile = opt.lockfile;
  385. this.webshotCookiesLockfile = opt.webshotCookiesLockfile;
  386. this.lock = opt.lock;
  387. this.workInterval = opt.workInterval;
  388. this.bot = opt.bot;
  389. this.webshotDelay = opt.webshotDelay;
  390. this.mode = opt.mode;
  391. this.wsUrl = opt.wsUrl;
  392. const cookiesFilePath = path.resolve(this.webshotCookiesLockfile);
  393. try {
  394. this.webshotCookies = JSON.parse(fs.readFileSync(cookiesFilePath, 'utf8'));
  395. logger.info(`loaded webshot cookies from file ${this.webshotCookiesLockfile}`);
  396. }
  397. catch (err) {
  398. logger.warn(`failed to load webshot cookies from file ${this.webshotCookiesLockfile}: `, err.message);
  399. logger.warn('cookies will be saved to this file when needed');
  400. }
  401. browserLogin = page => page.fill('input[name="username"]', opt.credentials[0], { timeout: 0 })
  402. .then(() => { isWaitingForLogin = true; logger.warn('blocked by login dialog, trying to log in manually...'); })
  403. .then(() => page.fill('input[name="password"]', opt.credentials[1], { timeout: 0 }))
  404. .then(() => page.click('button[type="submit"]', { timeout: 0 }))
  405. .then(() => (next => Promise.race([
  406. page.waitForSelector('#verificationCodeDescription', { timeout: 0 }).then(handle => handle.innerText()).then(text => {
  407. logger.info(`login is requesting two-factor authentication via ${/認証アプリ/.test(text) ? 'TOTP' : 'SMS'}`);
  408. return this.session.handle2FA(code => page.fill('input[name="verificationCode"]', code, { timeout: 0 }))
  409. .then(() => page.click('button:has-text("実行")', { timeout: 0 }))
  410. .then(next);
  411. }),
  412. page.waitForResponse(res => res.status() === 429, { timeout: 0 })
  413. .then(() => { logger.error('fatal error: login restricted: code 429, exiting'); process.exit(1); }),
  414. next(),
  415. ]))(() => page.click('button:has-text("情報を保存")', { timeout: 0 }).then(() => { isWaitingForLogin = false; })));
  416. browserSaveCookies = page => page.context().cookies()
  417. .then(cookies => {
  418. this.webshotCookies = cookies;
  419. logger.info('successfully logged in, saving cookies to file...');
  420. fs.writeFileSync(path.resolve(this.webshotCookiesLockfile), JSON.stringify(cookies, null, 2), 'utf-8');
  421. });
  422. exports.WebshotHelpers.handleLogin = page => browserLogin(page)
  423. .then(() => page.waitForSelector('img[data-testid="user-avatar"]', { timeout: this.webshotDelay }))
  424. .then(() => browserSaveCookies(page))
  425. .catch((err) => {
  426. if (err.name === 'TimeoutError') {
  427. logger.warn('navigation timed out, assuming login has failed');
  428. isWaitingForLogin = false;
  429. }
  430. throw err;
  431. });
  432. ScreenNameNormalizer._queryUser = this.queryUser;
  433. const parseMediaError = (err) => {
  434. if (!(err instanceof instagram_private_api_1.IgResponseError && err.text === 'Media not found or unavailable')) {
  435. logger.warn(`error retrieving instagram media: ${err.message}`);
  436. return `获取媒体时出现错误:${err.message}`;
  437. }
  438. return '找不到请求的媒体,它可能已被删除。';
  439. };
  440. exports.getPostOwner = (segmentId) => this.client.media.info(instagram_id_to_url_segment_1.urlSegmentToInstagramId(segmentId))
  441. .then(media => media.items[0].user)
  442. .then(user => `${user.username}:${user.pk}`)
  443. .catch((err) => { throw Error(parseMediaError(err)); });
  444. exports.sendPost = (segmentId, receiver) => {
  445. this.getMedia(segmentId, this.sendMedia(`instagram media ${segmentId}`, receiver))
  446. .catch((err) => { this.bot.sendTo(receiver, parseMediaError(err)); });
  447. };
  448. }
  449. }
  450. exports.default = default_1;