twitter.ts 26 KB

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