twitter.js 31 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544
  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.parseLink = exports.linkBuilder = exports.graphqlLinkBuilder = 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. const instagram_private_api_1 = require("instagram-private-api");
  22. const socks_proxy_agent_1 = require("socks-proxy-agent");
  23. const loggers_1 = require("./loggers");
  24. const utils_1 = require("./utils");
  25. const webshot_1 = require("./webshot");
  26. const parseLink = (link) => {
  27. let match = /instagram\.com\/(?:[^\/?#]+\/)?(?:p|tv)\/([A-Za-z0-9\-_]+)/.exec(link);
  28. if (match)
  29. return { postUrlSegment: match[1] };
  30. match =
  31. /instagram\.com\/([^\/?#]+)/.exec(link) ||
  32. /^([^\/?#]+)$/.exec(link);
  33. if (match)
  34. return { userName: ScreenNameNormalizer.normalize(match[1]).split(':')[0] };
  35. return;
  36. };
  37. exports.parseLink = parseLink;
  38. const linkBuilder = (config) => {
  39. if (config.userName)
  40. return `https://www.instagram.com/${config.userName}/`;
  41. if (config.postUrlSegment)
  42. return `https://www.instagram.com/p/${config.postUrlSegment}/`;
  43. };
  44. exports.linkBuilder = linkBuilder;
  45. const graphqlLinkBuilder = ({ userId: id, first = '12', after }) => `https://www.instagram.com/graphql/query/?query_hash=8c2a529969ee035a5063f2fc8602a0fd&variables=${JSON.stringify({ id, first, after })}`;
  46. exports.graphqlLinkBuilder = graphqlLinkBuilder;
  47. const urlSegmentToId = (urlSegment) => urlSegment.length <= 28 ?
  48. (0, instagram_id_to_url_segment_1.urlSegmentToInstagramId)(urlSegment) : (0, instagram_id_to_url_segment_1.urlSegmentToInstagramId)(urlSegment.slice(0, -28));
  49. exports.urlSegmentToId = urlSegmentToId;
  50. class SessionManager {
  51. constructor(client, file, credentials, codeServicePort) {
  52. this.init = () => {
  53. this.ig.state.generateDevice(this.username);
  54. this.ig.request.end$.subscribe(() => { this.save(); });
  55. const filePath = path.resolve(this.lockfile);
  56. if (fs.existsSync(filePath)) {
  57. try {
  58. const serialized = JSON.parse(fs.readFileSync(filePath, 'utf8'));
  59. return this.ig.state.deserialize(serialized).then(() => {
  60. logger.info(`successfully loaded client session cookies for user ${this.username}`);
  61. });
  62. }
  63. catch (err) {
  64. logger.error(`failed to load client session cookies from file ${this.lockfile}: `, err);
  65. return Promise.resolve();
  66. }
  67. }
  68. else {
  69. return this.login().catch((err) => {
  70. logger.error(`error while trying to log in as user ${this.username}, error: ${err}`);
  71. logger.warn('attempting to retry after 1 minute...');
  72. if (fs.existsSync(filePath))
  73. fs.unlinkSync(filePath);
  74. (0, util_1.promisify)(setTimeout)(60000).then(this.init);
  75. });
  76. }
  77. };
  78. this.handle2FA = (submitter) => new Promise((resolve, reject) => {
  79. const token = crypto.randomBytes(20).toString('hex');
  80. logger.info('please submit the code with a one-time token from your browser with this path:');
  81. logger.info(`/confirm-2fa?code=<the code you received>&token=${token}`);
  82. let working;
  83. const server = http.createServer((req, res) => {
  84. const { pathname, query } = (0, url_1.parse)(req.url, true);
  85. if (!working && pathname === '/confirm-2fa' && query.token === token &&
  86. typeof (query.code) === 'string' && /^\d{6}$/.test(query.code)) {
  87. const code = query.code;
  88. logger.debug(`received code: ${code}`);
  89. working = true;
  90. submitter(code)
  91. .then(response => { res.write('OK'); res.end(); server.close(() => resolve(response)); })
  92. .catch(err => { res.write('Error'); res.end(); reject(err); })
  93. .finally(() => { working = false; });
  94. }
  95. });
  96. server.listen(this.codeServicePort);
  97. });
  98. this.login = () => this.ig.simulate.preLoginFlow()
  99. .then(() => this.ig.account.login(this.username, this.password))
  100. .catch((err) => {
  101. if (err instanceof instagram_private_api_1.IgLoginTwoFactorRequiredError) {
  102. const { two_factor_identifier, totp_two_factor_on } = err.response.body.two_factor_info;
  103. logger.debug(`2FA info: ${JSON.stringify(err.response.body.two_factor_info)}`);
  104. logger.info(`login is requesting two-factor authentication via ${totp_two_factor_on ? 'TOTP' : 'SMS'}`);
  105. return this.handle2FA(code => this.ig.account.twoFactorLogin({
  106. username: this.username,
  107. verificationCode: code,
  108. twoFactorIdentifier: two_factor_identifier,
  109. verificationMethod: totp_two_factor_on ? '0' : '1',
  110. }));
  111. }
  112. throw err;
  113. })
  114. .then(user => new Promise(resolve => {
  115. logger.info(`successfully logged in as ${this.username}`);
  116. process.nextTick(() => resolve(this.ig.simulate.postLoginFlow().then(() => user)));
  117. }));
  118. this.save = () => this.ig.state.serialize()
  119. .then((serialized) => {
  120. delete serialized.constants;
  121. return fs.writeFileSync(path.resolve(this.lockfile), JSON.stringify(serialized, null, 2), 'utf-8');
  122. });
  123. this.ig = client;
  124. this.lockfile = file;
  125. [this.username, this.password] = credentials;
  126. this.codeServicePort = codeServicePort;
  127. }
  128. }
  129. exports.SessionManager = SessionManager;
  130. class ScreenNameNormalizer {
  131. static normalizeLive(username) {
  132. return __awaiter(this, void 0, void 0, function* () {
  133. if (this._queryUser) {
  134. return yield this._queryUser(username)
  135. .catch((err) => {
  136. if (!(err instanceof instagram_private_api_1.IgExactUserNotFoundError)) {
  137. logger.warn(`error looking up user: ${err.message}`);
  138. return `${username}:`;
  139. }
  140. return null;
  141. });
  142. }
  143. return this.normalize(username);
  144. });
  145. }
  146. }
  147. exports.ScreenNameNormalizer = ScreenNameNormalizer;
  148. ScreenNameNormalizer.normalize = (username) => `${username.toLowerCase().replace(/^@/, '')}:`;
  149. let browserLogin = (page) => Promise.resolve();
  150. let browserSaveCookies = browserLogin;
  151. let isWaitingForLogin = false;
  152. const acceptCookieConsent = (page) => page.click('button:text-matches("すべて.*許可")', { timeout: 5000 })
  153. .then(() => logger.info('accepted cookie consent'))
  154. .catch((err) => { if (err.name !== 'TimeoutError')
  155. throw err; });
  156. exports.WebshotHelpers = {
  157. handleLogin: browserLogin,
  158. handleCookieConsent: acceptCookieConsent,
  159. get isWaitingForLogin() { return isWaitingForLogin; },
  160. };
  161. let getPostOwner = (segmentId) => Promise.reject();
  162. exports.getPostOwner = getPostOwner;
  163. let sendPost = (segmentId, receiver) => {
  164. throw Error();
  165. };
  166. exports.sendPost = sendPost;
  167. const graphNodeToMediaItem = (node) => (Object.assign({ taken_at: node.taken_at_timestamp, code: (code => {
  168. logger.debug(`converting post ${linkBuilder({ postUrlSegment: code })} into mobile api format...`);
  169. return code;
  170. })(node.shortcode), caption: (caption => (caption && caption.edges.length ? caption.edges[0].node : {}))(node.edge_media_to_caption), user: {
  171. pk: node.owner.id,
  172. username: node.owner.username,
  173. } }, graphBaseNodeToCarouselMediaItem(node)));
  174. const graphBaseNodeToCarouselMediaItem = (node) => (Object.assign(Object.assign(Object.assign({ pk: node.id }, (node.__typename === 'GraphImage') && { image_versions2: { candidates: node.display_resources.map(({ src, config_width, config_height }) => ({ url: src, width: config_width, height: config_height })) } }), (node.__typename === 'GraphVideo' && { video_versions: [{ url: node.video_url, height: 0, width: 0 }] })), (node.__typename === 'GraphSidecar' && { carousel_media: node.edge_sidecar_to_children.edges.map(({ node }) => graphBaseNodeToCarouselMediaItem(node)) })));
  175. const logger = (0, loggers_1.getLogger)('instagram');
  176. const maxTrials = 3;
  177. const retryInterval = 1500;
  178. const ordinal = (n) => {
  179. switch ((Math.trunc(n / 10) % 10 === 1) ? 0 : n % 10) {
  180. case 1:
  181. return `${n}st`;
  182. case 2:
  183. return `${n}nd`;
  184. case 3:
  185. return `${n}rd`;
  186. default:
  187. return `${n}th`;
  188. }
  189. };
  190. const retryOnError = (doWork, onRetry) => new Promise(resolve => {
  191. const retry = (reason, count) => {
  192. setTimeout(() => {
  193. let terminate = false;
  194. onRetry(reason, count, defaultValue => { terminate = true; resolve(defaultValue); });
  195. if (!terminate)
  196. doWork().then(resolve).catch(error => retry(error, count + 1));
  197. }, retryInterval);
  198. };
  199. doWork().then(resolve).catch(error => retry(error, 1));
  200. });
  201. class default_1 {
  202. constructor(opt) {
  203. this.webshotCookies = [];
  204. this.launch = () => {
  205. this.webshot = new webshot_1.default(this.wsUrl, this.mode, () => this.webshotCookies, doOnNewPage => {
  206. this.queryUserMedia = ((username, targetId) => {
  207. let page;
  208. let url;
  209. return (username.includes(':') ? Promise.resolve(username) : this.queryUser(username)).then(userNameId => doOnNewPage(newPage => {
  210. const [userName, userId] = userNameId.split(':');
  211. let fullName;
  212. url = graphqlLinkBuilder({ userId });
  213. logger.debug(`pulling ${targetId !== '0' ? `feed ${url} up to ${targetId}` : `top of feed ${url}`}...`);
  214. page = newPage;
  215. let timeout = this.webshotDelay / 2;
  216. const startTime = new Date().getTime();
  217. const getTimerTime = () => new Date().getTime() - startTime;
  218. const getTimeout = () => isWaitingForLogin ? 0 : Math.max(5000, timeout - getTimerTime());
  219. return page.context().addCookies(this.webshotCookies)
  220. .then(() => page.goto(url, { waitUntil: 'load', timeout: getTimeout() }))
  221. .then(response => {
  222. const nodes = [];
  223. const redirectionHandler = () => acceptCookieConsent(page)
  224. .then(() => browserLogin(page))
  225. .catch((err) => {
  226. if (err.name === 'TimeoutError') {
  227. logger.warn('navigation timed out, assuming login has failed');
  228. isWaitingForLogin = false;
  229. }
  230. throw err;
  231. })
  232. .then(() => browserSaveCookies(page))
  233. .then(() => page.goto(url, { waitUntil: 'load', timeout: getTimeout() }))
  234. .then(responseHandler);
  235. const responseHandler = (res) => {
  236. if (res.status() !== 200) {
  237. throw (0, utils_1.customError)('ResponseError')(`error navigating to user page, error was: ${res.status()} ${res.statusText()}`);
  238. }
  239. return res.text()
  240. .then(text => {
  241. logger.debug(`api returned ${text} while pulling for ${userName}`);
  242. return JSON.parse(text);
  243. })
  244. .catch(redirectionHandler)
  245. .then((json) => {
  246. var _a;
  247. if (!json || !((_a = (json.graphql || json.data)) === null || _a === void 0 ? void 0 : _a.user)) {
  248. logger.warn('error parsing graphql response, returning empty object...');
  249. const data = { user: { edge_owner_to_timeline_media: { edges: [] } } };
  250. return { data };
  251. }
  252. return json;
  253. });
  254. };
  255. const jsonHandler = ({ user }) => {
  256. if (user.full_name)
  257. fullName = user.full_name;
  258. const pageInfo = user.edge_owner_to_timeline_media.page_info;
  259. for (const { node } of user.edge_owner_to_timeline_media.edges) {
  260. if (!fullName && node.accessibility_caption) {
  261. fullName = node.accessibility_caption.replace(/^Photo by (.+) on \w+ \d+, \d+\..*/, '$1');
  262. }
  263. const isVideoTooLong = (info) => {
  264. let manifest;
  265. if (info && (manifest = info.video_dash_manifest)) {
  266. const match = /mediaPresentationDuration="PT(?:(\d+)H)?(?:(\d+)M)?\d+.\d+S"/.exec(manifest);
  267. return Number(match[1]) > 0 || Number(match[2]) > 10;
  268. }
  269. return false;
  270. };
  271. if (node.__typename === 'GraphVideo' && isVideoTooLong(node.dash_info))
  272. continue;
  273. if (node.id && utils_1.BigNumOps.compare(node.id, targetId) > 0)
  274. nodes.push(node);
  275. else
  276. return nodes;
  277. if (Number(targetId) < 1)
  278. return nodes;
  279. }
  280. if (!(pageInfo === null || pageInfo === void 0 ? void 0 : pageInfo.has_next_page))
  281. return nodes;
  282. logger.info('unable to find a smaller id than target, trying on next page...');
  283. url = graphqlLinkBuilder({ userId, after: pageInfo.end_cursor });
  284. const nextPageDelay = this.webshotDelay * (0.4 + Math.random() * 0.1);
  285. timeout += nextPageDelay;
  286. return (0, util_1.promisify)(setTimeout)(nextPageDelay)
  287. .then(() => page.goto(url, { waitUntil: 'load', timeout: getTimeout() }))
  288. .then(responseHandler)
  289. .then(({ data }) => jsonHandler(data));
  290. };
  291. return responseHandler(response)
  292. .then(({ data }) => jsonHandler(data));
  293. }).catch((err) => {
  294. if (err.name === 'ResponseError' || err.name === 'TypeError') {
  295. logger.warn(`error while fetching posts by @${userName}: ${err}`);
  296. }
  297. else if (err.name === 'TimeoutError') {
  298. logger.warn(`navigation timed out at ${getTimerTime()} ms`);
  299. }
  300. else
  301. throw err;
  302. return [];
  303. }).then(nodes => (!fullName && nodes.length ?
  304. this.client.user.searchExact(nodes[0].owner.username) :
  305. Promise.resolve({ full_name: fullName })).then(({ full_name }) => (0, util_1.promisify)(setTimeout)(getTimeout()).then(() => nodes.map(node => {
  306. const item = graphNodeToMediaItem(node);
  307. item.user.full_name = full_name;
  308. return {
  309. pk: item.pk,
  310. item: () => Promise.resolve(item),
  311. };
  312. }))));
  313. })).finally(() => { page.close(); });
  314. });
  315. setTimeout(this.work, this.workInterval * 1000 / this.lock.feed.length);
  316. });
  317. };
  318. this.queryUser = (username) => this.client.user.searchExact(username)
  319. .catch((error) => {
  320. if (error instanceof instagram_private_api_1.IgLoginRequiredError || error instanceof instagram_private_api_1.IgCookieNotFoundError) {
  321. logger.warn('login required, logging in again...');
  322. return this.session.login().then(() => this.client.user.searchExact(username));
  323. }
  324. else
  325. throw error;
  326. })
  327. .then(user => `${user.username}:${user.pk}`);
  328. this.workOnMedia = (lazyMediaItems, sendMedia) => this.webshot(lazyMediaItems, sendMedia, this.webshotDelay);
  329. this.urlSegmentToId = urlSegmentToId;
  330. this.lazyGetMediaById = (id) => ({
  331. pk: id,
  332. item: () => this.client.media.info(id).then(media => {
  333. const mediaItem = media.items[0];
  334. logger.debug(`api returned media post ${JSON.stringify(mediaItem)} for query id=${id}`);
  335. return mediaItem;
  336. }),
  337. });
  338. this.sendMedia = (source, ...to) => (msg, text, author) => {
  339. to.forEach(subscriber => {
  340. logger.info(`pushing data${source ? ` of ${source}` : ''} to ${JSON.stringify(subscriber)}`);
  341. retryOnError(() => this.bot.sendTo(subscriber, msg), (_, count, terminate) => {
  342. if (count <= maxTrials) {
  343. logger.warn(`retry sending to ${subscriber.chatID} for the ${ordinal(count)} time...`);
  344. }
  345. else {
  346. logger.warn(`${count - 1} consecutive failures while sending message chain, trying plain text instead...`);
  347. terminate(this.bot.sendTo(subscriber, author + text, true));
  348. }
  349. });
  350. });
  351. };
  352. this.workOnFeed = (feed) => new Promise(resolve => {
  353. const match = /https:\/\/www\.instagram\.com\/([^\/]+)/.exec(feed);
  354. if (!match) {
  355. logger.error(`current feed "${feed}" is invalid, please remove this feed manually`);
  356. return resolve([]);
  357. }
  358. const userNameId = `${match[1]}:${this.lock.threads[feed].id}`;
  359. return resolve(this.queryUserMedia(userNameId, this.lock.threads[feed].offset)
  360. .catch((error) => {
  361. logger.error(`error scraping media off profile page of ${match[1]}, error: ${error}`);
  362. return [];
  363. }));
  364. }).then(mediaItems => {
  365. const currentThread = this.lock.threads[feed];
  366. const updateDate = () => currentThread.updatedAt = new Date().toString();
  367. if (!mediaItems || mediaItems.length === 0) {
  368. updateDate();
  369. return;
  370. }
  371. const topOfFeed = mediaItems[0].pk;
  372. const updateOffset = () => { currentThread.offset = topOfFeed; };
  373. if (currentThread.offset === '-1') {
  374. updateOffset();
  375. return;
  376. }
  377. if (currentThread.offset === '0')
  378. mediaItems.splice(1);
  379. return this.workOnMedia(mediaItems, this.sendMedia(`thread ${feed}`, ...currentThread.subscribers))
  380. .then(updateDate).then(updateOffset);
  381. });
  382. this.work = () => {
  383. const lock = this.lock;
  384. if (this.workInterval < 1)
  385. this.workInterval = 1;
  386. if (this.isInactiveTime || lock.feed.length === 0) {
  387. setTimeout(this.work, this.workInterval * 1000 / lock.feed.length);
  388. return;
  389. }
  390. lock.feed.forEach((feed, index) => {
  391. if (!lock.threads[feed] ||
  392. !lock.threads[feed].subscribers ||
  393. lock.threads[feed].subscribers.length === 0) {
  394. logger.warn(`nobody subscribes thread ${feed}, removing from feed`);
  395. delete lock.threads[index];
  396. lock.feed.splice(index, 1);
  397. fs.writeFileSync(path.resolve(this.lockfile), JSON.stringify(lock));
  398. }
  399. });
  400. const queuedFeeds = lock.feed.slice(0, (lock.workon + 1) || undefined).reverse();
  401. (0, utils_1.chainPromises)(utils_1.Arr.chunk(queuedFeeds, 5).map((arr, i) => () => Promise.all(arr.map((currentFeed, j) => {
  402. const promiseDelay = this.workInterval * (Math.random() + j + 10 - arr.length) * 125 / lock.feed.length;
  403. const wait = (ms) => isWaitingForLogin ? (0, utils_1.neverResolves)() : (0, util_1.promisify)(setTimeout)(ms);
  404. const startTime = new Date().getTime();
  405. const getTimerTime = () => new Date().getTime() - startTime;
  406. const workon = (queuedFeeds.length - 1) - (i * 5 + j);
  407. fs.writeFileSync(path.resolve(this.lockfile), JSON.stringify(lock));
  408. if (Date.now() - new Date(lock.threads[currentFeed].updatedAt).getTime() < 3600000) {
  409. logger.info(`skipped feed #${workon}: ${currentFeed}, last updated within an hour`);
  410. return wait(promiseDelay * 3);
  411. }
  412. return (0, util_1.promisify)(setTimeout)(promiseDelay * 3).then(() => {
  413. logger.info(`about to pull from feed #${workon}: ${currentFeed}`);
  414. if (j === arr.length - 1)
  415. logger.info(`timeout for this batch job: ${Math.trunc(promiseDelay)} ms`);
  416. const promise = this.workOnFeed(currentFeed).then(() => {
  417. lock.workon = workon - 1;
  418. if (j === arr.length - 1) {
  419. logger.info(`batch job #${workon}-${workon + j} completed after ${getTimerTime()} ms`);
  420. }
  421. fs.writeFileSync(path.resolve(this.lockfile), JSON.stringify(lock));
  422. });
  423. return Promise.race([promise, wait(promiseDelay * 4)]);
  424. });
  425. })))).then(this.work);
  426. };
  427. this.client = new instagram_private_api_1.IgApiClient();
  428. if (opt.proxyUrl) {
  429. try {
  430. const url = new URL(opt.proxyUrl);
  431. if (!/^socks(?:4a?|5h?)?:$/.test(url.protocol))
  432. throw Error();
  433. if (!url.port)
  434. url.port = '1080';
  435. this.client.request.defaults.agent = new socks_proxy_agent_1.SocksProxyAgent({
  436. hostname: url.hostname,
  437. port: url.port,
  438. userId: url.username,
  439. password: url.password,
  440. });
  441. }
  442. catch (e) {
  443. logger.warn(`invalid socks proxy url: ${opt.proxyUrl}, ignoring`);
  444. }
  445. }
  446. this.session = new SessionManager(this.client, opt.sessionLockfile, opt.credentials, opt.codeServicePort);
  447. this.lockfile = opt.lockfile;
  448. this.webshotCookiesLockfile = opt.webshotCookiesLockfile;
  449. this.lock = opt.lock;
  450. this.inactiveHours = opt.inactiveHours;
  451. this.workInterval = opt.workInterval;
  452. this.bot = opt.bot;
  453. this.webshotDelay = opt.webshotDelay;
  454. this.mode = opt.mode;
  455. this.wsUrl = opt.wsUrl;
  456. const cookiesFilePath = path.resolve(this.webshotCookiesLockfile);
  457. try {
  458. this.webshotCookies = JSON.parse(fs.readFileSync(cookiesFilePath, 'utf8'));
  459. logger.info(`loaded webshot cookies from file ${this.webshotCookiesLockfile}`);
  460. }
  461. catch (err) {
  462. logger.warn(`failed to load webshot cookies from file ${this.webshotCookiesLockfile}: `, err.message);
  463. logger.warn('cookies will be saved to this file when needed');
  464. }
  465. browserLogin = page => page.fill('input[name="username"]', opt.credentials[0], { timeout: 0 })
  466. .then(() => {
  467. if (isWaitingForLogin !== true)
  468. return;
  469. logger.warn('still waiting for login, pausing execution...');
  470. return (0, utils_1.neverResolves)();
  471. })
  472. .then(() => { isWaitingForLogin = true; logger.warn('blocked by login dialog, trying to log in manually...'); })
  473. .then(() => page.fill('input[name="password"]', opt.credentials[1], { timeout: 0 }))
  474. .then(() => page.click('button[type="submit"]', { timeout: 0 }))
  475. .then(() => (next => Promise.race([
  476. page.waitForSelector('#verificationCodeDescription', { timeout: 0 }).then(handle => handle.innerText()).then(text => {
  477. logger.info(`login is requesting two-factor authentication via ${/認証アプリ/.test(text) ? 'TOTP' : 'SMS'}`);
  478. return this.session.handle2FA(code => page.fill('input[name="verificationCode"]', code, { timeout: 0 }))
  479. .then(() => page.click('button:has-text("実行")', { timeout: 0 }))
  480. .then(next);
  481. }),
  482. next(),
  483. ]))(() => page.click('button:has-text("情報を保存")', { timeout: 0 }).then(() => { isWaitingForLogin = false; })));
  484. browserSaveCookies = page => page.context().cookies()
  485. .then(cookies => {
  486. this.webshotCookies = cookies;
  487. logger.info('successfully logged in, saving cookies to file...');
  488. fs.writeFileSync(path.resolve(this.webshotCookiesLockfile), JSON.stringify(cookies, null, 2), 'utf-8');
  489. });
  490. exports.WebshotHelpers.handleLogin = page => browserLogin(page)
  491. .then(() => page.waitForSelector('img[data-testid="user-avatar"]', { timeout: this.webshotDelay }))
  492. .then(() => browserSaveCookies(page))
  493. .catch((err) => {
  494. if (err.name === 'TimeoutError') {
  495. logger.warn('navigation timed out, assuming login has failed');
  496. isWaitingForLogin = false;
  497. }
  498. throw err;
  499. });
  500. ScreenNameNormalizer._queryUser = this.queryUser;
  501. const parseMediaError = (err) => {
  502. if (!(err instanceof instagram_private_api_1.IgResponseError && err.text === 'Media not found or unavailable')) {
  503. logger.warn(`error retrieving instagram media: ${err.message}`);
  504. return `获取媒体时出现错误:${err.message}`;
  505. }
  506. return '找不到请求的媒体,它可能已被删除。';
  507. };
  508. exports.getPostOwner = (segmentId) => this.client.media.info(urlSegmentToId(segmentId))
  509. .then(media => media.items[0].user)
  510. .then(user => `${user.username}:${user.pk}`)
  511. .catch((err) => { throw Error(parseMediaError(err)); });
  512. exports.sendPost = (segmentId, receiver) => {
  513. const lazyMedia = this.lazyGetMediaById(urlSegmentToId(segmentId));
  514. return lazyMedia.item().then(mediaItem => {
  515. const lock = this.lock;
  516. const feed = linkBuilder({ userName: mediaItem.user.username });
  517. if (lock.feed.includes(feed) && lock.threads[feed].offset < mediaItem.pk) {
  518. logger.info(`post is newer than last offset of thread (${(0, instagram_id_to_url_segment_1.instagramIdToUrlSegment)(lock.threads[feed].offset)}), updating...`);
  519. this.workOnFeed(feed);
  520. if (lock.threads[feed].subscribers.some(subscriber => subscriber.chatID.toString() === receiver.chatID.toString() &&
  521. subscriber.chatType === receiver.chatType))
  522. return logger.info(`receiver has already subscribed to feed ${feed}, not sending again`);
  523. }
  524. lazyMedia.item = () => Promise.resolve(mediaItem);
  525. this.workOnMedia([lazyMedia], this.sendMedia(`instagram media ${segmentId}`, receiver));
  526. }).catch((err) => {
  527. this.bot.sendTo(receiver, parseMediaError(err));
  528. if (err instanceof instagram_private_api_1.IgLoginRequiredError || err instanceof instagram_private_api_1.IgCookieNotFoundError) {
  529. logger.warn('login required, awaiting login...');
  530. this.bot.sendTo(receiver, '等待登录中,稍后会处理请求,请稍候……');
  531. return this.session.login().then(() => (0, exports.sendPost)(segmentId, receiver));
  532. }
  533. ;
  534. });
  535. };
  536. }
  537. get isInactiveTime() {
  538. const timeToEpoch = (h = 0, m = 0) => new Date().setHours(h, m, 0, 0);
  539. return this.inactiveHours
  540. .map(rangeStr => ((start, end) => ({ start, end }))(...rangeStr.split('-', 2).map(timeStr => timeToEpoch(...timeStr.split(':', 2).map(Number)))))
  541. .some(range => (now => now >= range.start && now < range.end)(Date.now()));
  542. }
  543. }
  544. exports.default = default_1;