resolve short links

This commit is contained in:
Hailey
2024-06-26 16:52:03 -07:00
parent 2fc9fd9e22
commit d2f4f32b25
4 changed files with 46 additions and 24 deletions
+22
View File
@@ -0,0 +1,22 @@
import {logger} from '#/logger'
export async function resolveShortLink(shortLink: string) {
const controller = new AbortController()
const to = setTimeout(() => controller.abort(), 2e3)
try {
const res = await fetch(shortLink, {
method: 'GET',
signal: controller.signal,
})
if (res.status !== 301) {
return res.url
}
return res.headers.get('Location')
} catch (e: unknown) {
logger.error('Failed to resolve short link', {safeMessage: e})
return null
} finally {
clearTimeout(to)
}
}
+11
View File
@@ -2,6 +2,7 @@ import {AtUri} from '@atproto/api'
import psl from 'psl'
import TLDs from 'tlds'
import {logger} from '#/logger'
import {BSKY_SERVICE} from 'lib/constants'
import {isInvalidHandle} from 'lib/strings/handles'
@@ -285,3 +286,13 @@ export function createBskyAppAbsoluteUrl(path: string): string {
const sanitizedPath = path.replace(BSKY_APP_HOST, '').replace(/^\/+/, '')
return `${BSKY_APP_HOST.replace(/\/$/, '')}/${sanitizedPath}`
}
export function isShortLink(url: string): boolean {
try {
const urlp = new URL(url)
return urlp.host === 'go.bsky.app'
} catch (e) {
logger.error('Failed to parse possible short link', {safeMessage: e})
return false
}
}
-24
View File
@@ -1,24 +0,0 @@
import {logger} from '#/logger'
export function useResolveShortLink() {
return async (shortLink: string) => {
const controller = new AbortController()
const to = setTimeout(() => controller.abort(), 2e3)
try {
const res = await fetch(
shortLink,
{method: 'HEAD', redirect: 'manual'},
{signal: controller.signal},
)
if (res.status !== 301) {
return shortLink
}
return res.headers.get('Location')
} catch (e: unknown) {
logger.error('Failed to resolve short link', {safeMessage: e})
} finally {
clearTimeout(to)
}
}
}
@@ -12,11 +12,13 @@ import {
getPostAsQuote,
} from 'lib/link-meta/bsky'
import {getLinkMeta} from 'lib/link-meta/link-meta'
import {resolveShortLink} from 'lib/link-meta/resolve-short-link'
import {downloadAndResize} from 'lib/media/manip'
import {
isBskyCustomFeedUrl,
isBskyListUrl,
isBskyPostUrl,
isShortLink,
} from 'lib/strings/url-helpers'
import {ImageModel} from 'state/models/media/image'
import {ComposerOpts} from 'state/shell/composer'
@@ -94,6 +96,17 @@ export function useExternalLinkFetch({
setExtLink(undefined)
},
)
} else if (isShortLink(extLink.uri)) {
if (isShortLink(extLink.uri)) {
resolveShortLink(extLink.uri).then(res => {
if (res && res !== extLink.uri) {
setExtLink({
uri: res,
isLoading: true,
})
}
})
}
} else {
getLinkMeta(agent, extLink.uri).then(meta => {
if (aborted) {