1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
|
import {useState, useEffect} from 'react'
import {useStores} from 'state/index'
import * as apilib from 'lib/api/index'
import {getLinkMeta} from 'lib/link-meta/link-meta'
import {getPostAsQuote, getFeedAsEmbed} from 'lib/link-meta/bsky'
import {downloadAndResize} from 'lib/media/manip'
import {isBskyPostUrl, isBskyCustomFeedUrl} from 'lib/strings/url-helpers'
import {ComposerOpts} from 'state/models/ui/shell'
import {POST_IMG_MAX} from 'lib/constants'
export function useExternalLinkFetch({
setQuote,
}: {
setQuote: (opts: ComposerOpts['quote']) => void
}) {
const store = useStores()
const [extLink, setExtLink] = useState<apilib.ExternalEmbedDraft | undefined>(
undefined,
)
useEffect(() => {
let aborted = false
const cleanup = () => {
aborted = true
}
if (!extLink) {
return cleanup
}
if (!extLink.meta) {
if (isBskyPostUrl(extLink.uri)) {
getPostAsQuote(store, extLink.uri).then(
newQuote => {
if (aborted) {
return
}
setQuote(newQuote)
setExtLink(undefined)
},
err => {
store.log.error('Failed to fetch post for quote embedding', {err})
setExtLink(undefined)
},
)
} else if (isBskyCustomFeedUrl(extLink.uri)) {
getFeedAsEmbed(store, extLink.uri).then(
({embed, meta}) => {
if (aborted) {
return
}
setExtLink({
uri: extLink.uri,
isLoading: false,
meta,
embed,
})
},
err => {
store.log.error('Failed to fetch feed for embedding', {err})
setExtLink(undefined)
},
)
} else {
getLinkMeta(store, extLink.uri).then(meta => {
if (aborted) {
return
}
setExtLink({
uri: extLink.uri,
isLoading: !!meta.image,
meta,
})
})
}
return cleanup
}
if (extLink.isLoading && extLink.meta?.image && !extLink.localThumb) {
downloadAndResize({
uri: extLink.meta.image,
width: POST_IMG_MAX.width,
height: POST_IMG_MAX.height,
mode: 'contain',
maxSize: POST_IMG_MAX.size,
timeout: 15e3,
})
.catch(() => undefined)
.then(localThumb => {
if (aborted) {
return
}
setExtLink({
...extLink,
isLoading: false, // done
localThumb,
})
})
return cleanup
}
if (extLink.isLoading) {
setExtLink({
...extLink,
isLoading: false, // done
})
}
return cleanup
}, [store, extLink, setQuote])
return {extLink, setExtLink}
}
|