twitter.js 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508
  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.queryUser = (rawUserName) => {
  195. const username = ScreenNameNormalizer.normalize(rawUserName).split(':')[0];
  196. if (username in this.cache) {
  197. return Promise.resolve(`${username}:${this.cache[username].user.pk}`);
  198. }
  199. return this.client.user.searchExact(username)
  200. .catch((error) => {
  201. if (error instanceof instagram_private_api_1.IgLoginRequiredError || error instanceof instagram_private_api_1.IgCookieNotFoundError) {
  202. logger.warn('login required, logging in again...');
  203. return this.session.login().then(() => this.client.user.searchExact(username));
  204. }
  205. else
  206. throw error;
  207. })
  208. .then(user => {
  209. logger.info(`initialized cache item for user ${user.full_name} (@${username})`);
  210. this.cache[user.username] = { user, stories: {}, pullOrder: 0 };
  211. return `${user.username}:${user.pk}`;
  212. });
  213. };
  214. this.workOnMedia = (mediaItems, sendMedia) => Promise.resolve(mediaItems.forEach(({ msgs, text, author }) => sendMedia(msgs, text, author)));
  215. this.sendStories = (source, ...to) => (msg, text, author) => {
  216. to.forEach(subscriber => {
  217. logger.info(`pushing data${source ? ` of ${source}` : ''} to ${JSON.stringify(subscriber)}`);
  218. retryOnError(() => this.bot.sendTo(subscriber, msg), (_, count, terminate) => {
  219. if (count <= maxTrials) {
  220. logger.warn(`retry sending to ${subscriber.chatID} for the ${ordinal(count)} time...`);
  221. }
  222. else {
  223. logger.warn(`${count - 1} consecutive failures while sending message chain, trying plain text instead...`);
  224. terminate(this.bot.sendTo(subscriber, author + text, true));
  225. }
  226. });
  227. });
  228. };
  229. this.cache = {};
  230. this.workForAll = () => {
  231. if (this.isInactiveTime)
  232. return;
  233. logger.debug(`current cache: ${JSON.stringify(this.cache)}`);
  234. utils_1.chainPromises(Object.entries(this.lock.threads).map(([feed, thread]) => {
  235. const id = thread.id;
  236. const userName = parseLink(feed).userName;
  237. logger.debug(`preparing to add user @${userName} to next pull task...`);
  238. return (map = {}) => {
  239. if (userName in this.cache) {
  240. const item = this.cache[userName];
  241. if (item.pullOrder === 0)
  242. item.pullOrder = -1;
  243. return Promise.resolve(Object.assign(map, { [id]: item.user }));
  244. }
  245. return util_1.promisify(setTimeout)((Math.random() * 2 + 1) * 5000).then(() => this.client.user.info(id).then(user => {
  246. logger.info(`initialized cache item for user ${user.full_name} (@${userName})`);
  247. this.cache[userName] = { user, stories: {}, pullOrder: -1 };
  248. return Object.assign(map, { [id]: user });
  249. }));
  250. };
  251. }))
  252. .then(idToUserMap => {
  253. const userIdCache = Object.values(this.cache).some(item => item.pullOrder < 0) ?
  254. this.pullOrders = utils_1.Arr.shuffle(Object.keys(idToUserMap)).map(Number) :
  255. this.pullOrders;
  256. return utils_1.chainPromises(utils_1.Arr.chunk(userIdCache, 20).map(userIds => () => {
  257. const itemToUserName = (item) => idToUserMap[item.user.pk].username;
  258. logger.info(`pulling stories from users:${userIds.map(id => ` @${idToUserMap[id].username}`)}`);
  259. return this.client.feed.reelsMedia({ userIds }).items()
  260. .then(storyItems => Promise.all(storyItems
  261. .filter(item => !(item.pk in this.cache[itemToUserName(item)].stories))
  262. .map(item => this.webshot([Object.assign(Object.assign({}, item), { user: this.cache[itemToUserName(item)].user })], (msgs, text, author) => this.cache[itemToUserName(item)].stories[item.pk] = { pk: item.pk, msgs, text, author, original: item }, this.webshotDelay))))
  263. .finally(() => Object.values(this.lock.threads).forEach(thread => {
  264. if (userIds.includes(thread.id)) {
  265. thread.updatedAt = (this.cache[idToUserMap[thread.id].username].updated = new Date()).toString();
  266. }
  267. }));
  268. }), (lp1, lp2) => () => lp1().then(() => util_1.promisify(setTimeout)(this.workInterval * 1000 / this.lock.feed.length).then(lp2)));
  269. })
  270. .catch((error) => {
  271. if (error instanceof instagram_private_api_1.IgNetworkError) {
  272. if (error.cause.message === "Unexpected '<'") {
  273. logger.warn('login required, logging in again...');
  274. return this.session.login().then(this.workForAll);
  275. }
  276. logger.warn(`error while fetching stories for all: ${JSON.stringify(error.cause)}`);
  277. }
  278. else if (error instanceof instagram_private_api_1.IgLoginRequiredError || error instanceof instagram_private_api_1.IgCookieNotFoundError) {
  279. logger.warn('login required, logging in again...');
  280. this.session.login().then(this.workForAll);
  281. }
  282. else {
  283. logger.error(`unhandled error on fetching media for all: ${error}`);
  284. }
  285. });
  286. };
  287. this.work = () => {
  288. const lock = this.lock;
  289. if (this.workInterval < 1)
  290. this.workInterval = 1;
  291. if (this.isInactiveTime || lock.feed.length === 0) {
  292. setTimeout(() => {
  293. this.workForAll();
  294. setTimeout(this.work, this.workInterval * 200);
  295. }, this.workInterval * 1000 / lock.feed.length);
  296. return;
  297. }
  298. if (lock.workon >= lock.feed.length)
  299. lock.workon = 0;
  300. const currentFeed = lock.feed[lock.workon];
  301. if (!lock.threads[currentFeed] ||
  302. !lock.threads[currentFeed].subscribers ||
  303. lock.threads[currentFeed].subscribers.length === 0) {
  304. logger.warn(`nobody subscribes thread ${currentFeed}, removing from feed`);
  305. delete lock.threads[currentFeed];
  306. this.cache[parseLink(currentFeed).userName].pullOrder = 0;
  307. lock.feed.splice(lock.workon, 1);
  308. fs.writeFileSync(path.resolve(this.lockfile), JSON.stringify(lock));
  309. this.work();
  310. return;
  311. }
  312. logger.debug(`searching for new items from ${currentFeed} in cache`);
  313. const match = /https:\/\/www\.instagram\.com\/([^\/]+)/.exec(currentFeed);
  314. if (!match) {
  315. logger.error(`current feed "${currentFeed}" is invalid, please remove this feed manually`);
  316. lock.workon++;
  317. setTimeout(this.work, this.workInterval * 1000 / lock.feed.length);
  318. return;
  319. }
  320. const cachedFeed = this.cache[match[1]];
  321. if (!cachedFeed) {
  322. setTimeout(this.work, this.workInterval * 1000 / lock.feed.length);
  323. return;
  324. }
  325. const newer = (item) => utils_1.BigNumOps.compare(item.pk, lock.threads[currentFeed].offset) > 0;
  326. const promise = Promise.resolve(Object.values(cachedFeed.stories)
  327. .filter(newer)
  328. .sort((i1, i2) => utils_1.BigNumOps.compare(i2.pk, i1.pk))
  329. .slice(-5));
  330. promise.then((mediaItems) => {
  331. const currentThread = lock.threads[currentFeed];
  332. if (!mediaItems || mediaItems.length === 0)
  333. return;
  334. const question = mediaItems.find(story => story.original.story_questions);
  335. const topOfFeed = question ? question.pk : mediaItems[0].pk;
  336. const updateOffset = () => currentThread.offset = topOfFeed;
  337. if (currentThread.offset === '-1') {
  338. updateOffset();
  339. return;
  340. }
  341. if (currentThread.offset === '0')
  342. mediaItems.splice(1);
  343. return this.workOnMedia(mediaItems.reverse(), this.sendStories(`thread ${currentFeed}`, ...currentThread.subscribers))
  344. .then(updateOffset)
  345. .then(() => {
  346. if (question) {
  347. currentThread.subscribers.forEach(subscriber => {
  348. const username = cachedFeed.user.username;
  349. const author = `${cachedFeed.user.full_name} (@${username}) `;
  350. this.bot.sendTo(subscriber, `请注意,用户${author}已开启问答互动。需退订请回复:/igstory_unsub ${username}${Object.keys(cachedFeed.stories).some(id => id > topOfFeed) ?
  351. `\n本次推送已截止于此条动态,下次推送在 ${Math.floor(this.workInterval * 1000 / lock.feed.length)} 秒后。` : ''}`);
  352. });
  353. }
  354. });
  355. })
  356. .then(() => {
  357. lock.workon++;
  358. let timeout = this.workInterval * 1000 / lock.feed.length;
  359. if (timeout < 1000)
  360. timeout = 1000;
  361. fs.writeFileSync(path.resolve(this.lockfile), JSON.stringify(lock));
  362. setTimeout(this.work, timeout);
  363. });
  364. };
  365. this.client = new instagram_private_api_1.IgApiClient();
  366. if (opt.proxyUrl) {
  367. try {
  368. const url = new URL(opt.proxyUrl);
  369. if (!/^socks(?:4a?|5h?)?:$/.test(url.protocol))
  370. throw Error();
  371. if (!url.port)
  372. url.port = '1080';
  373. this.client.request.defaults.agent = new socks_proxy_agent_1.SocksProxyAgent({
  374. hostname: url.hostname,
  375. port: url.port,
  376. userId: url.username,
  377. password: url.password,
  378. });
  379. }
  380. catch (e) {
  381. logger.warn(`invalid socks proxy url: ${opt.proxyUrl}, ignoring`);
  382. }
  383. }
  384. this.session = new SessionManager(this.client, opt.sessionLockfile, opt.credentials, opt.codeServicePort);
  385. this.lockfile = opt.lockfile;
  386. this.lock = opt.lock;
  387. this.inactiveHours = opt.inactiveHours;
  388. this.workInterval = opt.workInterval;
  389. this.bot = opt.bot;
  390. this.webshotDelay = opt.webshotDelay;
  391. this.mode = opt.mode;
  392. this.wsUrl = opt.wsUrl;
  393. const workNow = (config) => {
  394. const { action, retryAction, reply, rawUserName } = config;
  395. return this.queryUser(rawUserName)
  396. .then(userNameId => {
  397. var _a, _b;
  398. const [userName, userId] = userNameId.split(':');
  399. if (Date.now() - ((_b = (_a = this.cache[userName]) === null || _a === void 0 ? void 0 : _a.updated) === null || _b === void 0 ? void 0 : _b.getTime()) > this.workInterval * 1000 &&
  400. Object.keys(this.cache[userName].stories).length > 0) {
  401. return userName;
  402. }
  403. return this.client.feed.reelsMedia({ userIds: [userId] }).items()
  404. .then(storyItems => Promise.all(storyItems
  405. .filter(item => !(item.pk in this.cache[userName].stories))
  406. .map(item => this.webshot([Object.assign(Object.assign({}, item), { user: this.cache[userName].user })], (msgs, text, author) => this.cache[userName].stories[item.pk] = { pk: item.pk, msgs, text, author, original: item }, this.webshotDelay))).then(() => userName).finally(() => this.cache[userName].updated = new Date()));
  407. })
  408. .then(action)
  409. .catch((error) => {
  410. if (error instanceof instagram_private_api_1.IgExactUserNotFoundError) {
  411. reply(`找不到用户 ${rawUserName.replace(/^@?(.*)$/, '@$1')}。`);
  412. }
  413. if (error instanceof instagram_private_api_1.IgNetworkError) {
  414. if (error.cause.message === "Unexpected '<'") {
  415. logger.warn('login required, logging in again...');
  416. return this.session.login().then(retryAction);
  417. }
  418. logger.warn(`error while fetching stories for ${rawUserName}: ${JSON.stringify(error.cause)}`);
  419. reply(`获取 Stories 时出现错误:原因: ${error.cause}`);
  420. }
  421. else if (error instanceof instagram_private_api_1.IgLoginRequiredError || error instanceof instagram_private_api_1.IgCookieNotFoundError) {
  422. logger.warn('login required, logging in again...');
  423. reply('等待登陆中,稍后会处理请求,请稍候……');
  424. this.session.login().then(retryAction);
  425. }
  426. else {
  427. logger.error(`unhandled error while fetching stories for ${rawUserName}: ${error}`);
  428. reply(`获取 Stories 时发生未知错误: ${error}`);
  429. }
  430. });
  431. };
  432. ScreenNameNormalizer._queryUser = this.queryUser;
  433. exports.sendTimeline = (rawUserName, receiver) => {
  434. const reply = msg => this.bot.sendTo(receiver, msg);
  435. workNow({
  436. rawUserName,
  437. action: userName => {
  438. const storyItems = Object.values(this.cache[userName].stories)
  439. .sort((i1, i2) => -utils_1.BigNumOps.compare(i2.pk, i1.pk));
  440. if (storyItems.length === 0)
  441. return reply(`当前用户 (@${userName}) 没有可用的 Instagram 限时动态。`);
  442. return reply('#. 编号:发送时间\n' + storyItems.map(({ original }, index) => `\n${index + 1}. ${original.pk}: ${datetime_1.relativeDate(original.taken_at * 1000)}`).join(''))
  443. .then(() => reply(`请使用 /igstory_view ${userName} skip=<#-1> count=1
  444. 或 /igstory_view https://www.instagram.com/stories/${userName}/<编号>/
  445. 查看指定的限时动态。`));
  446. },
  447. reply,
  448. retryAction: () => exports.sendTimeline(rawUserName, receiver),
  449. });
  450. };
  451. exports.sendStory = (rawUserName, storyId, receiver) => {
  452. const reply = msg => this.bot.sendTo(receiver, msg);
  453. const sender = this.sendStories(`instagram stories for ${rawUserName}`, receiver);
  454. workNow({
  455. rawUserName,
  456. action: userName => {
  457. if (!(storyId in this.cache[userName].stories))
  458. return reply('此动态不存在或已过期。');
  459. return this.workOnMedia([this.cache[userName].stories[storyId]], sender);
  460. },
  461. reply,
  462. retryAction: () => exports.sendStory(rawUserName, storyId, receiver),
  463. });
  464. };
  465. exports.sendAllStories = (rawUserName, receiver, startIndex = 0, count = 10) => {
  466. const reply = msg => this.bot.sendTo(receiver, msg);
  467. if (startIndex < 0)
  468. return reply('跳过数量参数值应为非负整数。');
  469. if (count < 1)
  470. return reply('最大查看数量参数值应为正整数。');
  471. const sender = this.sendStories(`instagram stories for ${rawUserName}`, receiver);
  472. workNow({
  473. rawUserName,
  474. action: userName => {
  475. const storyItems = Object.values(this.cache[userName].stories)
  476. .sort((i1, i2) => -utils_1.BigNumOps.compare(i2.pk, i1.pk));
  477. if (storyItems.length === 0)
  478. return reply(`当前用户 (@${userName}) 没有可用的 Instagram 限时动态。`);
  479. if (startIndex + 1 > storyItems.length)
  480. return reply('跳过数量到达或超过当前用户可用的限时动态数量。');
  481. const endIndex = Math.min(storyItems.length, startIndex + count);
  482. const sendRangeText = `${startIndex + 1}${endIndex - startIndex > 1 ? `-${endIndex}` : ''}`;
  483. return this.workOnMedia(storyItems.slice(startIndex, endIndex), sender)
  484. .then(() => reply(`已显示当前用户 ${storyItems.length} 条可用限时动态中的第 ${sendRangeText} 条。`));
  485. },
  486. reply,
  487. retryAction: () => exports.sendAllStories(rawUserName, receiver, startIndex, count)
  488. });
  489. };
  490. }
  491. get pullOrders() {
  492. const arr = [];
  493. Object.values(this.cache).forEach(item => { if (item.pullOrder > 0)
  494. arr[item.pullOrder - 1] = item.user.pk; });
  495. return arr;
  496. }
  497. ;
  498. set pullOrders(arr) {
  499. Object.values(this.cache).forEach(item => { item.pullOrder = arr.indexOf(item.user.pk) + 1; });
  500. }
  501. get isInactiveTime() {
  502. const timeToEpoch = (h = 0, m = 0) => new Date().setHours(h, m, 0, 0);
  503. return this.inactiveHours
  504. .map(rangeStr => ((start, end) => ({ start, end }))(...rangeStr.split('-', 2).map(timeStr => timeToEpoch(...timeStr.split(':', 2).map(Number)))))
  505. .some(range => (now => now >= range.start && now < range.end)(Date.now()));
  506. }
  507. }
  508. exports.default = default_1;