twitter.js 31 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561
  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, browserAwaitLogin = browserLogin;
  151. let isWaitingForLogin = false;
  152. const LoginAwaiter = Object.seal({
  153. awaiter: Promise.resolve(),
  154. resolver: () => logger.warn('already logged in'),
  155. new: () => {
  156. isWaitingForLogin = true;
  157. LoginAwaiter.awaiter = new Promise(resolve => {
  158. const getNew = LoginAwaiter.new;
  159. const resolver = LoginAwaiter.resolver;
  160. LoginAwaiter.resolver = () => {
  161. resolve();
  162. isWaitingForLogin = false;
  163. LoginAwaiter.resolver = resolver;
  164. LoginAwaiter.new = getNew;
  165. };
  166. });
  167. LoginAwaiter.new = () => logger.warn('awaiting login...');
  168. },
  169. });
  170. const acceptCookieConsent = (page) => page.click('button:text-matches("すべて.*許可")', { timeout: 5000 })
  171. .then(() => logger.info('accepted cookie consent'))
  172. .catch((err) => { if (err.name !== 'TimeoutError')
  173. throw err; });
  174. exports.WebshotHelpers = {
  175. handleLogin: browserLogin,
  176. handleCookieConsent: acceptCookieConsent,
  177. get isWaitingForLogin() { return isWaitingForLogin; },
  178. };
  179. let getPostOwner = (segmentId) => Promise.reject();
  180. exports.getPostOwner = getPostOwner;
  181. let sendPost = (segmentId, receiver) => {
  182. throw Error();
  183. };
  184. exports.sendPost = sendPost;
  185. const graphNodeToMediaItem = (node) => (Object.assign({ taken_at: node.taken_at_timestamp, code: (code => {
  186. logger.debug(`converting post ${linkBuilder({ postUrlSegment: code })} into mobile api format...`);
  187. return code;
  188. })(node.shortcode), caption: (caption => (caption && caption.edges.length ? caption.edges[0].node : {}))(node.edge_media_to_caption), user: {
  189. pk: node.owner.id,
  190. username: node.owner.username,
  191. } }, graphBaseNodeToCarouselMediaItem(node)));
  192. 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)) })));
  193. const logger = (0, loggers_1.getLogger)('instagram');
  194. const maxTrials = 3;
  195. const retryInterval = 1500;
  196. const ordinal = (n) => {
  197. switch ((Math.trunc(n / 10) % 10 === 1) ? 0 : n % 10) {
  198. case 1:
  199. return `${n}st`;
  200. case 2:
  201. return `${n}nd`;
  202. case 3:
  203. return `${n}rd`;
  204. default:
  205. return `${n}th`;
  206. }
  207. };
  208. const retryOnError = (doWork, onRetry) => new Promise(resolve => {
  209. const retry = (reason, count) => {
  210. setTimeout(() => {
  211. let terminate = false;
  212. onRetry(reason, count, defaultValue => { terminate = true; resolve(defaultValue); });
  213. if (!terminate)
  214. doWork().then(resolve).catch(error => retry(error, count + 1));
  215. }, retryInterval);
  216. };
  217. doWork().then(resolve).catch(error => retry(error, 1));
  218. });
  219. class default_1 {
  220. constructor(opt) {
  221. this.webshotCookies = [];
  222. this.launch = () => {
  223. this.webshot = new webshot_1.default(this.wsUrl, this.mode, () => this.webshotCookies, doOnNewPage => {
  224. this.queryUserMedia = ((username, targetId) => {
  225. let page;
  226. let url;
  227. return (username.includes(':') ? Promise.resolve(username) : this.queryUser(username)).then(userNameId => doOnNewPage(newPage => {
  228. const [userName, userId] = userNameId.split(':');
  229. let fullName;
  230. url = graphqlLinkBuilder({ userId });
  231. logger.debug(`pulling ${targetId !== '0' ? `feed ${url} up to ${targetId}` : `top of feed ${url}`}...`);
  232. page = newPage;
  233. let timeout = this.webshotDelay / 2;
  234. const startTime = new Date().getTime();
  235. const getTimerTime = () => new Date().getTime() - startTime;
  236. const getTimeout = () => isWaitingForLogin ? 0 : Math.max(5000, timeout - getTimerTime());
  237. const nextPageDelay = this.webshotDelay * (0.4 + Math.random() * 0.1);
  238. return page.context().addCookies(this.webshotCookies)
  239. .then(() => page.goto(url, { waitUntil: 'load', timeout: getTimeout() }))
  240. .then(response => {
  241. const nodes = [];
  242. const redirectionHandler = () => acceptCookieConsent(page)
  243. .then(() => isWaitingForLogin ?
  244. browserAwaitLogin(page).then(() => (0, util_1.promisify)(setTimeout)(nextPageDelay)) :
  245. browserLogin(page)
  246. .catch((err) => {
  247. if (err.name === 'TimeoutError') {
  248. logger.warn('navigation timed out, assuming login has failed');
  249. LoginAwaiter.resolver();
  250. }
  251. throw err;
  252. })
  253. .then(() => browserSaveCookies(page)))
  254. .then(() => page.goto(url, { waitUntil: 'load', timeout: getTimeout() }))
  255. .then(responseHandler);
  256. const responseHandler = (res) => {
  257. if (res.status() !== 200) {
  258. throw (0, utils_1.customError)('ResponseError')(`error navigating to user page, error was: ${res.status()} ${res.statusText()}`);
  259. }
  260. return res.text()
  261. .then(text => {
  262. logger.debug(`api returned ${text} while pulling for ${userName}`);
  263. return JSON.parse(text);
  264. })
  265. .catch(redirectionHandler)
  266. .then((json) => {
  267. var _a;
  268. if (!json || !((_a = (json.graphql || json.data)) === null || _a === void 0 ? void 0 : _a.user)) {
  269. logger.warn('error parsing graphql response, returning empty object...');
  270. const data = { user: { edge_owner_to_timeline_media: { edges: [] } } };
  271. return { data };
  272. }
  273. return json;
  274. });
  275. };
  276. const jsonHandler = ({ user }) => {
  277. if (user.full_name)
  278. fullName = user.full_name;
  279. const pageInfo = user.edge_owner_to_timeline_media.page_info;
  280. for (const { node } of user.edge_owner_to_timeline_media.edges) {
  281. if (!fullName && node.accessibility_caption) {
  282. fullName = node.accessibility_caption.replace(/^Photo by (.+) on \w+ \d+, \d+\..*/, '$1');
  283. }
  284. const isVideoTooLong = (info) => {
  285. let manifest;
  286. if (info && (manifest = info.video_dash_manifest)) {
  287. const match = /mediaPresentationDuration="PT(?:(\d+)H)?(?:(\d+)M)?\d+.\d+S"/.exec(manifest);
  288. return Number(match[1]) > 0 || Number(match[2]) > 10;
  289. }
  290. return false;
  291. };
  292. if (node.__typename === 'GraphVideo' && isVideoTooLong(node.dash_info))
  293. continue;
  294. if (node.id && utils_1.BigNumOps.compare(node.id, targetId) > 0)
  295. nodes.push(node);
  296. else
  297. return nodes;
  298. if (Number(targetId) < 1)
  299. return nodes;
  300. }
  301. if (!(pageInfo === null || pageInfo === void 0 ? void 0 : pageInfo.has_next_page))
  302. return nodes;
  303. logger.info('unable to find a smaller id than target, trying on next page...');
  304. url = graphqlLinkBuilder({ userId, after: pageInfo.end_cursor });
  305. timeout += nextPageDelay;
  306. return (0, util_1.promisify)(setTimeout)(nextPageDelay)
  307. .then(() => page.goto(url, { waitUntil: 'load', timeout: getTimeout() }))
  308. .then(responseHandler)
  309. .then(({ data }) => jsonHandler(data));
  310. };
  311. return responseHandler(response)
  312. .then(({ data }) => jsonHandler(data));
  313. }).catch((err) => {
  314. if (err.name === 'ResponseError' || err.name === 'TypeError') {
  315. logger.warn(`error while fetching posts by @${userName}: ${err}`);
  316. }
  317. else if (err.name === 'TimeoutError') {
  318. logger.warn(`navigation timed out at ${getTimerTime()} ms`);
  319. }
  320. else
  321. throw err;
  322. return [];
  323. }).then(nodes => (!fullName && nodes.length ?
  324. this.client.user.searchExact(nodes[0].owner.username) :
  325. Promise.resolve({ full_name: fullName })).then(({ full_name }) => (0, util_1.promisify)(setTimeout)(getTimeout()).then(() => nodes.map(node => {
  326. const item = graphNodeToMediaItem(node);
  327. item.user.full_name = full_name;
  328. return {
  329. pk: item.pk,
  330. item: () => Promise.resolve(item),
  331. };
  332. }))));
  333. })).finally(() => { page.close(); });
  334. });
  335. setTimeout(this.work, this.workInterval * 1000 / this.lock.feed.length);
  336. });
  337. };
  338. this.queryUser = (username) => this.client.user.searchExact(username)
  339. .catch((error) => {
  340. if (error instanceof instagram_private_api_1.IgLoginRequiredError || error instanceof instagram_private_api_1.IgCookieNotFoundError) {
  341. logger.warn('login required, logging in again...');
  342. return this.session.login().then(() => this.client.user.searchExact(username));
  343. }
  344. else
  345. throw error;
  346. })
  347. .then(user => `${user.username}:${user.pk}`);
  348. this.workOnMedia = (lazyMediaItems, sendMedia) => this.webshot(lazyMediaItems, sendMedia, this.webshotDelay);
  349. this.urlSegmentToId = urlSegmentToId;
  350. this.lazyGetMediaById = (id) => ({
  351. pk: id,
  352. item: () => this.client.media.info(id).then(media => {
  353. const mediaItem = media.items[0];
  354. logger.debug(`api returned media post ${JSON.stringify(mediaItem)} for query id=${id}`);
  355. return mediaItem;
  356. }),
  357. });
  358. this.sendMedia = (source, ...to) => (msg, text, author) => {
  359. to.forEach(subscriber => {
  360. logger.info(`pushing data${source ? ` of ${source}` : ''} to ${JSON.stringify(subscriber)}`);
  361. retryOnError(() => this.bot.sendTo(subscriber, msg), (_, count, terminate) => {
  362. if (count <= maxTrials) {
  363. logger.warn(`retry sending to ${subscriber.chatID} for the ${ordinal(count)} time...`);
  364. }
  365. else {
  366. logger.warn(`${count - 1} consecutive failures while sending message chain, trying plain text instead...`);
  367. terminate(this.bot.sendTo(subscriber, author + text, true));
  368. }
  369. });
  370. });
  371. };
  372. this.workOnFeed = (feed) => new Promise(resolve => {
  373. const match = /https:\/\/www\.instagram\.com\/([^\/]+)/.exec(feed);
  374. if (!match) {
  375. logger.error(`current feed "${feed}" is invalid, please remove this feed manually`);
  376. return resolve([]);
  377. }
  378. const userNameId = `${match[1]}:${this.lock.threads[feed].id}`;
  379. return resolve(this.queryUserMedia(userNameId, this.lock.threads[feed].offset)
  380. .catch((error) => {
  381. logger.error(`error scraping media off profile page of ${match[1]}, error: ${error}`);
  382. return [];
  383. }));
  384. }).then(mediaItems => {
  385. const currentThread = this.lock.threads[feed];
  386. const updateDate = () => currentThread.updatedAt = new Date().toString();
  387. if (!mediaItems || mediaItems.length === 0) {
  388. updateDate();
  389. return;
  390. }
  391. const topOfFeed = mediaItems[0].pk;
  392. const updateOffset = () => { currentThread.offset = topOfFeed; };
  393. if (currentThread.offset === '-1') {
  394. updateOffset();
  395. return;
  396. }
  397. if (currentThread.offset === '0')
  398. mediaItems.splice(1);
  399. return this.workOnMedia(mediaItems, this.sendMedia(`thread ${feed}`, ...currentThread.subscribers))
  400. .then(updateDate).then(updateOffset);
  401. });
  402. this.work = () => {
  403. const lock = this.lock;
  404. if (this.workInterval < 1)
  405. this.workInterval = 1;
  406. if (this.isInactiveTime || lock.feed.length === 0) {
  407. setTimeout(this.work, this.workInterval * 1000 / lock.feed.length);
  408. return;
  409. }
  410. lock.feed.forEach((feed, index) => {
  411. if (!lock.threads[feed] ||
  412. !lock.threads[feed].subscribers ||
  413. lock.threads[feed].subscribers.length === 0) {
  414. logger.warn(`nobody subscribes thread ${feed}, removing from feed`);
  415. delete lock.threads[index];
  416. lock.feed.splice(index, 1);
  417. fs.writeFileSync(path.resolve(this.lockfile), JSON.stringify(lock));
  418. }
  419. });
  420. const queuedFeeds = lock.feed.slice(0, (lock.workon + 1) || undefined).reverse();
  421. let logComplete = () => { };
  422. (0, utils_1.chainPromises)(utils_1.Arr.chunk(queuedFeeds, 5).map((arr, i) => () => Promise.all(arr.map((currentFeed, j) => {
  423. const promiseDelay = this.workInterval * (Math.random() + j + 10 - arr.length) * 125 / lock.feed.length;
  424. const wait = (ms) => isWaitingForLogin ? LoginAwaiter.awaiter : (0, util_1.promisify)(setTimeout)(ms);
  425. const startTime = new Date().getTime();
  426. const getTimerTime = () => new Date().getTime() - startTime;
  427. const workon = (queuedFeeds.length - 1) - (i * 5 + j);
  428. if (j === arr.length - 1) {
  429. logComplete = () => logger.info(`batch job #${workon}-${workon + j} completed after ${getTimerTime()} ms`);
  430. }
  431. const next = () => {
  432. lock.workon = workon - 1;
  433. fs.writeFileSync(path.resolve(this.lockfile), JSON.stringify(lock));
  434. };
  435. if (Date.now() - new Date(lock.threads[currentFeed].updatedAt).getTime() < 3600000) {
  436. logger.info(`skipped feed #${workon}: ${currentFeed}, last updated within an hour`);
  437. return wait(promiseDelay * 3).then(next);
  438. }
  439. return wait(promiseDelay * 3).then(() => {
  440. logger.info(`about to pull from feed #${workon}: ${currentFeed}`);
  441. return this.workOnFeed(currentFeed);
  442. }).then(next);
  443. })).then(logComplete))).then(this.work);
  444. };
  445. this.client = new instagram_private_api_1.IgApiClient();
  446. if (opt.proxyUrl) {
  447. try {
  448. const url = new URL(opt.proxyUrl);
  449. if (!/^socks(?:4a?|5h?)?:$/.test(url.protocol))
  450. throw Error();
  451. if (!url.port)
  452. url.port = '1080';
  453. this.client.request.defaults.agent = new socks_proxy_agent_1.SocksProxyAgent({
  454. hostname: url.hostname,
  455. port: url.port,
  456. userId: url.username,
  457. password: url.password,
  458. });
  459. }
  460. catch (e) {
  461. logger.warn(`invalid socks proxy url: ${opt.proxyUrl}, ignoring`);
  462. }
  463. }
  464. this.session = new SessionManager(this.client, opt.sessionLockfile, opt.credentials, opt.codeServicePort);
  465. this.lockfile = opt.lockfile;
  466. this.webshotCookiesLockfile = opt.webshotCookiesLockfile;
  467. this.lock = opt.lock;
  468. this.inactiveHours = opt.inactiveHours;
  469. this.workInterval = opt.workInterval;
  470. this.bot = opt.bot;
  471. this.webshotDelay = opt.webshotDelay;
  472. this.mode = opt.mode;
  473. this.wsUrl = opt.wsUrl;
  474. const cookiesFilePath = path.resolve(this.webshotCookiesLockfile);
  475. try {
  476. this.webshotCookies = JSON.parse(fs.readFileSync(cookiesFilePath, 'utf8'));
  477. logger.info(`loaded webshot cookies from file ${this.webshotCookiesLockfile}`);
  478. }
  479. catch (err) {
  480. logger.warn(`failed to load webshot cookies from file ${this.webshotCookiesLockfile}: `, err.message);
  481. logger.warn('cookies will be saved to this file when needed');
  482. }
  483. browserLogin = page => page.fill('input[name="username"]', opt.credentials[0], { timeout: 0 })
  484. .then(() => { LoginAwaiter.new(); logger.warn('blocked by login dialog, trying to log in manually...'); })
  485. .then(() => page.fill('input[name="password"]', opt.credentials[1], { timeout: 0 }))
  486. .then(() => page.click('button[type="submit"]', { timeout: 0 }))
  487. .then(() => (next => Promise.race([
  488. page.waitForSelector('#verificationCodeDescription', { timeout: 0 }).then(handle => handle.innerText()).then(text => {
  489. logger.info(`login is requesting two-factor authentication via ${/認証アプリ/.test(text) ? 'TOTP' : 'SMS'}`);
  490. return this.session.handle2FA(code => page.fill('input[name="verificationCode"]', code, { timeout: 0 }))
  491. .then(() => page.click('button:has-text("実行")', { timeout: 0 }))
  492. .then(next);
  493. }),
  494. next(),
  495. ]))(() => page.click('button:has-text("情報を保存")', { timeout: 0 }).then(LoginAwaiter.resolver)));
  496. browserAwaitLogin = page => LoginAwaiter.awaiter
  497. .then(() => { logger.warn('still waiting for login, pausing execution...'); return page.context(); })
  498. .then(ctx => ctx.clearCookies().then(() => ctx.addCookies(this.webshotCookies)))
  499. .then();
  500. browserSaveCookies = page => page.context().cookies()
  501. .then(cookies => {
  502. this.webshotCookies = cookies;
  503. logger.info('successfully logged in, saving cookies to file...');
  504. fs.writeFileSync(path.resolve(this.webshotCookiesLockfile), JSON.stringify(cookies, null, 2), 'utf-8');
  505. });
  506. exports.WebshotHelpers.handleLogin = page => isWaitingForLogin ? browserAwaitLogin(page) :
  507. browserLogin(page)
  508. .then(() => page.waitForSelector('img[data-testid="user-avatar"]', { timeout: this.webshotDelay }))
  509. .then(() => browserSaveCookies(page))
  510. .catch((err) => {
  511. if (err.name === 'TimeoutError') {
  512. logger.warn('navigation timed out, assuming login has failed');
  513. LoginAwaiter.resolver();
  514. }
  515. throw err;
  516. });
  517. ScreenNameNormalizer._queryUser = this.queryUser;
  518. const parseMediaError = (err) => {
  519. if (!(err instanceof instagram_private_api_1.IgResponseError && err.text === 'Media not found or unavailable')) {
  520. logger.warn(`error retrieving instagram media: ${err.message}`);
  521. return `获取媒体时出现错误:${err.message}`;
  522. }
  523. return '找不到请求的媒体,它可能已被删除。';
  524. };
  525. exports.getPostOwner = (segmentId) => this.client.media.info(urlSegmentToId(segmentId))
  526. .then(media => media.items[0].user)
  527. .then(user => `${user.username}:${user.pk}`)
  528. .catch((err) => { throw Error(parseMediaError(err)); });
  529. exports.sendPost = (segmentId, receiver) => {
  530. const lazyMedia = this.lazyGetMediaById(urlSegmentToId(segmentId));
  531. return lazyMedia.item().then(mediaItem => {
  532. const lock = this.lock;
  533. const feed = Object.keys(lock.threads).find(key => lock.threads[key].id === mediaItem.user.pk);
  534. if (lock.feed.includes(feed) && lock.threads[feed].offset < mediaItem.pk) {
  535. logger.info(`post is newer than last offset of thread (${(0, instagram_id_to_url_segment_1.instagramIdToUrlSegment)(lock.threads[feed].offset)}), updating...`);
  536. this.workOnFeed(feed);
  537. if (lock.threads[feed].subscribers.some(subscriber => subscriber.chatID.toString() === receiver.chatID.toString() &&
  538. subscriber.chatType === receiver.chatType))
  539. return logger.info(`receiver has already subscribed to feed ${feed}, not sending again`);
  540. }
  541. lazyMedia.item = () => Promise.resolve(mediaItem);
  542. this.workOnMedia([lazyMedia], this.sendMedia(`instagram media ${segmentId}`, receiver));
  543. }).catch((err) => {
  544. this.bot.sendTo(receiver, parseMediaError(err));
  545. if (err instanceof instagram_private_api_1.IgLoginRequiredError || err instanceof instagram_private_api_1.IgCookieNotFoundError) {
  546. logger.warn('login required, awaiting login...');
  547. this.bot.sendTo(receiver, '等待登录中,稍后会处理请求,请稍候……');
  548. return this.session.login().then(() => (0, exports.sendPost)(segmentId, receiver));
  549. }
  550. ;
  551. });
  552. };
  553. }
  554. get isInactiveTime() {
  555. const timeToEpoch = (h = 0, m = 0) => new Date().setHours(h, m, 0, 0);
  556. return this.inactiveHours
  557. .map(rangeStr => ((start, end) => ({ start, end }))(...rangeStr.split('-', 2).map(timeStr => timeToEpoch(...timeStr.split(':', 2).map(Number)))))
  558. .some(range => (now => now >= range.start && now < range.end)(Date.now()));
  559. }
  560. }
  561. exports.default = default_1;