format.ts 7.6 KB

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