Support Reddit gallery posts

This commit is contained in:
jjbrunton committed 2026-08-09 09:42:15 +01:00
1 parent 5c9839926d
commit 7db60e8839
2 files changed
+118

No files matched your search

+37
View File
@@ -63,6 +63,20 @@ export interface RedditPost {
resolutions: Array<{ url: string; width: number; height: number }>;
}>;
};
is_gallery?: boolean;
gallery_data?: {
items: Array<{ media_id: string; id?: number }>;
};
media_metadata?: Record<string, {
status?: string;
m?: string;
s?: {
u?: string;
gif?: string;
x?: number;
y?: number;
};
}>;
created_utc: number;
over_18: boolean;
spoiler: boolean;
@@ -252,6 +266,8 @@ export class RedditApiClient {
}
private hasImage(post: RedditPost): boolean {
if (this.getGalleryImageUrl(post)) return true;
// Check post_hint
if (post.post_hint === 'image') return true;
@@ -272,6 +288,9 @@ export class RedditApiClient {
}
getImageUrl(post: RedditPost): string | null {
const galleryImageUrl = this.getGalleryImageUrl(post);
if (galleryImageUrl) return galleryImageUrl;
// Prefer high-quality preview images (already processed by Reddit)
if (post.preview?.images?.[0]?.source?.url) {
// Reddit encodes URLs in preview, need to decode HTML entities
@@ -312,6 +331,24 @@ export class RedditApiClient {
return null;
}
/** Return the first valid gallery image in Reddit's declared display order. */
private getGalleryImageUrl(post: RedditPost): string | null {
if (!post.is_gallery || !post.media_metadata) return null;
const orderedMediaIds = post.gallery_data?.items.map((item) => item.media_id)
?? Object.keys(post.media_metadata);
for (const mediaId of orderedMediaIds) {
const media = post.media_metadata[mediaId];
if (!media || (media.status && media.status !== 'valid')) continue;
if (media.m && !media.m.startsWith('image/')) continue;
const sourceUrl = media.s?.u ?? media.s?.gif;
if (sourceUrl) return this.decodeRedditUrl(sourceUrl);
}
return null;
}
private decodeRedditUrl(url: string): string {
return url.replace(/&amp;/g, '&');
}