twitter.js 28 KB

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