twitter.js 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489
  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. 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 isValidUrlSegment = (input) => /^[A-Za-z0-9\-_]+$/.test(input);
  39. exports.isValidUrlSegment = isValidUrlSegment;
  40. const linkBuilder = (config) => {
  41. if (config.userName)
  42. return `https://www.instagram.com/${config.userName}/`;
  43. if (config.postUrlSegment)
  44. return `https://www.instagram.com/p/${config.postUrlSegment}/`;
  45. };
  46. exports.linkBuilder = linkBuilder;
  47. const urlSegmentToId = (urlSegment) => urlSegment.length <= 28 ?
  48. instagram_id_to_url_segment_1.urlSegmentToInstagramId(urlSegment) : 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. 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 } = 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:has-text("すべて許可")', { 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 logger = loggers_1.getLogger('instagram');
  168. const maxTrials = 3;
  169. const retryInterval = 1500;
  170. const ordinal = (n) => {
  171. switch ((Math.trunc(n / 10) % 10 === 1) ? 0 : n % 10) {
  172. case 1:
  173. return `${n}st`;
  174. case 2:
  175. return `${n}nd`;
  176. case 3:
  177. return `${n}rd`;
  178. default:
  179. return `${n}th`;
  180. }
  181. };
  182. const retryOnError = (doWork, onRetry) => new Promise(resolve => {
  183. const retry = (reason, count) => {
  184. setTimeout(() => {
  185. let terminate = false;
  186. onRetry(reason, count, defaultValue => { terminate = true; resolve(defaultValue); });
  187. if (!terminate)
  188. doWork().then(resolve).catch(error => retry(error, count + 1));
  189. }, retryInterval);
  190. };
  191. doWork().then(resolve).catch(error => retry(error, 1));
  192. });
  193. class default_1 {
  194. constructor(opt) {
  195. this.webshotCookies = [];
  196. this.launch = () => {
  197. this.webshot = new webshot_1.default(this.wsUrl, this.mode, () => this.webshotCookies, doOnNewPage => {
  198. this.queryUserMedia = ((userName, targetId) => {
  199. let page;
  200. const url = linkBuilder({ userName });
  201. logger.debug(`pulling ${targetId !== '0' ? `feed ${url} up to ${targetId}` : `top of feed ${url}`}...`);
  202. return doOnNewPage(newPage => {
  203. page = newPage;
  204. let timeout = this.webshotDelay;
  205. const startTime = new Date().getTime();
  206. const getTimerTime = () => new Date().getTime() - startTime;
  207. const getTimeout = () => isWaitingForLogin ? 0 : Math.max(90000, timeout - getTimerTime());
  208. return page.context().addCookies(this.webshotCookies)
  209. .then(() => page.goto(url, { waitUntil: 'load', timeout: getTimeout() }))
  210. .then(response => {
  211. if (response.status() !== 200) {
  212. const err = new Error(`error navigating to user page, error was: ${response.status()} ${response.statusText()}`);
  213. throw Object.defineProperty(err, 'name', {
  214. value: 'ResponseError',
  215. });
  216. }
  217. }).then(() => acceptCookieConsent(page))
  218. .then(() => (next => Promise.race([
  219. browserLogin(page)
  220. .catch((err) => {
  221. if (err.name === 'TimeoutError') {
  222. logger.warn('navigation timed out, assuming login has failed');
  223. isWaitingForLogin = false;
  224. }
  225. throw err;
  226. })
  227. .then(() => browserSaveCookies(page))
  228. .then(() => page.goto(url)).then(next),
  229. next(),
  230. ]))(() => util_1.promisify(setTimeout)(2000).then(() => page.waitForSelector('article', { timeout: getTimeout() })))).then(handle => {
  231. const postHandler = () => {
  232. const toId = (href) => { var _a; return urlSegmentToId(((_a = /\/p\/(.*)\/$/.exec(href)) !== null && _a !== void 0 ? _a : [, ''])[1]); };
  233. if (targetId === '0') {
  234. return handle.$$eval('a', as => as.filter(a => !a.querySelector('[aria-label="IGTV"]'))[0].href).then(href => Number(toId(href)) > 0 ? [toId(href)] : []);
  235. }
  236. return handle.$$eval('a', as => as.filter(a => !a.querySelector('[aria-label="IGTV"]')).map(a => a.href)).then(hrefs => {
  237. let id;
  238. const itemIds = [];
  239. for (const href of hrefs) {
  240. id = toId(href);
  241. if (id && utils_1.BigNumOps.compare(id, targetId) > 0)
  242. itemIds.push(id);
  243. else
  244. return itemIds;
  245. }
  246. logger.info('unable to find a smaller id than target, trying on next page...');
  247. return null;
  248. });
  249. };
  250. return postHandler().then(itemIds => {
  251. if (itemIds)
  252. return itemIds;
  253. timeout += this.workInterval * 500;
  254. return handle.$$('a')
  255. .then(as => { as.pop().scrollIntoViewIfNeeded(); return as.length + 1; })
  256. .then(loadedCount => page.waitForFunction(count => document.querySelectorAll('article a').length > count, loadedCount))
  257. .then(postHandler);
  258. });
  259. }).catch((err) => {
  260. if (err.name !== 'TimeoutError' && err.name !== 'ResponseError')
  261. throw err;
  262. if (err.name === 'ResponseError') {
  263. logger.warn(`error while fetching tweets for ${userName}: ${err.message}`);
  264. }
  265. else
  266. logger.warn(`navigation timed out at ${getTimerTime()} ms`);
  267. return [];
  268. }).then(itemIds => util_1.promisify(setTimeout)(getTimeout()).then(() => itemIds.map(id => this.lazyGetMediaById(id))));
  269. }).finally(() => { page.close(); });
  270. });
  271. setTimeout(this.work, this.workInterval * 1000 / this.lock.feed.length);
  272. });
  273. };
  274. this.queryUser = (username) => this.client.user.searchExact(username)
  275. .then(user => `${user.username}:${user.pk}`);
  276. this.workOnMedia = (lazyMediaItems, sendMedia) => this.webshot(lazyMediaItems, sendMedia, this.webshotDelay);
  277. this.urlSegmentToId = urlSegmentToId;
  278. this.lazyGetMediaById = (id) => ({
  279. pk: id,
  280. item: () => this.client.media.info(id).then(media => {
  281. const mediaItem = media.items[0];
  282. logger.debug(`api returned media post ${JSON.stringify(mediaItem)} for query id=${id}`);
  283. return mediaItem;
  284. }),
  285. });
  286. this.sendMedia = (source, ...to) => (msg, text, author) => {
  287. to.forEach(subscriber => {
  288. logger.info(`pushing data${source ? ` of ${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 message chain, trying plain text instead...`);
  295. terminate(this.bot.sendTo(subscriber, author + text, true));
  296. }
  297. });
  298. });
  299. };
  300. this.workOnFeed = (feed) => new Promise(resolve => {
  301. const match = /https:\/\/www\.instagram\.com\/([^\/]+)/.exec(feed);
  302. if (!match) {
  303. logger.error(`current feed "${feed}" is invalid, please remove this feed manually`);
  304. return resolve([]);
  305. }
  306. return resolve(this.queryUserMedia(match[1], this.lock.threads[feed].offset)
  307. .catch((error) => {
  308. logger.error(`error scraping media off profile page of ${match[1]}, error: ${error}`);
  309. return [];
  310. }));
  311. }).then(mediaItems => {
  312. const currentThread = this.lock.threads[feed];
  313. const updateDate = () => currentThread.updatedAt = new Date().toString();
  314. if (!mediaItems || mediaItems.length === 0) {
  315. updateDate();
  316. return;
  317. }
  318. const topOfFeed = mediaItems[0].pk;
  319. const updateOffset = () => { currentThread.offset = topOfFeed; };
  320. if (currentThread.offset === '-1') {
  321. updateOffset();
  322. return;
  323. }
  324. if (currentThread.offset === '0')
  325. mediaItems.splice(1);
  326. return this.workOnMedia(mediaItems, this.sendMedia(`thread ${feed}`, ...currentThread.subscribers))
  327. .then(updateDate).then(updateOffset);
  328. });
  329. this.work = () => {
  330. const lock = this.lock;
  331. if (this.workInterval < 1)
  332. this.workInterval = 1;
  333. if (this.isInactiveTime || lock.feed.length === 0) {
  334. setTimeout(this.work, this.workInterval * 1000 / lock.feed.length);
  335. return;
  336. }
  337. lock.feed.forEach((feed, index) => {
  338. if (!lock.threads[feed] ||
  339. !lock.threads[feed].subscribers ||
  340. lock.threads[feed].subscribers.length === 0) {
  341. logger.warn(`nobody subscribes thread ${feed}, removing from feed`);
  342. delete lock.threads[index];
  343. lock.feed.splice(index, 1);
  344. fs.writeFileSync(path.resolve(this.lockfile), JSON.stringify(lock));
  345. }
  346. });
  347. const queuedFeeds = lock.feed.slice(0, lock.workon + 1).reverse();
  348. utils_1.chainPromises(utils_1.Arr.chunk(queuedFeeds, 5).map((arr, i) => () => Promise.all(arr.map((currentFeed, j) => {
  349. if (Date.now() - new Date(lock.threads[currentFeed].updatedAt).getTime() > 3600000)
  350. return;
  351. const workon = (queuedFeeds.length - 1) - (i * 5 + j);
  352. fs.writeFileSync(path.resolve(this.lockfile), JSON.stringify(lock));
  353. const promiseDelay = this.workInterval * (Math.random() + j) * 500 / lock.feed.length;
  354. const startTime = new Date().getTime();
  355. const getTimerTime = () => new Date().getTime() - startTime;
  356. const promise = util_1.promisify(setTimeout)(promiseDelay).then(() => {
  357. logger.info(`about to pull from feed #${workon}: ${currentFeed}`);
  358. if (j === arr.length - 1)
  359. logger.info(`timeout for this batch job: ${Math.trunc(promiseDelay * 2)} ms`);
  360. return this.workOnFeed(currentFeed);
  361. }).then(() => {
  362. lock.workon = (workon || lock.feed.length) - 1;
  363. if (j === arr.length - 1) {
  364. logger.info(`batch job #${workon}-${workon + j} completed after ${getTimerTime()} ms`);
  365. }
  366. fs.writeFileSync(path.resolve(this.lockfile), JSON.stringify(lock));
  367. });
  368. return Promise.race([promise, isWaitingForLogin ? utils_1.neverResolves() : util_1.promisify(setTimeout)(promiseDelay * 3)]);
  369. }))))
  370. .then(() => {
  371. let timeout = this.workInterval * 500;
  372. if (timeout < 1000)
  373. timeout = 1000;
  374. fs.writeFileSync(path.resolve(this.lockfile), JSON.stringify(lock));
  375. setTimeout(() => {
  376. this.work();
  377. }, timeout);
  378. });
  379. };
  380. this.client = new instagram_private_api_1.IgApiClient();
  381. if (opt.proxyUrl) {
  382. try {
  383. const url = new URL(opt.proxyUrl);
  384. if (!/^socks(?:4a?|5h?)?:$/.test(url.protocol))
  385. throw Error();
  386. if (!url.port)
  387. url.port = '1080';
  388. this.client.request.defaults.agent = new socks_proxy_agent_1.SocksProxyAgent({
  389. hostname: url.hostname,
  390. port: url.port,
  391. userId: url.username,
  392. password: url.password,
  393. });
  394. }
  395. catch (e) {
  396. logger.warn(`invalid socks proxy url: ${opt.proxyUrl}, ignoring`);
  397. }
  398. }
  399. this.session = new SessionManager(this.client, opt.sessionLockfile, opt.credentials, opt.codeServicePort);
  400. this.lockfile = opt.lockfile;
  401. this.webshotCookiesLockfile = opt.webshotCookiesLockfile;
  402. this.lock = opt.lock;
  403. this.inactiveHours = opt.inactiveHours;
  404. this.workInterval = opt.workInterval;
  405. this.bot = opt.bot;
  406. this.webshotDelay = opt.webshotDelay;
  407. this.mode = opt.mode;
  408. this.wsUrl = opt.wsUrl;
  409. const cookiesFilePath = path.resolve(this.webshotCookiesLockfile);
  410. try {
  411. this.webshotCookies = JSON.parse(fs.readFileSync(cookiesFilePath, 'utf8'));
  412. logger.info(`loaded webshot cookies from file ${this.webshotCookiesLockfile}`);
  413. }
  414. catch (err) {
  415. logger.warn(`failed to load webshot cookies from file ${this.webshotCookiesLockfile}: `, err.message);
  416. logger.warn('cookies will be saved to this file when needed');
  417. }
  418. browserLogin = page => page.fill('input[name="username"]', opt.credentials[0], { timeout: 0 })
  419. .then(() => {
  420. if (isWaitingForLogin !== true)
  421. return;
  422. logger.warn('still waiting for login, pausing execution...');
  423. return utils_1.neverResolves();
  424. })
  425. .then(() => { isWaitingForLogin = true; logger.warn('blocked by login dialog, trying to log in manually...'); })
  426. .then(() => page.fill('input[name="password"]', opt.credentials[1], { timeout: 0 }))
  427. .then(() => page.click('button[type="submit"]', { timeout: 0 }))
  428. .then(() => (next => Promise.race([
  429. page.waitForSelector('#verificationCodeDescription', { timeout: 0 }).then(handle => handle.innerText()).then(text => {
  430. logger.info(`login is requesting two-factor authentication via ${/認証アプリ/.test(text) ? 'TOTP' : 'SMS'}`);
  431. return this.session.handle2FA(code => page.fill('input[name="verificationCode"]', code, { timeout: 0 }))
  432. .then(() => page.click('button:has-text("実行")', { timeout: 0 }))
  433. .then(next);
  434. }),
  435. next(),
  436. ]))(() => page.click('button:has-text("情報を保存")', { timeout: 0 }).then(() => { isWaitingForLogin = false; })));
  437. browserSaveCookies = page => page.context().cookies()
  438. .then(cookies => {
  439. this.webshotCookies = cookies;
  440. logger.info('successfully logged in, saving cookies to file...');
  441. fs.writeFileSync(path.resolve(this.webshotCookiesLockfile), JSON.stringify(cookies, null, 2), 'utf-8');
  442. });
  443. exports.WebshotHelpers.handleLogin = page => browserLogin(page)
  444. .then(() => page.waitForSelector('img[data-testid="user-avatar"]', { timeout: this.webshotDelay }))
  445. .then(() => browserSaveCookies(page))
  446. .catch((err) => {
  447. if (err.name === 'TimeoutError') {
  448. logger.warn('navigation timed out, assuming login has failed');
  449. isWaitingForLogin = false;
  450. }
  451. throw err;
  452. });
  453. ScreenNameNormalizer._queryUser = this.queryUser;
  454. const parseMediaError = (err) => {
  455. if (!(err instanceof instagram_private_api_1.IgResponseError && err.text === 'Media not found or unavailable')) {
  456. logger.warn(`error retrieving instagram media: ${err.message}`);
  457. return `获取媒体时出现错误:${err.message}`;
  458. }
  459. return '找不到请求的媒体,它可能已被删除。';
  460. };
  461. exports.getPostOwner = (segmentId) => this.client.media.info(urlSegmentToId(segmentId))
  462. .then(media => media.items[0].user)
  463. .then(user => `${user.username}:${user.pk}`)
  464. .catch((err) => { throw Error(parseMediaError(err)); });
  465. exports.sendPost = (segmentId, receiver) => {
  466. const lazyMedia = this.lazyGetMediaById(urlSegmentToId(segmentId));
  467. return lazyMedia.item().then(mediaItem => {
  468. const lock = this.lock;
  469. const feed = linkBuilder({ userName: mediaItem.user.username });
  470. if (lock.feed.includes(feed) && lock.threads[feed].offset < mediaItem.pk) {
  471. logger.info(`post is newer than last offset of thread (${instagram_id_to_url_segment_1.instagramIdToUrlSegment(lock.threads[feed].offset)}), updating...`);
  472. this.workOnFeed(feed);
  473. if (lock.threads[feed].subscribers.some(subscriber => subscriber.chatID.toString() === receiver.chatID.toString() &&
  474. subscriber.chatType === receiver.chatType))
  475. return logger.info(`receiver has already subscribed to feed ${feed}, not sending again`);
  476. }
  477. lazyMedia.item = () => Promise.resolve(mediaItem);
  478. this.workOnMedia([lazyMedia], this.sendMedia(`instagram media ${segmentId}`, receiver));
  479. }).catch((err) => { this.bot.sendTo(receiver, parseMediaError(err)); });
  480. };
  481. }
  482. get isInactiveTime() {
  483. const timeToEpoch = (h = 0, m = 0) => new Date().setHours(h, m, 0, 0);
  484. return this.inactiveHours
  485. .map(rangeStr => ((start, end) => ({ start, end }))(...rangeStr.split('-', 2).map(timeStr => timeToEpoch(...timeStr.split(':', 2).map(Number)))))
  486. .some(range => (now => now >= range.start && now < range.end)(Date.now()));
  487. }
  488. }
  489. exports.default = default_1;