twitter.js 29 KB

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