twitter.js 26 KB

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