format.ts 8.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279
  1. import { Tweet } from './twitter.ts';
  2. class SafeString {
  3. constructor(readonly raw: string) {}
  4. get length(): number {
  5. return this.raw.length;
  6. }
  7. toString(): string {
  8. return this.raw;
  9. }
  10. toJSON(): string {
  11. return this.raw;
  12. }
  13. }
  14. type StringLike = string | SafeString;
  15. function escapeHTML(unsafe: string): StringLike {
  16. return new SafeString(
  17. unsafe
  18. .replace(/&/g, "&")
  19. .replace(/</g, "&lt;")
  20. .replace(/>/g, "&gt;")
  21. .replace(/"/g, "&quot;")
  22. .replace(/'/g, "&#039;")
  23. );
  24. }
  25. function unescapeHTML(safe: string): string {
  26. return safe
  27. .replace(/&amp;/g, "&")
  28. .replace(/&lt;/g, "<")
  29. .replace(/&gt;/g, ">")
  30. .replace(/"/g, "&quot;")
  31. .replace(/'/g, "&#039;");
  32. }
  33. function joinChildren(children: StringLike[]): SafeString {
  34. return new SafeString(children
  35. .map(child => typeof child === 'string' ? escapeHTML(child) : child)
  36. .join('')
  37. );
  38. }
  39. function tag(tag: string, attributes: Record<string, string> = {}, children: StringLike | StringLike[] = []): SafeString {
  40. const attrs = Object.entries(attributes).map(([ key, value ]) => {
  41. return ` ${key}="${escapeHTML(value)}"`;
  42. }).join('');
  43. if (children.length === 0) {
  44. return new SafeString(`<${tag}${attrs} />`);
  45. } else {
  46. const childrenArray = Array.isArray(children) ? children : [children];
  47. const normalizedChildren = joinChildren(childrenArray);
  48. return new SafeString(`<${tag}${attrs}>${normalizedChildren}</${tag}>`);
  49. }
  50. }
  51. function buildTwitterUrl(url: string): string {
  52. return new URL(url, 'https://twitter.com').toString();
  53. }
  54. function buildProxyUrl(url: string): string {
  55. const search = new URLSearchParams({ target: url }).toString();
  56. return `/__proxy?${search}`;
  57. }
  58. function formatPlainText(text: string): SafeString {
  59. // apparently twitter already escapes the text for you
  60. return new SafeString(text.replace(/\n/g, "<br />"));
  61. }
  62. class TextFormatter {
  63. private splices: { text: StringLike, indices: [number, number] }[];
  64. private media: { type: 'video' | 'img', url: string, loop: boolean, link?: string }[];
  65. private characters: string[];
  66. constructor(readonly tweet: Tweet, readonly useProxy: boolean) {
  67. this.characters = [...tweet.full_text];
  68. this.splices = [];
  69. this.media = [];
  70. for (const { indices, text } of tweet.entities.hashtags) {
  71. const url = buildTwitterUrl(`/hashtag/${text}`);
  72. this.splices.push({
  73. indices,
  74. text: tag('a', { href: url }, `#${text}`),
  75. });
  76. }
  77. for (const link of tweet.entities.urls) {
  78. const url = new URL(link.expanded_url).toString();
  79. this.splices.push({
  80. indices: link.indices,
  81. text: tag('a', { href: url }, link.display_url),
  82. });
  83. }
  84. for (const { indices, name, screen_name } of tweet.entities.user_mentions) {
  85. const url = buildTwitterUrl(`/${screen_name}`);
  86. this.splices.push({
  87. indices: indices,
  88. text: tag('a', { href: url, title: name }, `@${screen_name}`),
  89. });
  90. }
  91. const media = tweet.extended_entities?.media ?? [];
  92. for (const item of media) {
  93. if (item.type === 'photo') {
  94. const url = new URL(item.media_url_https).toString();
  95. this.media.push({ type: 'img', url, loop: false });
  96. } else if (item.video_info !== undefined) {
  97. let max = -1;
  98. let maxUrl: string | undefined = undefined;
  99. for (const variant of item.video_info.variants) {
  100. if (variant.bitrate === undefined) {
  101. continue;
  102. }
  103. if (variant.bitrate > max) {
  104. max = variant.bitrate;
  105. maxUrl = variant.url;
  106. }
  107. }
  108. const loop = item.type === 'animated_gif';
  109. if (maxUrl !== undefined) {
  110. const url = new URL(maxUrl).toString();
  111. this.media.push({ type: 'video', url, loop });
  112. } else {
  113. const url = new URL(item.media_url_https).toString();
  114. this.media.push({ type: 'img', url, link: item.expanded_url, loop });
  115. }
  116. }
  117. }
  118. }
  119. getRange(start: number, end?: number): string {
  120. const max = this.tweet.display_text_range[1];
  121. return this.characters.slice(start, end ?? max).join('');
  122. }
  123. headerHTML(): SafeString {
  124. const date = new Date(this.tweet.created_at);
  125. const dateOptions = {
  126. weekday: 'short',
  127. year: 'numeric',
  128. month: '2-digit',
  129. day: '2-digit',
  130. hour: '2-digit',
  131. minute: '2-digit',
  132. timeZoneName: 'short',
  133. } as const;
  134. const imageUrl = new URL(this.tweet.user.profile_image_url_https).toString();
  135. const imageSrc = this.useProxy ? buildProxyUrl(imageUrl) : imageUrl;
  136. const profileUrl = buildTwitterUrl(`/${this.tweet.user.screen_name}`);
  137. const tweetUrl = buildTwitterUrl(`/${this.tweet.user.screen_name}/status/${this.tweet.id_str}`);
  138. const html = [
  139. tag('img', { loading: 'lazy', src: imageSrc, height: '24px', width: '24px' }),
  140. ' ',
  141. tag('strong', {}, this.tweet.user.name),
  142. ' ',
  143. tag('a', { href: profileUrl }, `@${this.tweet.user.screen_name}`),
  144. tag('br'),
  145. 'Posted ',
  146. tag('a', { href: tweetUrl }, date.toLocaleString(this.tweet.lang, dateOptions)),
  147. ];
  148. return joinChildren(html);
  149. }
  150. bodyHTML(): SafeString {
  151. const max = this.tweet.display_text_range[1];
  152. const splices = this.splices
  153. .filter(({ indices }) => indices[0] < max && indices[1] <= max)
  154. .sort((a, b) => a.indices[0] - b.indices[0]);
  155. let index = 0;
  156. const html: StringLike[] = [];
  157. for (const { text, indices } of splices) {
  158. const start = index;
  159. const end = indices[0];
  160. html.push(formatPlainText(this.getRange(start, end)));
  161. html.push(text);
  162. index = indices[1];
  163. }
  164. html.push(formatPlainText(this.getRange(index)));
  165. for (const { type, url, link, loop } of this.media) {
  166. html.push(tag('br'));
  167. html.push(tag('br'));
  168. const src = this.useProxy ? buildProxyUrl(url) : url;
  169. if (type === 'img') {
  170. html.push(tag('a', { href: link ?? url }, [
  171. tag('img', { loading: 'lazy', src }),
  172. ]));
  173. } else if (type === 'video') {
  174. html.push(tag('video', { controls: '', src, loop: `${loop}` }));
  175. }
  176. }
  177. return joinChildren(html);
  178. }
  179. toHTML(): SafeString {
  180. return joinChildren([ this.headerHTML(), tag('br'), this.bodyHTML() ]);
  181. }
  182. }
  183. const STYLES = `
  184. body > div {
  185. margin: 10px;
  186. padding: 10px;
  187. border: solid 1px gray;
  188. border-radius: 10px;
  189. }
  190. blockquote {
  191. padding: 10px;
  192. border: solid 1px lightgray;
  193. border-radius: 10px;
  194. }
  195. div {
  196. max-width: 600px;
  197. }
  198. img, video {
  199. max-width: 100%;
  200. }
  201. `;
  202. export function timelineAsHTML(tweets: Tweet[]): string {
  203. const body = tweets.map(tweet => {
  204. const displayTweet = tweet.retweeted_status ?? tweet;
  205. const children: StringLike[] = [];
  206. children.push(new TextFormatter(displayTweet, true).toHTML());
  207. const quoteTweet = displayTweet.quoted_status;
  208. if (quoteTweet !== undefined) {
  209. children.push(tag('blockquote', {}, new TextFormatter(quoteTweet, true).toHTML()));
  210. }
  211. return tag('div', {}, children);
  212. }).join('\n');
  213. return `
  214. <html>
  215. <head>
  216. <style>${STYLES}</style>
  217. </head>
  218. <body>${body}</body>
  219. </html>
  220. `;
  221. }
  222. export function timelineAsJSON(username: string, tweets: Tweet[]): string {
  223. const items = tweets.map(tweet => {
  224. const displayTweet = tweet.retweeted_status ?? tweet;
  225. const children: StringLike[] = [];
  226. children.push(new TextFormatter(displayTweet, false).bodyHTML());
  227. const quoteTweet = displayTweet.quoted_status;
  228. if (quoteTweet !== undefined) {
  229. children.push(tag('blockquote', {}, [
  230. new TextFormatter(quoteTweet, false).toHTML(),
  231. ]));
  232. }
  233. const html = joinChildren(children);
  234. return {
  235. id: tweet.id_str,
  236. title: unescapeHTML(tweet.full_text.split('\n')[0]),
  237. url: buildTwitterUrl(`/${tweet.user.screen_name}/status/${tweet.id_str}`),
  238. content_html: html,
  239. date_published: new Date(tweet.created_at).toISOString(),
  240. authors: [{
  241. name: `${displayTweet.user.name} - @${displayTweet.user.screen_name}`,
  242. url: buildTwitterUrl(`/${displayTweet.user.screen_name}`),
  243. avatar: displayTweet.user.profile_image_url_https,
  244. }],
  245. };
  246. });
  247. return JSON.stringify({
  248. version: '1.1',
  249. title: `Twitter @${username}`,
  250. home_page_url: buildTwitterUrl(`/${username}`),
  251. items,
  252. });
  253. }