twitter.js 28 KB

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