twitter.js 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523
  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.sendAllStories = exports.sendStory = exports.sendTimeline = exports.ScreenNameNormalizer = exports.SessionManager = 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_private_api_1 = require("instagram-private-api");
  20. const socks_proxy_agent_1 = require("socks-proxy-agent");
  21. const datetime_1 = require("./datetime");
  22. const loggers_1 = require("./loggers");
  23. const utils_1 = require("./utils");
  24. const webshot_1 = require("./webshot");
  25. const parseLink = (link) => {
  26. let match = /instagram\.com\/stories\/([^\/?#]+)\/(\d+)/.exec(link);
  27. if (match)
  28. return { userName: ScreenNameNormalizer.normalize(match[1]).split(':')[0], storyId: match[2] };
  29. match =
  30. /instagram\.com\/([^\/?#]+)/.exec(link) ||
  31. /^([^\/?#]+)$/.exec(link);
  32. if (match)
  33. return { userName: ScreenNameNormalizer.normalize(match[1]).split(':')[0] };
  34. return;
  35. };
  36. exports.parseLink = parseLink;
  37. const linkBuilder = (config) => {
  38. if (!config.userName)
  39. return;
  40. if (!config.storyId)
  41. return `https://www.instagram.com/${config.userName}/`;
  42. return `https://www.instagram.com/stories/${config.userName}/${config.storyId}/`;
  43. };
  44. exports.linkBuilder = linkBuilder;
  45. class SessionManager {
  46. constructor(client, file, credentials, codeServicePort) {
  47. this.init = () => {
  48. this.ig.state.generateDevice(this.username);
  49. this.ig.request.end$.subscribe(() => { this.save(); });
  50. const filePath = path.resolve(this.lockfile);
  51. if (fs.existsSync(filePath)) {
  52. try {
  53. const serialized = JSON.parse(fs.readFileSync(filePath, 'utf8'));
  54. return this.ig.state.deserialize(serialized).then(() => {
  55. logger.info(`successfully loaded client session cookies for user ${this.username}`);
  56. });
  57. }
  58. catch (err) {
  59. logger.error(`failed to load client session cookies from file ${this.lockfile}: `, err);
  60. return Promise.resolve();
  61. }
  62. }
  63. else {
  64. return this.login().catch((err) => {
  65. logger.error(`error while trying to log in as user ${this.username}, error: ${err}`);
  66. logger.warn('attempting to retry after 1 minute...');
  67. if (fs.existsSync(filePath))
  68. fs.unlinkSync(filePath);
  69. util_1.promisify(setTimeout)(60000).then(this.init);
  70. });
  71. }
  72. };
  73. this.handle2FA = (submitter) => new Promise((resolve, reject) => {
  74. const token = crypto.randomBytes(20).toString('hex');
  75. logger.info('please submit the code with a one-time token from your browser with this path:');
  76. logger.info(`/confirm-2fa?code=<the code you received>&token=${token}`);
  77. let working;
  78. const server = http.createServer((req, res) => {
  79. const { pathname, query } = url_1.parse(req.url, true);
  80. if (!working && pathname === '/confirm-2fa' && query.token === token &&
  81. typeof (query.code) === 'string' && /^\d{6}$/.test(query.code)) {
  82. const code = query.code;
  83. logger.debug(`received code: ${code}`);
  84. working = true;
  85. submitter(code)
  86. .then(response => { res.write('OK'); res.end(); server.close(() => resolve(response)); })
  87. .catch(err => { res.write('Error'); res.end(); reject(err); })
  88. .finally(() => { working = false; });
  89. }
  90. });
  91. server.listen(this.codeServicePort);
  92. });
  93. this.login = () => this.ig.simulate.preLoginFlow()
  94. .then(() => this.ig.account.login(this.username, this.password))
  95. .catch((err) => {
  96. if (err instanceof instagram_private_api_1.IgLoginTwoFactorRequiredError) {
  97. const { two_factor_identifier, totp_two_factor_on } = err.response.body.two_factor_info;
  98. logger.debug(`2FA info: ${JSON.stringify(err.response.body.two_factor_info)}`);
  99. logger.info(`login is requesting two-factor authentication via ${totp_two_factor_on ? 'TOTP' : 'SMS'}`);
  100. return this.handle2FA(code => this.ig.account.twoFactorLogin({
  101. username: this.username,
  102. verificationCode: code,
  103. twoFactorIdentifier: two_factor_identifier,
  104. verificationMethod: totp_two_factor_on ? '0' : '1',
  105. }));
  106. }
  107. throw err;
  108. })
  109. .then(user => new Promise(resolve => {
  110. logger.info(`successfully logged in as ${this.username}`);
  111. process.nextTick(() => resolve(this.ig.simulate.postLoginFlow().then(() => user)));
  112. }));
  113. this.save = () => this.ig.state.serialize()
  114. .then((serialized) => {
  115. delete serialized.constants;
  116. return fs.writeFileSync(path.resolve(this.lockfile), JSON.stringify(serialized, null, 2), 'utf-8');
  117. });
  118. this.ig = client;
  119. this.lockfile = file;
  120. [this.username, this.password] = credentials;
  121. this.codeServicePort = codeServicePort;
  122. }
  123. }
  124. exports.SessionManager = SessionManager;
  125. class ScreenNameNormalizer {
  126. static normalizeLive(username) {
  127. return __awaiter(this, void 0, void 0, function* () {
  128. if (this._queryUser) {
  129. return yield this._queryUser(username)
  130. .catch((err) => {
  131. if (!(err instanceof instagram_private_api_1.IgExactUserNotFoundError)) {
  132. logger.warn(`error looking up user: ${err.message}`);
  133. return `${username}:`;
  134. }
  135. return null;
  136. });
  137. }
  138. return this.normalize(username);
  139. });
  140. }
  141. }
  142. exports.ScreenNameNormalizer = ScreenNameNormalizer;
  143. ScreenNameNormalizer.normalize = (username) => `${username.toLowerCase().replace(/^@/, '')}:`;
  144. let sendTimeline = (username, receiver) => {
  145. throw Error();
  146. };
  147. exports.sendTimeline = sendTimeline;
  148. let sendStory = (username, storyId, receiver) => {
  149. throw Error();
  150. };
  151. exports.sendStory = sendStory;
  152. let sendAllStories = (username, receiver, startIndex, count) => {
  153. throw Error();
  154. };
  155. exports.sendAllStories = sendAllStories;
  156. const logger = loggers_1.getLogger('instagram');
  157. const maxTrials = 3;
  158. const retryInterval = 1500;
  159. const ordinal = (n) => {
  160. switch ((Math.trunc(n / 10) % 10 === 1) ? 0 : n % 10) {
  161. case 1:
  162. return `${n}st`;
  163. case 2:
  164. return `${n}nd`;
  165. case 3:
  166. return `${n}rd`;
  167. default:
  168. return `${n}th`;
  169. }
  170. };
  171. const retryOnError = (doWork, onRetry) => new Promise(resolve => {
  172. const retry = (reason, count) => {
  173. setTimeout(() => {
  174. let terminate = false;
  175. onRetry(reason, count, defaultValue => { terminate = true; resolve(defaultValue); });
  176. if (!terminate)
  177. doWork().then(resolve).catch(error => retry(error, count + 1));
  178. }, retryInterval);
  179. };
  180. doWork().then(resolve).catch(error => retry(error, 1));
  181. });
  182. class default_1 {
  183. constructor(opt) {
  184. this.launch = () => {
  185. this.webshot = new webshot_1.default(this.wsUrl, this.mode, () => {
  186. setTimeout(this.workForAll, this.workInterval * 1000 / this.lock.feed.length);
  187. setTimeout(() => {
  188. this.work();
  189. setInterval(() => { this.pullOrders = utils_1.Arr.shuffle(this.pullOrders); }, 21600000);
  190. setInterval(this.workForAll, this.workInterval * 1000);
  191. }, this.workInterval * 1200 / this.lock.feed.length);
  192. });
  193. };
  194. this.queryUserObject = (userName) => this.client.user.searchExact(userName)
  195. .catch((error) => {
  196. if (error instanceof instagram_private_api_1.IgLoginRequiredError || error instanceof instagram_private_api_1.IgCookieNotFoundError) {
  197. logger.warn('login required, logging in again...');
  198. return this.session.login().then(() => this.client.user.searchExact(userName));
  199. }
  200. else
  201. throw error;
  202. });
  203. this.queryUser = (rawUserName) => {
  204. const username = ScreenNameNormalizer.normalize(rawUserName).split(':')[0];
  205. for (const { user } of Object.values(this.cache)) {
  206. if (user.username === username)
  207. return Promise.resolve(`${username}:${user.pk}`);
  208. }
  209. return this.queryUserObject(username)
  210. .then(({ pk, username, full_name }) => {
  211. this.cache[pk] = { user: { pk, username, full_name }, stories: {}, pullOrder: 0 };
  212. fs.writeFileSync(path.resolve(this.cachefile), JSON.stringify(this.cache));
  213. logger.info(`initialized cache item for user ${full_name} (@${username})`);
  214. return `${username}:${pk}`;
  215. });
  216. };
  217. this.workOnMedia = (mediaItems, sendMedia) => Promise.resolve(mediaItems.forEach(({ msgs, text, author }) => sendMedia(msgs, text, author)));
  218. this.sendStories = (source, ...to) => (msg, text, author) => {
  219. to.forEach(subscriber => {
  220. logger.info(`pushing data${source ? ` of ${source}` : ''} to ${JSON.stringify(subscriber)}`);
  221. retryOnError(() => this.bot.sendTo(subscriber, msg), (_, count, terminate) => {
  222. if (count <= maxTrials) {
  223. logger.warn(`retry sending to ${subscriber.chatID} for the ${ordinal(count)} time...`);
  224. }
  225. else {
  226. logger.warn(`${count - 1} consecutive failures while sending message chain, trying plain text instead...`);
  227. terminate(this.bot.sendTo(subscriber, author + text, true));
  228. }
  229. });
  230. });
  231. };
  232. this.workForAll = () => {
  233. if (this.isInactiveTime)
  234. return;
  235. logger.debug(`current cache: ${JSON.stringify(this.cache)}`);
  236. utils_1.chainPromises(Object.entries(this.lock.threads).map(([feed, thread]) => () => {
  237. const id = thread.id;
  238. const userName = parseLink(feed).userName;
  239. logger.debug(`preparing to add user @${userName} to next pull task...`);
  240. if (id in this.cache) {
  241. const item = this.cache[id];
  242. if (item.pullOrder === 0)
  243. item.pullOrder = -1;
  244. return Promise.resolve();
  245. }
  246. return util_1.promisify(setTimeout)((Math.random() * 2 + 1) * 5000).then(() => this.client.user.info(id).then(({ pk, username, full_name }) => {
  247. this.cache[id] = { user: { pk, username, full_name }, stories: {}, pullOrder: -1 };
  248. fs.writeFileSync(path.resolve(this.cachefile), JSON.stringify(this.cache));
  249. logger.info(`initialized cache item for user ${full_name} (@${username})`);
  250. }));
  251. }))
  252. .then(() => {
  253. const userIdCache = Object.values(this.cache).some(item => item.pullOrder < 0) ?
  254. this.pullOrders = utils_1.Arr.shuffle(Object.keys(this.cache)).map(Number) :
  255. this.pullOrders;
  256. return utils_1.chainPromises(utils_1.Arr.chunk(userIdCache, 20).map(userIds => () => {
  257. logger.info(`pulling stories from users:${userIds.map(id => ` @${this.cache[id].user.username}`)}`);
  258. return this.client.feed.reelsMedia({ userIds }).request()
  259. .then(({ reels }) => utils_1.chainPromises(Object.keys(reels).map(userId => this.cache[userId]).map(cacheItem => () => this.queryUserObject(cacheItem.user.username)
  260. .catch((error) => {
  261. if (error instanceof instagram_private_api_1.IgExactUserNotFoundError) {
  262. return this.client.user.info(cacheItem.user.pk)
  263. .then(({ username, full_name }) => {
  264. cacheItem.user.username = username;
  265. cacheItem.user.full_name = full_name;
  266. });
  267. }
  268. }).finally(() => Promise.all(reels[cacheItem.user.pk].items
  269. .filter(item => !(item.pk in cacheItem.stories))
  270. .map(item => this.webshot([Object.assign(Object.assign({}, item), { user: cacheItem.user })], (msgs, text, author) => cacheItem.stories[item.pk] = { pk: item.pk, msgs, text, author, original: item }, this.webshotDelay)))))))
  271. .finally(() => {
  272. fs.writeFileSync(path.resolve(this.cachefile), JSON.stringify(this.cache));
  273. Object.values(this.lock.threads).forEach(thread => {
  274. if (userIds.includes(thread.id)) {
  275. thread.updatedAt = this.cache[thread.id].updated = Date();
  276. }
  277. });
  278. });
  279. }), (lp1, lp2) => () => lp1().then(() => util_1.promisify(setTimeout)(this.workInterval * 1000 / this.lock.feed.length).then(lp2)));
  280. })
  281. .catch((error) => {
  282. if (error instanceof instagram_private_api_1.IgNetworkError) {
  283. if (error.cause.message === "Unexpected '<'") {
  284. logger.warn('login required, logging in again...');
  285. return this.session.login().then(this.workForAll);
  286. }
  287. logger.warn(`error while fetching stories for all: ${JSON.stringify(error.cause)}`);
  288. }
  289. else if (error instanceof instagram_private_api_1.IgLoginRequiredError || error instanceof instagram_private_api_1.IgCookieNotFoundError) {
  290. logger.warn('login required, logging in again...');
  291. this.session.login().then(this.workForAll);
  292. }
  293. else {
  294. logger.error(`unhandled error on fetching media for all: ${error}`);
  295. }
  296. });
  297. };
  298. this.work = () => {
  299. const lock = this.lock;
  300. if (this.workInterval < 1)
  301. this.workInterval = 1;
  302. if (this.isInactiveTime || lock.feed.length === 0) {
  303. setTimeout(() => {
  304. this.workForAll();
  305. setTimeout(this.work, this.workInterval * 200);
  306. }, this.workInterval * 1000 / lock.feed.length);
  307. return;
  308. }
  309. if (lock.workon >= lock.feed.length)
  310. lock.workon = 0;
  311. const currentFeed = lock.feed[lock.workon];
  312. if (!lock.threads[currentFeed] ||
  313. !lock.threads[currentFeed].subscribers ||
  314. lock.threads[currentFeed].subscribers.length === 0) {
  315. logger.warn(`nobody subscribes thread ${currentFeed}, removing from feed`);
  316. delete lock.threads[currentFeed];
  317. (this.cache[parseLink(currentFeed).userName] || {}).pullOrder = 0;
  318. lock.feed.splice(lock.workon, 1);
  319. fs.writeFileSync(path.resolve(this.lockfile), JSON.stringify(lock));
  320. this.work();
  321. return;
  322. }
  323. logger.debug(`searching for new items from ${currentFeed} in cache`);
  324. const match = /https:\/\/www\.instagram\.com\/([^\/]+)/.exec(currentFeed);
  325. if (!match) {
  326. logger.error(`current feed "${currentFeed}" is invalid, please remove this feed manually`);
  327. lock.workon++;
  328. setTimeout(this.work, this.workInterval * 1000 / lock.feed.length);
  329. return;
  330. }
  331. const cachedFeed = this.cache[lock.threads[currentFeed].id];
  332. if (!cachedFeed) {
  333. setTimeout(this.work, this.workInterval * 1000 / lock.feed.length);
  334. return;
  335. }
  336. const newer = (item) => utils_1.BigNumOps.compare(item.pk, lock.threads[currentFeed].offset) > 0;
  337. const promise = Promise.resolve(Object.values(cachedFeed.stories)
  338. .filter(newer)
  339. .sort((i1, i2) => utils_1.BigNumOps.compare(i2.pk, i1.pk))
  340. .slice(-5));
  341. promise.then((mediaItems) => {
  342. const currentThread = lock.threads[currentFeed];
  343. if (!mediaItems || mediaItems.length === 0)
  344. return;
  345. const question = mediaItems.find(story => story.original.story_questions);
  346. const topOfFeed = question ? question.pk : mediaItems[0].pk;
  347. const updateOffset = () => currentThread.offset = topOfFeed;
  348. if (currentThread.offset === '-1') {
  349. updateOffset();
  350. return;
  351. }
  352. if (currentThread.offset === '0')
  353. mediaItems.splice(1);
  354. return this.workOnMedia(mediaItems.reverse(), this.sendStories(`thread ${currentFeed}`, ...currentThread.subscribers))
  355. .then(updateOffset)
  356. .then(() => {
  357. if (question) {
  358. currentThread.subscribers.forEach(subscriber => {
  359. const username = cachedFeed.user.username;
  360. const author = `${cachedFeed.user.full_name} (@${username}) `;
  361. this.bot.sendTo(subscriber, `请注意,用户${author}已开启问答互动。需退订请回复:/igstory_unsub ${username}${Object.keys(cachedFeed.stories).some(id => id > topOfFeed) ?
  362. `\n本次推送已截止于此条动态,下次推送在 ${Math.floor(this.workInterval / lock.feed.length)} 秒后。` : ''}`);
  363. });
  364. }
  365. });
  366. })
  367. .then(() => {
  368. lock.workon++;
  369. let timeout = this.workInterval * 1000 / lock.feed.length;
  370. if (timeout < 1000)
  371. timeout = 1000;
  372. fs.writeFileSync(path.resolve(this.lockfile), JSON.stringify(lock));
  373. setTimeout(this.work, timeout);
  374. });
  375. };
  376. this.client = new instagram_private_api_1.IgApiClient();
  377. if (opt.proxyUrl) {
  378. try {
  379. const url = new URL(opt.proxyUrl);
  380. if (!/^socks(?:4a?|5h?)?:$/.test(url.protocol))
  381. throw Error();
  382. if (!url.port)
  383. url.port = '1080';
  384. this.client.request.defaults.agent = new socks_proxy_agent_1.SocksProxyAgent({
  385. hostname: url.hostname,
  386. port: url.port,
  387. userId: url.username,
  388. password: url.password,
  389. });
  390. }
  391. catch (e) {
  392. logger.warn(`invalid socks proxy url: ${opt.proxyUrl}, ignoring`);
  393. }
  394. }
  395. this.session = new SessionManager(this.client, opt.sessionLockfile, opt.credentials, opt.codeServicePort);
  396. this.lockfile = opt.lockfile;
  397. this.lock = opt.lock;
  398. this.cachefile = opt.cachefile;
  399. this.cache = opt.cache;
  400. this.inactiveHours = opt.inactiveHours;
  401. this.workInterval = opt.workInterval;
  402. this.bot = opt.bot;
  403. this.webshotDelay = opt.webshotDelay;
  404. this.mode = opt.mode;
  405. this.wsUrl = opt.wsUrl;
  406. const workNow = (config) => {
  407. const { action, retryAction, reply, rawUserName } = config;
  408. return this.queryUser(rawUserName)
  409. .then(userNameId => {
  410. var _a, _b;
  411. const userId = userNameId.split(':')[1];
  412. if (Date.now() - new Date((_b = (_a = this.cache[userId]) === null || _a === void 0 ? void 0 : _a.updated) !== null && _b !== void 0 ? _b : Date()).getTime() > this.workInterval * 1000 &&
  413. Object.keys(this.cache[userId].stories).length > 0) {
  414. return userId;
  415. }
  416. return this.client.feed.reelsMedia({ userIds: [userId] }).items()
  417. .then(storyItems => Promise.all(storyItems
  418. .filter(item => !(item.pk in this.cache[userId].stories))
  419. .map(item => this.webshot([Object.assign(Object.assign({}, item), { user: this.cache[userId].user })], (msgs, text, author) => this.cache[userId].stories[item.pk] = { pk: item.pk, msgs, text, author, original: item }, this.webshotDelay))).then(() => userId).finally(() => this.cache[userId].updated = Date()));
  420. })
  421. .then(action)
  422. .catch((error) => {
  423. if (error instanceof instagram_private_api_1.IgExactUserNotFoundError) {
  424. reply(`找不到用户 ${rawUserName.replace(/^@?(.*)$/, '@$1')}。`);
  425. }
  426. else if (error instanceof instagram_private_api_1.IgNetworkError) {
  427. if (error.cause.message === "Unexpected '<'") {
  428. logger.warn('login required, logging in again...');
  429. return this.session.login().then(retryAction);
  430. }
  431. logger.warn(`error while fetching stories for ${rawUserName}: ${JSON.stringify(error.cause)}`);
  432. reply(`获取 Stories 时出现错误:原因: ${error.cause}`);
  433. }
  434. else if (error instanceof instagram_private_api_1.IgLoginRequiredError || error instanceof instagram_private_api_1.IgCookieNotFoundError) {
  435. logger.warn('login required, logging in again...');
  436. reply('等待登录中,稍后会处理请求,请稍候……');
  437. this.session.login().then(retryAction);
  438. }
  439. else {
  440. logger.error(`unhandled error while fetching stories for ${rawUserName}: ${error}`);
  441. reply(`获取 Stories 时发生未知错误: ${error}`);
  442. }
  443. });
  444. };
  445. ScreenNameNormalizer._queryUser = this.queryUser;
  446. exports.sendTimeline = (rawUserName, receiver) => {
  447. const reply = msg => this.bot.sendTo(receiver, msg);
  448. workNow({
  449. rawUserName,
  450. action: userId => {
  451. const userName = this.cache[userId].user.username;
  452. const storyItems = Object.values(this.cache[userId].stories)
  453. .sort((i1, i2) => -utils_1.BigNumOps.compare(i2.pk, i1.pk));
  454. if (storyItems.length === 0)
  455. return reply(`当前用户 (@${userName}) 没有可用的 Instagram 限时动态。`);
  456. return reply('#. 编号:发送时间\n' + storyItems.map(({ original }, index) => `\n${index + 1}. ${original.pk}: ${datetime_1.relativeDate(original.taken_at * 1000)}`).join(''))
  457. .then(() => reply(`请使用 /igstory_view ${userName} skip=<#-1> count=1
  458. 或 /igstory_view https://www.instagram.com/stories/${userName}/<编号>/
  459. 查看指定的限时动态。`));
  460. },
  461. reply,
  462. retryAction: () => exports.sendTimeline(rawUserName, receiver),
  463. });
  464. };
  465. exports.sendStory = (rawUserName, storyId, receiver) => {
  466. const reply = msg => this.bot.sendTo(receiver, msg);
  467. const sender = this.sendStories(`instagram stories for ${rawUserName}`, receiver);
  468. workNow({
  469. rawUserName,
  470. action: userId => {
  471. if (!(storyId in this.cache[userId].stories))
  472. return reply('此动态不存在或已过期。');
  473. return this.workOnMedia([this.cache[userId].stories[storyId]], sender);
  474. },
  475. reply,
  476. retryAction: () => exports.sendStory(rawUserName, storyId, receiver),
  477. });
  478. };
  479. exports.sendAllStories = (rawUserName, receiver, startIndex = 0, count = 10) => {
  480. const reply = msg => this.bot.sendTo(receiver, msg);
  481. if (startIndex < 0)
  482. return reply('跳过数量参数值应为非负整数。');
  483. if (count < 1)
  484. return reply('最大查看数量参数值应为正整数。');
  485. const sender = this.sendStories(`instagram stories for ${rawUserName}`, receiver);
  486. workNow({
  487. rawUserName,
  488. action: userId => {
  489. const userName = this.cache[userId].user.username;
  490. const storyItems = Object.values(this.cache[userId].stories)
  491. .sort((i1, i2) => -utils_1.BigNumOps.compare(i2.pk, i1.pk));
  492. if (storyItems.length === 0)
  493. return reply(`当前用户 (@${userName}) 没有可用的 Instagram 限时动态。`);
  494. if (startIndex + 1 > storyItems.length)
  495. return reply('跳过数量到达或超过当前用户可用的限时动态数量。');
  496. const endIndex = Math.min(storyItems.length, startIndex + count);
  497. const sendRangeText = `${startIndex + 1}${endIndex - startIndex > 1 ? `-${endIndex}` : ''}`;
  498. return this.workOnMedia(storyItems.slice(startIndex, endIndex), sender)
  499. .then(() => reply(`已显示当前用户 ${storyItems.length} 条可用限时动态中的第 ${sendRangeText} 条。`));
  500. },
  501. reply,
  502. retryAction: () => exports.sendAllStories(rawUserName, receiver, startIndex, count)
  503. });
  504. };
  505. }
  506. get pullOrders() {
  507. const arr = [];
  508. Object.values(this.cache).forEach(item => { if (item.pullOrder > 0)
  509. arr[item.pullOrder - 1] = item.user.pk; });
  510. return arr;
  511. }
  512. ;
  513. set pullOrders(arr) {
  514. Object.values(this.cache).forEach(item => { item.pullOrder = arr.indexOf(item.user.pk) + 1; });
  515. }
  516. get isInactiveTime() {
  517. const timeToEpoch = (h = 0, m = 0) => new Date().setHours(h, m, 0, 0);
  518. return this.inactiveHours
  519. .map(rangeStr => ((start, end) => ({ start, end }))(...rangeStr.split('-', 2).map(timeStr => timeToEpoch(...timeStr.split(':', 2).map(Number)))))
  520. .some(range => (now => now >= range.start && now < range.end)(Date.now()));
  521. }
  522. }
  523. exports.default = default_1;