twitter.js 27 KB

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