mirror of https://git.lenooby09.tech/LeNooby09/social-app.git
1import {Dimensions} from 'react-native'
2
3import {isSafari} from '#/lib/browser'
4import {isWeb} from '#/platform/detection'
5
6const {height: SCREEN_HEIGHT} = Dimensions.get('window')
7
8const IFRAME_HOST = isWeb
9 ? // @ts-ignore only for web
10 window.location.host === 'localhost:8100'
11 ? 'http://localhost:8100'
12 : 'https://bsky.app'
13 : __DEV__ && !process.env.JEST_WORKER_ID
14 ? 'http://localhost:8100'
15 : 'https://bsky.app'
16
17export const embedPlayerSources = [
18 'youtube',
19 'youtubeShorts',
20 'twitch',
21 'spotify',
22 'soundcloud',
23 'appleMusic',
24 'vimeo',
25 'giphy',
26 'tenor',
27 'flickr',
28] as const
29
30export type EmbedPlayerSource = (typeof embedPlayerSources)[number]
31
32export type EmbedPlayerType =
33 | 'youtube_video'
34 | 'youtube_short'
35 | 'twitch_video'
36 | 'spotify_album'
37 | 'spotify_playlist'
38 | 'spotify_song'
39 | 'soundcloud_track'
40 | 'soundcloud_set'
41 | 'apple_music_playlist'
42 | 'apple_music_album'
43 | 'apple_music_song'
44 | 'vimeo_video'
45 | 'giphy_gif'
46 | 'tenor_gif'
47 | 'flickr_album'
48
49export const externalEmbedLabels: Record<EmbedPlayerSource, string> = {
50 youtube: 'YouTube',
51 youtubeShorts: 'YouTube Shorts',
52 vimeo: 'Vimeo',
53 twitch: 'Twitch',
54 giphy: 'GIPHY',
55 tenor: 'Tenor',
56 spotify: 'Spotify',
57 appleMusic: 'Apple Music',
58 soundcloud: 'SoundCloud',
59 flickr: 'Flickr',
60}
61
62export interface EmbedPlayerParams {
63 type: EmbedPlayerType
64 playerUri: string
65 isGif?: boolean
66 source: EmbedPlayerSource
67 metaUri?: string
68 hideDetails?: boolean
69 dimensions?: {
70 height: number
71 width: number
72 }
73}
74
75const giphyRegex = /media(?:[0-4]\.giphy\.com|\.giphy\.com)/i
76const gifFilenameRegex = /^(\S+)\.(webp|gif|mp4)$/i
77
78export function parseEmbedPlayerFromUrl(
79 url: string,
80): EmbedPlayerParams | undefined {
81 let urlp
82 try {
83 urlp = new URL(url)
84 } catch (e) {
85 return undefined
86 }
87
88 // youtube
89 if (urlp.hostname === 'youtu.be') {
90 const videoId = urlp.pathname.split('/')[1]
91 const t = urlp.searchParams.get('t') ?? '0'
92 const seek = encodeURIComponent(t.replace(/s$/, ''))
93
94 if (videoId) {
95 return {
96 type: 'youtube_video',
97 source: 'youtube',
98 playerUri: `${IFRAME_HOST}/iframe/youtube.html?videoId=${videoId}&start=${seek}`,
99 }
100 }
101 }
102 if (
103 urlp.hostname === 'www.youtube.com' ||
104 urlp.hostname === 'youtube.com' ||
105 urlp.hostname === 'm.youtube.com' ||
106 urlp.hostname === 'music.youtube.com'
107 ) {
108 const [_, page, shortOrLiveVideoId] = urlp.pathname.split('/')
109
110 const isShorts = page === 'shorts'
111 const isLive = page === 'live'
112 const videoId =
113 isShorts || isLive
114 ? shortOrLiveVideoId
115 : (urlp.searchParams.get('v') as string)
116 const t = urlp.searchParams.get('t') ?? '0'
117 const seek = encodeURIComponent(t.replace(/s$/, ''))
118
119 if (videoId) {
120 return {
121 type: isShorts ? 'youtube_short' : 'youtube_video',
122 source: isShorts ? 'youtubeShorts' : 'youtube',
123 hideDetails: isShorts ? true : undefined,
124 playerUri: `${IFRAME_HOST}/iframe/youtube.html?videoId=${videoId}&start=${seek}`,
125 }
126 }
127 }
128
129 // twitch
130 if (
131 urlp.hostname === 'twitch.tv' ||
132 urlp.hostname === 'www.twitch.tv' ||
133 urlp.hostname === 'm.twitch.tv'
134 ) {
135 const parent = isWeb
136 ? // @ts-ignore only for web
137 window.location.hostname
138 : 'localhost'
139
140 const [_, channelOrVideo, clipOrId, id] = urlp.pathname.split('/')
141
142 if (channelOrVideo === 'videos') {
143 return {
144 type: 'twitch_video',
145 source: 'twitch',
146 playerUri: `https://player.twitch.tv/?volume=0.5&!muted&autoplay&video=${clipOrId}&parent=${parent}`,
147 }
148 } else if (clipOrId === 'clip') {
149 return {
150 type: 'twitch_video',
151 source: 'twitch',
152 playerUri: `https://clips.twitch.tv/embed?volume=0.5&autoplay=true&clip=${id}&parent=${parent}`,
153 }
154 } else if (channelOrVideo) {
155 return {
156 type: 'twitch_video',
157 source: 'twitch',
158 playerUri: `https://player.twitch.tv/?volume=0.5&!muted&autoplay&channel=${channelOrVideo}&parent=${parent}`,
159 }
160 }
161 }
162
163 // spotify
164 if (urlp.hostname === 'open.spotify.com') {
165 const [_, typeOrLocale, idOrType, id] = urlp.pathname.split('/')
166
167 if (idOrType) {
168 if (typeOrLocale === 'playlist' || idOrType === 'playlist') {
169 return {
170 type: 'spotify_playlist',
171 source: 'spotify',
172 playerUri: `https://open.spotify.com/embed/playlist/${
173 id ?? idOrType
174 }`,
175 }
176 }
177 if (typeOrLocale === 'album' || idOrType === 'album') {
178 return {
179 type: 'spotify_album',
180 source: 'spotify',
181 playerUri: `https://open.spotify.com/embed/album/${id ?? idOrType}`,
182 }
183 }
184 if (typeOrLocale === 'track' || idOrType === 'track') {
185 return {
186 type: 'spotify_song',
187 source: 'spotify',
188 playerUri: `https://open.spotify.com/embed/track/${id ?? idOrType}`,
189 }
190 }
191 if (typeOrLocale === 'episode' || idOrType === 'episode') {
192 return {
193 type: 'spotify_song',
194 source: 'spotify',
195 playerUri: `https://open.spotify.com/embed/episode/${id ?? idOrType}`,
196 }
197 }
198 if (typeOrLocale === 'show' || idOrType === 'show') {
199 return {
200 type: 'spotify_song',
201 source: 'spotify',
202 playerUri: `https://open.spotify.com/embed/show/${id ?? idOrType}`,
203 }
204 }
205 }
206 }
207
208 // soundcloud
209 if (
210 urlp.hostname === 'soundcloud.com' ||
211 urlp.hostname === 'www.soundcloud.com'
212 ) {
213 const [_, user, trackOrSets, set] = urlp.pathname.split('/')
214
215 if (user && trackOrSets) {
216 if (trackOrSets === 'sets' && set) {
217 return {
218 type: 'soundcloud_set',
219 source: 'soundcloud',
220 playerUri: `https://w.soundcloud.com/player/?url=${url}&auto_play=true&visual=false&hide_related=true`,
221 }
222 }
223
224 return {
225 type: 'soundcloud_track',
226 source: 'soundcloud',
227 playerUri: `https://w.soundcloud.com/player/?url=${url}&auto_play=true&visual=false&hide_related=true`,
228 }
229 }
230 }
231
232 if (
233 urlp.hostname === 'music.apple.com' ||
234 urlp.hostname === 'music.apple.com'
235 ) {
236 // This should always have: locale, type (playlist or album), name, and id. We won't use spread since we want
237 // to check if the length is correct
238 const pathParams = urlp.pathname.split('/')
239 const type = pathParams[2]
240 const songId = urlp.searchParams.get('i')
241
242 if (pathParams.length === 5 && (type === 'playlist' || type === 'album')) {
243 // We want to append the songId to the end of the url if it exists
244 const embedUri = `https://embed.music.apple.com${urlp.pathname}${
245 urlp.search ? '?i=' + songId : ''
246 }`
247
248 if (type === 'playlist') {
249 return {
250 type: 'apple_music_playlist',
251 source: 'appleMusic',
252 playerUri: embedUri,
253 }
254 } else if (type === 'album') {
255 if (songId) {
256 return {
257 type: 'apple_music_song',
258 source: 'appleMusic',
259 playerUri: embedUri,
260 }
261 } else {
262 return {
263 type: 'apple_music_album',
264 source: 'appleMusic',
265 playerUri: embedUri,
266 }
267 }
268 }
269 }
270 }
271
272 if (urlp.hostname === 'vimeo.com' || urlp.hostname === 'www.vimeo.com') {
273 const [_, videoId] = urlp.pathname.split('/')
274 if (videoId) {
275 return {
276 type: 'vimeo_video',
277 source: 'vimeo',
278 playerUri: `https://player.vimeo.com/video/${videoId}?autoplay=1`,
279 }
280 }
281 }
282
283 if (urlp.hostname === 'giphy.com' || urlp.hostname === 'www.giphy.com') {
284 const [_, gifs, nameAndId] = urlp.pathname.split('/')
285
286 /*
287 * nameAndId is a string that consists of the name (dash separated) and the id of the gif (the last part of the name)
288 * We want to get the id of the gif, then direct to media.giphy.com/media/{id}/giphy.webp so we can
289 * use it in an <Image> component
290 */
291
292 if (gifs === 'gifs' && nameAndId) {
293 const gifId = nameAndId.split('-').pop()
294
295 if (gifId) {
296 return {
297 type: 'giphy_gif',
298 source: 'giphy',
299 isGif: true,
300 hideDetails: true,
301 metaUri: `https://giphy.com/gifs/${gifId}`,
302 playerUri: `https://i.giphy.com/media/${gifId}/200.webp`,
303 }
304 }
305 }
306 }
307
308 // There are five possible hostnames that also can be giphy urls: media.giphy.com and media0-4.giphy.com
309 // These can include (presumably) a tracking id in the path name, so we have to check for that as well
310 if (giphyRegex.test(urlp.hostname)) {
311 // We can link directly to the gif, if its a proper link
312 const [_, media, trackingOrId, idOrFilename, filename] =
313 urlp.pathname.split('/')
314
315 if (media === 'media') {
316 if (idOrFilename && gifFilenameRegex.test(idOrFilename)) {
317 return {
318 type: 'giphy_gif',
319 source: 'giphy',
320 isGif: true,
321 hideDetails: true,
322 metaUri: `https://giphy.com/gifs/${trackingOrId}`,
323 playerUri: `https://i.giphy.com/media/${trackingOrId}/200.webp`,
324 }
325 } else if (filename && gifFilenameRegex.test(filename)) {
326 return {
327 type: 'giphy_gif',
328 source: 'giphy',
329 isGif: true,
330 hideDetails: true,
331 metaUri: `https://giphy.com/gifs/${idOrFilename}`,
332 playerUri: `https://i.giphy.com/media/${idOrFilename}/200.webp`,
333 }
334 }
335 }
336 }
337
338 // Finally, we should see if it is a link to i.giphy.com. These links don't necessarily end in .gif but can also
339 // be .webp
340 if (urlp.hostname === 'i.giphy.com' || urlp.hostname === 'www.i.giphy.com') {
341 const [_, mediaOrFilename, filename] = urlp.pathname.split('/')
342
343 if (mediaOrFilename === 'media' && filename) {
344 const gifId = filename.split('.')[0]
345 return {
346 type: 'giphy_gif',
347 source: 'giphy',
348 isGif: true,
349 hideDetails: true,
350 metaUri: `https://giphy.com/gifs/${gifId}`,
351 playerUri: `https://i.giphy.com/media/${gifId}/200.webp`,
352 }
353 } else if (mediaOrFilename) {
354 const gifId = mediaOrFilename.split('.')[0]
355 return {
356 type: 'giphy_gif',
357 source: 'giphy',
358 isGif: true,
359 hideDetails: true,
360 metaUri: `https://giphy.com/gifs/${gifId}`,
361 playerUri: `https://i.giphy.com/media/${
362 mediaOrFilename.split('.')[0]
363 }/200.webp`,
364 }
365 }
366 }
367
368 const tenorGif = parseTenorGif(urlp)
369 if (tenorGif.success) {
370 const {playerUri, dimensions} = tenorGif
371
372 return {
373 type: 'tenor_gif',
374 source: 'tenor',
375 isGif: true,
376 hideDetails: true,
377 playerUri,
378 dimensions,
379 }
380 }
381
382 // this is a standard flickr path! we can use the embedder for albums and groups, so validate the path
383 if (urlp.hostname === 'www.flickr.com' || urlp.hostname === 'flickr.com') {
384 let i = urlp.pathname.length - 1
385 while (i > 0 && urlp.pathname.charAt(i) === '/') {
386 --i
387 }
388
389 const path_components = urlp.pathname.slice(1, i + 1).split('/')
390 if (path_components.length === 4) {
391 // discard username - it's not relevant
392 const [photos, _, albums, id] = path_components
393 if (photos === 'photos' && albums === 'albums') {
394 // this at least has the shape of a valid photo-album URL!
395 return {
396 type: 'flickr_album',
397 source: 'flickr',
398 playerUri: `https://embedr.flickr.com/photosets/${id}`,
399 }
400 }
401 }
402
403 if (path_components.length === 3) {
404 const [groups, id, pool] = path_components
405 if (groups === 'groups' && pool === 'pool') {
406 return {
407 type: 'flickr_album',
408 source: 'flickr',
409 playerUri: `https://embedr.flickr.com/groups/${id}`,
410 }
411 }
412 }
413 // not an album or a group pool, don't know what to do with this!
414 return undefined
415 }
416
417 // link shortened flickr path
418 if (urlp.hostname === 'flic.kr') {
419 const b58alph = '123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ'
420 let [_, type, idBase58Enc] = urlp.pathname.split('/')
421 let id = 0n
422 for (const char of idBase58Enc) {
423 const nextIdx = b58alph.indexOf(char)
424 if (nextIdx >= 0) {
425 id = id * 58n + BigInt(nextIdx)
426 } else {
427 // not b58 encoded, ergo not a valid link to embed
428 return undefined
429 }
430 }
431
432 switch (type) {
433 case 'go':
434 const formattedGroupId = `${id}`
435 return {
436 type: 'flickr_album',
437 source: 'flickr',
438 playerUri: `https://embedr.flickr.com/groups/${formattedGroupId.slice(
439 0,
440 -2,
441 )}@N${formattedGroupId.slice(-2)}`,
442 }
443 case 's':
444 return {
445 type: 'flickr_album',
446 source: 'flickr',
447 playerUri: `https://embedr.flickr.com/photosets/${id}`,
448 }
449 default:
450 // we don't know what this is so we can't embed it
451 return undefined
452 }
453 }
454}
455
456export function getPlayerAspect({
457 type,
458 hasThumb,
459 width,
460}: {
461 type: EmbedPlayerParams['type']
462 hasThumb: boolean
463 width: number
464}): {aspectRatio?: number; height?: number} {
465 if (!hasThumb) return {aspectRatio: 16 / 9}
466
467 switch (type) {
468 case 'youtube_video':
469 case 'twitch_video':
470 case 'vimeo_video':
471 return {aspectRatio: 16 / 9}
472 case 'youtube_short':
473 if (SCREEN_HEIGHT < 600) {
474 return {aspectRatio: (9 / 16) * 1.75}
475 } else {
476 return {aspectRatio: (9 / 16) * 1.5}
477 }
478 case 'spotify_album':
479 case 'apple_music_album':
480 case 'apple_music_playlist':
481 case 'spotify_playlist':
482 case 'soundcloud_set':
483 return {height: 380}
484 case 'spotify_song':
485 if (width <= 300) {
486 return {height: 155}
487 }
488 return {height: 232}
489 case 'soundcloud_track':
490 return {height: 165}
491 case 'apple_music_song':
492 return {height: 150}
493 default:
494 return {aspectRatio: 16 / 9}
495 }
496}
497
498export function getGifDims(
499 originalHeight: number,
500 originalWidth: number,
501 viewWidth: number,
502) {
503 const scaledHeight = (originalHeight / originalWidth) * viewWidth
504
505 return {
506 height: scaledHeight > 250 ? 250 : scaledHeight,
507 width: (250 / scaledHeight) * viewWidth,
508 }
509}
510
511export function getGiphyMetaUri(url: URL) {
512 if (giphyRegex.test(url.hostname) || url.hostname === 'i.giphy.com') {
513 const params = parseEmbedPlayerFromUrl(url.toString())
514 if (params && params.type === 'giphy_gif') {
515 return params.metaUri
516 }
517 }
518}
519
520export function parseTenorGif(urlp: URL):
521 | {success: false}
522 | {
523 success: true
524 playerUri: string
525 dimensions: {height: number; width: number}
526 } {
527 if (urlp.hostname !== 'media.tenor.com') {
528 return {success: false}
529 }
530
531 let [_, id, filename] = urlp.pathname.split('/')
532
533 if (!id || !filename) {
534 return {success: false}
535 }
536
537 if (!id.includes('AAAAC')) {
538 return {success: false}
539 }
540
541 const h = urlp.searchParams.get('hh')
542 const w = urlp.searchParams.get('ww')
543
544 if (!h || !w) {
545 return {success: false}
546 }
547
548 const dimensions = {
549 height: Number(h),
550 width: Number(w),
551 }
552
553 if (isWeb) {
554 if (isSafari) {
555 id = id.replace('AAAAC', 'AAAP1')
556 filename = filename.replace('.gif', '.mp4')
557 } else {
558 id = id.replace('AAAAC', 'AAAP3')
559 filename = filename.replace('.gif', '.webm')
560 }
561 } else {
562 id = id.replace('AAAAC', 'AAAAM')
563 }
564
565 return {
566 success: true,
567 playerUri: `https://t.gifs.bsky.app/${id}/${filename}`,
568 dimensions,
569 }
570}