twitter.ts 26 KB

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