twitter.ts 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333
  1. import * as fs from 'fs';
  2. import * as path from 'path';
  3. import * as request from 'request';
  4. import * as Twitter from 'twitter';
  5. import TwitterTypes from 'twitter-d';
  6. import { getLogger } from './loggers';
  7. import QQBot, { Message, MessageChain } from './mirai';
  8. import { BigNumOps } from './utils';
  9. import Webshot from './webshot';
  10. interface IWorkerOption {
  11. lock: ILock;
  12. lockfile: string;
  13. bot: QQBot;
  14. workInterval: number;
  15. webshotDelay: number;
  16. consumer_key: string;
  17. consumer_secret: string;
  18. access_token_key: string;
  19. access_token_secret: string;
  20. private_csrf_token: string;
  21. private_auth_token: string;
  22. mode: number;
  23. }
  24. export class ScreenNameNormalizer {
  25. // tslint:disable-next-line: variable-name
  26. public static _queryUser: (username: string) => Promise<string>;
  27. public static permaFeeds = {};
  28. public static savePermaFeedForUser(user: FullUser) {
  29. this.permaFeeds[`https://twitter.com/${user.screen_name}`] = `https://twitter.com/i/user/${user.id_str}`;
  30. }
  31. public static normalize = (username: string) => username.toLowerCase().replace(/^@/, '');
  32. public static async normalizeLive(username: string) {
  33. if (this._queryUser) {
  34. return await this._queryUser(username)
  35. .catch((err: {code: number, message: string}[]) => {
  36. if (err[0].code !== 50) {
  37. logger.warn(`error looking up user: ${err[0].message}`);
  38. return username;
  39. }
  40. return null;
  41. });
  42. }
  43. return this.normalize(username);
  44. }
  45. }
  46. export let sendAllFleets = (username: string, receiver: IChat): void => {
  47. throw Error();
  48. };
  49. const logger = getLogger('twitter');
  50. const maxTrials = 3;
  51. const uploadTimeout = 10000;
  52. const retryInterval = 1500;
  53. const ordinal = (n: number) => {
  54. switch ((Math.trunc(n / 10) % 10 === 1) ? 0 : n % 10) {
  55. case 1:
  56. return `${n}st`;
  57. case 2:
  58. return `${n}nd`;
  59. case 3:
  60. return `${n}rd`;
  61. default:
  62. return `${n}th`;
  63. }
  64. };
  65. const retryOnError = <T, U>(
  66. doWork: () => Promise<T>,
  67. onRetry: (error, count: number, terminate: (defaultValue: U) => void) => void
  68. ) => new Promise<T | U>(resolve => {
  69. const retry = (reason, count: number) => {
  70. setTimeout(() => {
  71. let terminate = false;
  72. onRetry(reason, count, defaultValue => { terminate = true; resolve(defaultValue); });
  73. if (!terminate) doWork().then(resolve).catch(error => retry(error, count + 1));
  74. }, retryInterval);
  75. };
  76. doWork().then(resolve).catch(error => retry(error, 1));
  77. });
  78. export type FullUser = TwitterTypes.FullUser;
  79. export type MediaEntity = TwitterTypes.MediaEntity;
  80. type TwitterMod = {
  81. -readonly [K in keyof Twitter]: Twitter[K];
  82. } & {
  83. options?: any;
  84. };
  85. interface IFleet {
  86. created_at: string;
  87. deleted_at: string;
  88. expiration: string;
  89. fleet_id: string;
  90. fleet_thread_id: string;
  91. media_bounding_boxes: [{
  92. anchor_point_x: number;
  93. anchor_point_y: number;
  94. width: number;
  95. height: number;
  96. rotation: number;
  97. entity: {
  98. type: string;
  99. value: any;
  100. }
  101. }];
  102. media_entity: MediaEntity;
  103. media_key: {
  104. media_category: 'TWEET_IMAGE' | 'TWEET_VIDEO';
  105. media_id: number;
  106. media_id_str: string;
  107. };
  108. mentions: any;
  109. mentions_str: any;
  110. read: boolean;
  111. text: string;
  112. user_id: number;
  113. user_id_str: string;
  114. }
  115. export type Fleet = IFleet;
  116. export type Fleets = IFleet[];
  117. interface IFleetFeed {
  118. fleet_threads: {fleets: Fleets}[];
  119. }
  120. export default class {
  121. private client: Twitter;
  122. private privateClient: TwitterMod;
  123. private lock: ILock;
  124. private lockfile: string;
  125. private workInterval: number;
  126. private bot: QQBot;
  127. private webshotDelay: number;
  128. private webshot: Webshot;
  129. private mode: number;
  130. constructor(opt: IWorkerOption) {
  131. this.client = new Twitter({
  132. consumer_key: opt.consumer_key,
  133. consumer_secret: opt.consumer_secret,
  134. access_token_key: opt.access_token_key,
  135. access_token_secret: opt.access_token_secret,
  136. });
  137. this.privateClient = new Twitter({
  138. bearer_token: 'AAAAAAAAAAAAAAAAAAAAANRILgAAAAAAnNwIzUejRCOuH5E6I8xnZz4puTs%3D1Zv7ttfk8LF81IUq16cHjhLTvJu4FA33AGWWjCpTnA',
  139. } as any);
  140. this.privateClient.request = request.defaults({
  141. headers: {
  142. ...this.privateClient.options.request_options.headers,
  143. 'Content-Type': 'application/x-www-form-urlencoded',
  144. Cookie: `auth_token=${opt.private_auth_token}; ct0=${opt.private_csrf_token};`,
  145. 'X-CSRF-Token': opt.private_csrf_token,
  146. },
  147. });
  148. this.lockfile = opt.lockfile;
  149. this.lock = opt.lock;
  150. this.workInterval = opt.workInterval;
  151. this.bot = opt.bot;
  152. this.mode = opt.mode;
  153. ScreenNameNormalizer._queryUser = this.queryUser;
  154. sendAllFleets = (username, receiver) => {
  155. this.client.get('users/show', {screen_name: username})
  156. .then((user: FullUser) => {
  157. const feed = `https://twitter.com/${user.screen_name}`;
  158. return this.getFleets(user.id_str)
  159. .catch(error => {
  160. logger.error(`unhandled error while fetching fleets for ${feed}: ${JSON.stringify(error)}`);
  161. this.bot.sendTo(receiver, `获取 Fleets 时出现错误:${error}`);
  162. })
  163. .then((fleetFeed: IFleetFeed) => {
  164. if (!fleetFeed || fleetFeed.fleet_threads.length === 0) {
  165. this.bot.sendTo(receiver, `当前用户(@${user.screen_name})没有可用的 Fleets。`);
  166. return;
  167. }
  168. this.workOnFleets(user, fleetFeed.fleet_threads[0].fleets, this.sendFleets(`thread ${feed}`, receiver));
  169. });
  170. })
  171. .catch((err: {code: number, message: string}[]) => {
  172. if (err[0].code !== 50) {
  173. logger.warn(`error looking up user: ${err[0].message}, unable to fetch fleets`);
  174. }
  175. this.bot.sendTo(receiver, `找不到用户 ${username.replace(/^@?(.*)$/, '@$1')}。`);
  176. });
  177. };
  178. }
  179. public launch = () => {
  180. this.webshot = new Webshot(
  181. this.mode,
  182. () => setTimeout(this.work, this.workInterval * 1000)
  183. );
  184. }
  185. public queryUser = (username: string) =>
  186. this.client.get('users/show', {screen_name: username})
  187. .then((user: FullUser) => {
  188. ScreenNameNormalizer.savePermaFeedForUser(user);
  189. return user.screen_name;
  190. })
  191. private workOnFleets = (
  192. user: FullUser,
  193. fleets: Fleets,
  194. sendFleets: (msg: MessageChain, text: string) => void
  195. ) => {
  196. const uploader = (
  197. message: ReturnType<typeof Message.Image>,
  198. lastResort: (...args) => ReturnType<typeof Message.Plain>
  199. ) => {
  200. let timeout = uploadTimeout;
  201. return retryOnError(() =>
  202. this.bot.uploadPic(message, timeout).then(() => message),
  203. (_, count, terminate: (defaultValue: ReturnType<typeof Message.Plain>) => void) => {
  204. if (count <= maxTrials) {
  205. timeout *= (count + 2) / (count + 1);
  206. logger.warn(`retry uploading for the ${ordinal(count)} time...`);
  207. } else {
  208. logger.warn(`${count - 1} consecutive failures while uploading, trying plain text instead...`);
  209. terminate(lastResort());
  210. }
  211. });
  212. };
  213. return this.webshot(user, fleets, uploader, sendFleets, this.webshotDelay);
  214. }
  215. private sendFleets = (source?: string, ...to: IChat[]) =>
  216. (msg: MessageChain, text: string) => {
  217. to.forEach(subscriber => {
  218. logger.info(`pushing data${source ? ` of ${source}` : ''} to ${JSON.stringify(subscriber)}`);
  219. retryOnError(
  220. () => this.bot.sendTo(subscriber, msg),
  221. (_, count, terminate: (doNothing: Promise<void>) => void) => {
  222. if (count <= maxTrials) {
  223. logger.warn(`retry sending to ${subscriber.chatID} for the ${ordinal(count)} time...`);
  224. } else {
  225. logger.warn(`${count - 1} consecutive failures while sending` +
  226. 'message chain, trying plain text instead...');
  227. terminate(this.bot.sendTo(subscriber, text));
  228. }
  229. });
  230. });
  231. }
  232. private getFleets = (userID: string) => new Promise<IFleetFeed | void>((resolve, reject) => {
  233. const endpoint = `https://api.twitter.com/fleets/v1/user_fleets?user_id=${userID}`;
  234. this.privateClient.get(endpoint, (error, fleetFeed: IFleetFeed, _) => {
  235. if (error) reject(error);
  236. else resolve(fleetFeed);
  237. });
  238. })
  239. public work = () => {
  240. const lock = this.lock;
  241. if (this.workInterval < 1) this.workInterval = 1;
  242. if (lock.feed.length === 0) {
  243. setTimeout(() => {
  244. this.work();
  245. }, this.workInterval * 1000);
  246. return;
  247. }
  248. if (lock.workon >= lock.feed.length) lock.workon = 0;
  249. if (!lock.threads[lock.feed[lock.workon]] ||
  250. !lock.threads[lock.feed[lock.workon]].subscribers ||
  251. lock.threads[lock.feed[lock.workon]].subscribers.length === 0) {
  252. logger.warn(`nobody subscribes thread ${lock.feed[lock.workon]}, removing from feed`);
  253. delete lock.threads[lock.feed[lock.workon]];
  254. lock.feed.splice(lock.workon, 1);
  255. fs.writeFileSync(path.resolve(this.lockfile), JSON.stringify(lock));
  256. this.work();
  257. return;
  258. }
  259. const currentFeed = lock.feed[lock.workon];
  260. logger.debug(`pulling feed ${currentFeed}`);
  261. let user: FullUser;
  262. let match = currentFeed.match(/https:\/\/twitter.com\/([^\/]+)/);
  263. if (match) match = lock.threads[currentFeed].permaFeed.match(/https:\/\/twitter.com\/i\/user\/([^\/]+)/);
  264. if (!match) {
  265. logger.error(`cannot get endpoint for feed ${currentFeed}`);
  266. return;
  267. }
  268. this.client.get('users/show', {user_id: match[1]})
  269. .then((fullUser: FullUser) => { user = fullUser; return this.getFleets(match[1]); })
  270. .catch(error => {
  271. logger.error(`unhandled error on fetching fleets for ${currentFeed}: ${JSON.stringify(error)}`);
  272. })
  273. .then((fleetFeed: IFleetFeed) => {
  274. logger.debug(`private api returned ${JSON.stringify(fleetFeed)} for feed ${currentFeed}`);
  275. logger.debug(`api returned ${JSON.stringify(user)} for owner of feed ${currentFeed}`);
  276. const currentThread = lock.threads[currentFeed];
  277. const updateDate = () => currentThread.updatedAt = new Date().toString();
  278. if (!fleetFeed || fleetFeed.fleet_threads.length === 0) { updateDate(); return; }
  279. let fleets = fleetFeed.fleet_threads[0].fleets;
  280. const bottomOfFeed = fleets.slice(-1)[0].fleet_id.substring(3);
  281. const updateOffset = () => currentThread.offset = bottomOfFeed;
  282. if (currentThread.offset === '-1') { updateOffset(); return; }
  283. if (currentThread.offset !== '0') {
  284. const readCount = fleets.findIndex(fleet =>
  285. Number(BigNumOps.plus(fleet.fleet_id.substring(3), `-${currentThread.offset}`)) > 0);
  286. if (readCount === -1) return;
  287. fleets = fleets.slice(readCount);
  288. }
  289. return this.workOnFleets(user, fleets, this.sendFleets(`thread ${currentFeed}`, ...currentThread.subscribers))
  290. .then(updateDate).then(updateOffset);
  291. })
  292. .then(() => {
  293. lock.workon++;
  294. let timeout = this.workInterval * 1000 / lock.feed.length;
  295. if (timeout < 1000) timeout = 1000;
  296. fs.writeFileSync(path.resolve(this.lockfile), JSON.stringify(lock));
  297. setTimeout(() => {
  298. this.work();
  299. }, timeout);
  300. });
  301. }
  302. }