twitter.js 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524
  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. (0, 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 } = (0, 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 = (0, 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. (0, 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 (0, 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 (0, 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 }) => (0, utils_1.chainPromises)(Object.keys(reels).map(userId => this.cache[userId]).map(({ user, stories }) => () => this.queryUserObject(user.username)
  260. .catch((error) => {
  261. if (error instanceof instagram_private_api_1.IgExactUserNotFoundError) {
  262. return this.client.user.info(user.pk)
  263. .then(({ username, full_name }) => {
  264. user.username = username;
  265. user.full_name = full_name;
  266. });
  267. }
  268. }).finally(() => Promise.all(reels[user.pk].items
  269. .filter(item => !(item.pk in stories))
  270. .map(item => this.webshot([Object.assign(Object.assign({}, item), { user })], (msgs, text, author) => 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(() => (0, 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. fs.writeFileSync(path.resolve(this.cachefile), JSON.stringify(this.cache));
  319. lock.feed.splice(lock.workon, 1);
  320. fs.writeFileSync(path.resolve(this.lockfile), JSON.stringify(lock));
  321. this.work();
  322. return;
  323. }
  324. logger.debug(`searching for new items from ${currentFeed} in cache`);
  325. const match = /https:\/\/www\.instagram\.com\/([^\/]+)/.exec(currentFeed);
  326. if (!match) {
  327. logger.error(`current feed "${currentFeed}" is invalid, please remove this feed manually`);
  328. lock.workon++;
  329. setTimeout(this.work, this.workInterval * 1000 / lock.feed.length);
  330. return;
  331. }
  332. const cachedFeed = this.cache[lock.threads[currentFeed].id];
  333. if (!cachedFeed) {
  334. setTimeout(this.work, this.workInterval * 1000 / lock.feed.length);
  335. return;
  336. }
  337. const newer = (item) => utils_1.BigNumOps.compare(item.pk, lock.threads[currentFeed].offset) > 0;
  338. const promise = Promise.resolve(Object.values(cachedFeed.stories)
  339. .filter(newer)
  340. .sort((i1, i2) => utils_1.BigNumOps.compare(i2.pk, i1.pk))
  341. .slice(-5));
  342. promise.then((mediaItems) => {
  343. const currentThread = lock.threads[currentFeed];
  344. if (!mediaItems || mediaItems.length === 0)
  345. return;
  346. const question = mediaItems.find(story => story.original.story_questions);
  347. const topOfFeed = question ? question.pk : mediaItems[0].pk;
  348. const updateOffset = () => currentThread.offset = topOfFeed;
  349. if (currentThread.offset === '-1') {
  350. updateOffset();
  351. return;
  352. }
  353. if (currentThread.offset === '0')
  354. mediaItems.splice(1);
  355. return this.workOnMedia(mediaItems.reverse(), this.sendStories(`thread ${currentFeed}`, ...currentThread.subscribers))
  356. .then(updateOffset)
  357. .then(() => {
  358. if (question) {
  359. currentThread.subscribers.forEach(subscriber => {
  360. const username = cachedFeed.user.username;
  361. const author = `${cachedFeed.user.full_name} (@${username}) `;
  362. this.bot.sendTo(subscriber, `请注意,用户${author}已开启问答互动。需退订请回复:/igstory_unsub ${username}${Object.keys(cachedFeed.stories).some(id => id > topOfFeed) ?
  363. `\n本次推送已截止于此条动态,下次推送在 ${Math.floor(this.workInterval / lock.feed.length)} 秒后。` : ''}`);
  364. });
  365. }
  366. });
  367. })
  368. .then(() => {
  369. lock.workon++;
  370. let timeout = this.workInterval * 1000 / lock.feed.length;
  371. if (timeout < 1000)
  372. timeout = 1000;
  373. fs.writeFileSync(path.resolve(this.lockfile), JSON.stringify(lock));
  374. setTimeout(this.work, timeout);
  375. });
  376. };
  377. this.client = new instagram_private_api_1.IgApiClient();
  378. if (opt.proxyUrl) {
  379. try {
  380. const url = new URL(opt.proxyUrl);
  381. if (!/^socks(?:4a?|5h?)?:$/.test(url.protocol))
  382. throw Error();
  383. if (!url.port)
  384. url.port = '1080';
  385. this.client.request.defaults.agent = new socks_proxy_agent_1.SocksProxyAgent({
  386. hostname: url.hostname,
  387. port: url.port,
  388. userId: url.username,
  389. password: url.password,
  390. });
  391. }
  392. catch (e) {
  393. logger.warn(`invalid socks proxy url: ${opt.proxyUrl}, ignoring`);
  394. }
  395. }
  396. this.session = new SessionManager(this.client, opt.sessionLockfile, opt.credentials, opt.codeServicePort);
  397. this.lockfile = opt.lockfile;
  398. this.lock = opt.lock;
  399. this.cachefile = opt.cachefile;
  400. this.cache = opt.cache;
  401. this.inactiveHours = opt.inactiveHours;
  402. this.workInterval = opt.workInterval;
  403. this.bot = opt.bot;
  404. this.webshotDelay = opt.webshotDelay;
  405. this.mode = opt.mode;
  406. this.wsUrl = opt.wsUrl;
  407. const workNow = (config) => {
  408. const { action, retryAction, reply, rawUserName } = config;
  409. return this.queryUser(rawUserName)
  410. .then(userNameId => {
  411. var _a, _b;
  412. const userId = userNameId.split(':')[1];
  413. 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 &&
  414. Object.keys(this.cache[userId].stories).length > 0) {
  415. return userId;
  416. }
  417. return this.client.feed.reelsMedia({ userIds: [userId] }).items()
  418. .then(storyItems => Promise.all(storyItems
  419. .filter(item => !(item.pk in this.cache[userId].stories))
  420. .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()));
  421. })
  422. .then(action)
  423. .catch((error) => {
  424. if (error instanceof instagram_private_api_1.IgExactUserNotFoundError) {
  425. reply(`找不到用户 ${rawUserName.replace(/^@?(.*)$/, '@$1')}。`);
  426. }
  427. else if (error instanceof instagram_private_api_1.IgNetworkError) {
  428. if (error.cause.message === "Unexpected '<'") {
  429. logger.warn('login required, logging in again...');
  430. return this.session.login().then(retryAction);
  431. }
  432. logger.warn(`error while fetching stories for ${rawUserName}: ${JSON.stringify(error.cause)}`);
  433. reply(`获取 Stories 时出现错误:原因: ${error.cause}`);
  434. }
  435. else if (error instanceof instagram_private_api_1.IgLoginRequiredError || error instanceof instagram_private_api_1.IgCookieNotFoundError) {
  436. logger.warn('login required, logging in again...');
  437. reply('等待登录中,稍后会处理请求,请稍候……');
  438. this.session.login().then(retryAction);
  439. }
  440. else {
  441. logger.error(`unhandled error while fetching stories for ${rawUserName}: ${error}`);
  442. reply(`获取 Stories 时发生未知错误: ${error}`);
  443. }
  444. });
  445. };
  446. ScreenNameNormalizer._queryUser = this.queryUser;
  447. exports.sendTimeline = (rawUserName, receiver) => {
  448. const reply = msg => this.bot.sendTo(receiver, msg);
  449. workNow({
  450. rawUserName,
  451. action: userId => {
  452. const userName = this.cache[userId].user.username;
  453. const storyItems = Object.values(this.cache[userId].stories)
  454. .sort((i1, i2) => -utils_1.BigNumOps.compare(i2.pk, i1.pk));
  455. if (storyItems.length === 0)
  456. return reply(`当前用户 (@${userName}) 没有可用的 Instagram 限时动态。`);
  457. return reply('#. 编号:发送时间\n' + storyItems.map(({ original }, index) => `\n${index + 1}. ${original.pk}: ${(0, datetime_1.relativeDate)(original.taken_at * 1000)}`).join(''))
  458. .then(() => reply(`请使用 /igstory_view ${userName} skip=<#-1> count=1
  459. 或 /igstory_view https://www.instagram.com/stories/${userName}/<编号>/
  460. 查看指定的限时动态。`));
  461. },
  462. reply,
  463. retryAction: () => (0, exports.sendTimeline)(rawUserName, receiver),
  464. });
  465. };
  466. exports.sendStory = (rawUserName, storyId, receiver) => {
  467. const reply = msg => this.bot.sendTo(receiver, msg);
  468. const sender = this.sendStories(`instagram stories for ${rawUserName}`, receiver);
  469. workNow({
  470. rawUserName,
  471. action: userId => {
  472. if (!(storyId in this.cache[userId].stories))
  473. return reply('此动态不存在或已过期。');
  474. return this.workOnMedia([this.cache[userId].stories[storyId]], sender);
  475. },
  476. reply,
  477. retryAction: () => (0, exports.sendStory)(rawUserName, storyId, receiver),
  478. });
  479. };
  480. exports.sendAllStories = (rawUserName, receiver, startIndex = 0, count = 10) => {
  481. const reply = msg => this.bot.sendTo(receiver, msg);
  482. if (startIndex < 0)
  483. return reply('跳过数量参数值应为非负整数。');
  484. if (count < 1)
  485. return reply('最大查看数量参数值应为正整数。');
  486. const sender = this.sendStories(`instagram stories for ${rawUserName}`, receiver);
  487. workNow({
  488. rawUserName,
  489. action: userId => {
  490. const userName = this.cache[userId].user.username;
  491. const storyItems = Object.values(this.cache[userId].stories)
  492. .sort((i1, i2) => -utils_1.BigNumOps.compare(i2.pk, i1.pk));
  493. if (storyItems.length === 0)
  494. return reply(`当前用户 (@${userName}) 没有可用的 Instagram 限时动态。`);
  495. if (startIndex + 1 > storyItems.length)
  496. return reply('跳过数量到达或超过当前用户可用的限时动态数量。');
  497. const endIndex = Math.min(storyItems.length, startIndex + count);
  498. const sendRangeText = `${startIndex + 1}${endIndex - startIndex > 1 ? `-${endIndex}` : ''}`;
  499. return this.workOnMedia(storyItems.slice(startIndex, endIndex), sender)
  500. .then(() => reply(`已显示当前用户 ${storyItems.length} 条可用限时动态中的第 ${sendRangeText} 条。`));
  501. },
  502. reply,
  503. retryAction: () => (0, exports.sendAllStories)(rawUserName, receiver, startIndex, count)
  504. });
  505. };
  506. }
  507. get pullOrders() {
  508. const arr = [];
  509. Object.values(this.cache).forEach(item => { if (item.pullOrder > 0)
  510. arr[item.pullOrder - 1] = item.user.pk; });
  511. return arr;
  512. }
  513. ;
  514. set pullOrders(arr) {
  515. Object.values(this.cache).forEach(item => { item.pullOrder = arr.indexOf(item.user.pk) + 1; });
  516. }
  517. get isInactiveTime() {
  518. const timeToEpoch = (h = 0, m = 0) => new Date().setHours(h, m, 0, 0);
  519. return this.inactiveHours
  520. .map(rangeStr => ((start, end) => ({ start, end }))(...rangeStr.split('-', 2).map(timeStr => timeToEpoch(...timeStr.split(':', 2).map(Number)))))
  521. .some(range => (now => now >= range.start && now < range.end)(Date.now()));
  522. }
  523. }
  524. exports.default = default_1;