-
Notifications
You must be signed in to change notification settings - Fork 6
/
image-proxy.ts
79 lines (59 loc) · 2.74 KB
/
image-proxy.ts
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
import { get } from 'svelte/store'
import { getInstance } from '$lib/lemmy.js'
import {
userSettings,
ENABLE_MEDIA_PROXY,
ENABLE_MEDIA_PROXY_LOCAL,
MEDIA_PROXY_BLACKLIST,
MEDIA_PROXY_LEMMY_ONLY
} from '$lib/settings.js'
// Accepts an image URL as input and determines whether to convert it into a proxied image URL or keep the original
export function imageProxyURL(url?:string, size?:number, format?:string): string|undefined {
if (!url) return
// Return original URL if media proxying is globally disabled
if (!ENABLE_MEDIA_PROXY) return url;
// Return original URL if user preference for media proxing is disabled
if (!get(userSettings)?.proxyMedia.enabled) return url;
// Return original URL if image url matches an entry in the blacklist
if (MEDIA_PROXY_BLACKLIST.length > 0) {
for (let i:number=0; i< MEDIA_PROXY_BLACKLIST.length; i++) {
if ( url.includes(MEDIA_PROXY_BLACKLIST[i]) ) return url;
}
}
// Return original URL if image is not on another Lemmy instance (identified by /pictrs/image in the url) and admin configured to only proxy Lemmy images
if (MEDIA_PROXY_LEMMY_ONLY && !url.includes('/pictrs/image')) return url;
// Return original URL if local media/home instance image proxying is disabled
if ( !ENABLE_MEDIA_PROXY_LOCAL && url.includes(getInstance())) return url;
// Don't proxy local blobs
if (url.startsWith('blob:')) return url;
// Don't proxy inline data images
if (url.startsWith('data:')) return url;
// Don't proxy images that are already going through the local proxy
if (url.includes(`${new URL(window.location.href).origin}/image_proxy/`)) return url;
// Build the image proxy URL to return
try {
let image = new URL(url);
let host = image.host;
let params = image.searchParams;
let path = image.pathname;
if (get(userSettings)?.proxyMedia.fallback) {
params.append('fallback', 'true');
}
// Only add the thumbnail and format parameters to pictrs URLs (to avoid caching multiple version of a GIF from Giphy, etc where those aren't respected)
if (url.includes('/pictrs/image')) {
if (size) {
params.set('thumbnail', size.toString());
}
if (format) {
params.set('format', format)
}
}
let origin = new URL(window.location.href).origin;
let imagePath = `${host}${path}`;
return `${origin}/image_proxy/${imagePath}?${params}`
}
// If building the URL fails, fallback to returning the original
catch {
return url;
}
}