twitter.ts 9.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292
  1. import * as fs from 'fs';
  2. import * as path from 'path';
  3. import * as Twitter from 'twitter';
  4. import TwitterTypes from 'twitter-d';
  5. import { getLogger } from './loggers';
  6. import QQBot, { Message, MessageChain } from './mirai';
  7. import Webshot from './webshot';
  8. interface IWorkerOption {
  9. lock: ILock;
  10. lockfile: string;
  11. bot: QQBot;
  12. workInterval: number;
  13. webshotDelay: number;
  14. consumer_key: string;
  15. consumer_secret: string;
  16. access_token_key: string;
  17. access_token_secret: string;
  18. mode: number;
  19. }
  20. export class ScreenNameNormalizer {
  21. // tslint:disable-next-line: variable-name
  22. public static _queryUser: (username: string) => Promise<string>;
  23. public static normalize = (username: string) => username.toLowerCase().replace(/^@/, '');
  24. public static async normalizeLive(username: string) {
  25. if (this._queryUser) {
  26. return await this._queryUser(username)
  27. .catch((err: {code: number, message: string}[]) => {
  28. if (err[0].code !== 50) {
  29. logger.warn(`error looking up user: ${err[0].message}`);
  30. return username;
  31. }
  32. return null;
  33. });
  34. }
  35. return this.normalize(username);
  36. }
  37. }
  38. export let sendTweet = (id: string, receiver: IChat): void => {
  39. throw Error();
  40. };
  41. const logger = getLogger('twitter');
  42. const maxTrials = 3;
  43. const uploadTimeout = 10000;
  44. const retryInterval = 1500;
  45. const ordinal = (n: number) => {
  46. switch ((~~(n / 10) % 10 === 1) ? 0 : n % 10) {
  47. case 1:
  48. return `${n}st`;
  49. case 2:
  50. return `${n}nd`;
  51. case 3:
  52. return `${n}rd`;
  53. default:
  54. return `${n}th`;
  55. }
  56. };
  57. const retryOnError = <T, U>(
  58. doWork: () => Promise<T>,
  59. onRetry: (error, count: number, terminate: (defaultValue: U) => void) => void
  60. ) => new Promise<T | U>(resolve => {
  61. const retry = (reason, count: number) => {
  62. setTimeout(() => {
  63. let terminate = false;
  64. onRetry(reason, count, defaultValue => { terminate = true; resolve(defaultValue); });
  65. if (!terminate) doWork().then(resolve).catch(error => retry(error, count + 1));
  66. }, retryInterval);
  67. };
  68. doWork().then(resolve).catch(error => retry(error, 1));
  69. });
  70. export type FullUser = TwitterTypes.FullUser;
  71. export type Entities = TwitterTypes.Entities;
  72. export type ExtendedEntities = TwitterTypes.ExtendedEntities;
  73. export type MediaEntity = TwitterTypes.MediaEntity;
  74. interface ITweet extends TwitterTypes.Status {
  75. user: FullUser;
  76. retweeted_status?: Tweet;
  77. }
  78. export type Tweet = ITweet;
  79. export type Tweets = ITweet[];
  80. export default class {
  81. private client: Twitter;
  82. private lock: ILock;
  83. private lockfile: string;
  84. private workInterval: number;
  85. private bot: QQBot;
  86. private webshotDelay: number;
  87. private webshot: Webshot;
  88. private mode: number;
  89. constructor(opt: IWorkerOption) {
  90. this.client = new Twitter({
  91. consumer_key: opt.consumer_key,
  92. consumer_secret: opt.consumer_secret,
  93. access_token_key: opt.access_token_key,
  94. access_token_secret: opt.access_token_secret,
  95. });
  96. this.lockfile = opt.lockfile;
  97. this.lock = opt.lock;
  98. this.workInterval = opt.workInterval;
  99. this.bot = opt.bot;
  100. this.webshotDelay = opt.webshotDelay;
  101. this.mode = opt.mode;
  102. ScreenNameNormalizer._queryUser = this.queryUser;
  103. sendTweet = (id, receiver) => {
  104. this.getTweet(id, this.sendTweets(`tweet ${id}`, receiver))
  105. .catch((err: {code: number, message: string}[]) => {
  106. if (err[0].code !== 144) {
  107. logger.warn(`error retrieving tweet: ${err[0].message}`);
  108. this.bot.sendTo(receiver, `获取推文时出现错误:${err[0].message}`);
  109. }
  110. this.bot.sendTo(receiver, '找不到请求的推文,它可能已被删除。');
  111. });
  112. };
  113. }
  114. public launch = () => {
  115. this.webshot = new Webshot(
  116. this.mode,
  117. () => setTimeout(this.work, this.workInterval * 1000)
  118. );
  119. }
  120. public queryUser = (username: string) =>
  121. this.client.get('users/show', {screen_name: username})
  122. .then((user: FullUser) => user.screen_name)
  123. private workOnTweets = (
  124. tweets: Tweets,
  125. sendTweets: (msg: MessageChain, text: string, author: string) => void
  126. ) => {
  127. const uploader = (
  128. message: ReturnType<typeof Message.Image>,
  129. lastResort: (...args) => ReturnType<typeof Message.Plain>
  130. ) => {
  131. let timeout = uploadTimeout;
  132. return retryOnError(() =>
  133. this.bot.uploadPic(message, timeout).then(() => message),
  134. (_, count, terminate: (defaultValue: ReturnType<typeof Message.Plain>) => void) => {
  135. if (count <= maxTrials) {
  136. timeout *= (count + 2) / (count + 1);
  137. logger.warn(`retry uploading for the ${ordinal(count)} time...`);
  138. } else {
  139. logger.warn(`${count - 1} consecutive failures while uploading, trying plain text instead...`);
  140. terminate(lastResort());
  141. }
  142. });
  143. };
  144. return this.webshot(tweets, uploader, sendTweets, this.webshotDelay);
  145. }
  146. public getTweet = (id: string, sender: (msg: MessageChain, text: string, author: string) => void) => {
  147. const endpoint = 'statuses/show';
  148. const config = {
  149. id,
  150. tweet_mode: 'extended',
  151. };
  152. return this.client.get(endpoint, config)
  153. .then((tweet: Tweet) => this.workOnTweets([tweet], sender));
  154. }
  155. private sendTweets = (source?: string, ...to: IChat[]) =>
  156. (msg: MessageChain, text: string, author: string) => {
  157. to.forEach(subscriber => {
  158. logger.info(`pushing data${source ? ` of ${source}` : ''} to ${JSON.stringify(subscriber)}`);
  159. retryOnError(
  160. () => this.bot.sendTo(subscriber, msg),
  161. (_, count, terminate: (doNothing: Promise<void>) => void) => {
  162. if (count <= maxTrials) {
  163. logger.warn(`retry sending to ${subscriber.chatID} for the ${ordinal(count)} time...`);
  164. } else {
  165. logger.warn(`${count - 1} consecutive failures while sending` +
  166. 'message chain, trying plain text instead...');
  167. terminate(this.bot.sendTo(subscriber, author + text));
  168. }
  169. });
  170. });
  171. }
  172. public work = () => {
  173. const lock = this.lock;
  174. if (this.workInterval < 1) this.workInterval = 1;
  175. if (lock.feed.length === 0) {
  176. setTimeout(() => {
  177. this.work();
  178. }, this.workInterval * 1000);
  179. return;
  180. }
  181. if (lock.workon >= lock.feed.length) lock.workon = 0;
  182. if (!lock.threads[lock.feed[lock.workon]] ||
  183. !lock.threads[lock.feed[lock.workon]].subscribers ||
  184. lock.threads[lock.feed[lock.workon]].subscribers.length === 0) {
  185. logger.warn(`nobody subscribes thread ${lock.feed[lock.workon]}, removing from feed`);
  186. delete lock.threads[lock.feed[lock.workon]];
  187. lock.feed.splice(lock.workon, 1);
  188. fs.writeFileSync(path.resolve(this.lockfile), JSON.stringify(lock));
  189. this.work();
  190. return;
  191. }
  192. const currentFeed = lock.feed[lock.workon];
  193. logger.debug(`pulling feed ${currentFeed}`);
  194. const promise = new Promise(resolve => {
  195. let match = currentFeed.match(/https:\/\/twitter.com\/([^\/]+)\/lists\/([^\/]+)/);
  196. let config: any;
  197. let endpoint: string;
  198. if (match) {
  199. if (match[1] === 'i') {
  200. config = {
  201. list_id: match[2],
  202. tweet_mode: 'extended',
  203. };
  204. } else {
  205. config = {
  206. owner_screen_name: match[1],
  207. slug: match[2],
  208. tweet_mode: 'extended',
  209. };
  210. }
  211. endpoint = 'lists/statuses';
  212. } else {
  213. match = currentFeed.match(/https:\/\/twitter.com\/([^\/]+)/);
  214. if (match) {
  215. config = {
  216. screen_name: match[1],
  217. exclude_replies: false,
  218. tweet_mode: 'extended',
  219. };
  220. endpoint = 'statuses/user_timeline';
  221. }
  222. }
  223. if (endpoint) {
  224. const offset = lock.threads[currentFeed].offset as unknown as number;
  225. if (offset > 0) config.since_id = offset;
  226. this.client.get(endpoint, config, (error, tweets, response) => {
  227. if (error) {
  228. if (error instanceof Array && error.length > 0 && error[0].code === 34) {
  229. logger.warn(`error on fetching tweets for ${currentFeed}: ${JSON.stringify(error)}`);
  230. lock.threads[currentFeed].subscribers.forEach(subscriber => {
  231. logger.info(`sending notfound message of ${currentFeed} to ${JSON.stringify(subscriber)}`);
  232. this.bot.sendTo(subscriber, `链接 ${currentFeed} 指向的用户或列表不存在,请退订。`).catch();
  233. });
  234. } else {
  235. logger.error(`unhandled error on fetching tweets for ${currentFeed}: ${JSON.stringify(error)}`);
  236. }
  237. resolve();
  238. } else resolve(tweets);
  239. });
  240. }
  241. });
  242. promise.then((tweets: Tweets) => {
  243. logger.debug(`api returned ${JSON.stringify(tweets)} for feed ${currentFeed}`);
  244. const currentThread = lock.threads[currentFeed];
  245. const updateDate = () => currentThread.updatedAt = new Date().toString();
  246. if (!tweets || tweets.length === 0) { updateDate(); return; }
  247. const topOfFeed = tweets[0].id_str;
  248. const updateOffset = () => currentThread.offset = topOfFeed;
  249. if (currentThread.offset === '-1') { updateOffset(); return; }
  250. if (currentThread.offset === '0') tweets.splice(1);
  251. return this.workOnTweets(tweets, this.sendTweets(`thread ${currentFeed}`, ...currentThread.subscribers))
  252. .then(updateDate).then(updateOffset);
  253. })
  254. .then(() => {
  255. lock.workon++;
  256. let timeout = this.workInterval * 1000 / lock.feed.length;
  257. if (timeout < 1000) timeout = 1000;
  258. fs.writeFileSync(path.resolve(this.lockfile), JSON.stringify(lock));
  259. setTimeout(() => {
  260. this.work();
  261. }, timeout);
  262. });
  263. }
  264. }