'use server' import type { RemoteUploadOptions, UploadResult } from './types' import { createMedia } from '@admin/actions/media' import { saveUpload } from '@admin/actions/storage' import { requireRole, UserRole } from '@admin/auth/middleware' import { DEFAULT_REMOTE_ACCEPT } from '@admin/utils/upload/default-remote-accept' import { getRemoteFilename } from '@admin/utils/upload/get-remote-filename' import { isAcceptedRemoteType } from '@admin/utils/upload/is-accepted-remote-type' import { REMOTE_FETCH_TIMEOUT_MS } from '@admin/utils/upload/remote-fetch-timeout-ms' export async function uploadMediaFromUrl( mediaUrl: string, { prefix = 'media', accept = DEFAULT_REMOTE_ACCEPT, maxSizeInBytes }: RemoteUploadOptions = {} ): Promise { await requireRole([UserRole.ADMIN, UserRole.EDITOR]) try { const url = new URL(mediaUrl) if (!['http:', 'https:'].includes(url.protocol)) { return { success: false, error: 'Only HTTP and HTTPS URLs are allowed' } } const response = await fetch(mediaUrl, { headers: { 'User-Agent': 'Mozilla/5.0 (compatible; BetterStartMediaFetcher/1.0)' }, signal: AbortSignal.timeout(REMOTE_FETCH_TIMEOUT_MS) }) if (!response.ok) { return { success: false, error: "Couldn't reach that URL. Check the link and try again." } } const contentType = (response.headers.get('content-type') || 'application/octet-stream') .split(';')[0] .trim() .toLowerCase() if (!contentType.startsWith('image/') && !contentType.startsWith('video/')) { return { success: false, error: 'That link is not an image or video.' } } const filename = getRemoteFilename(url, contentType) if (!isAcceptedRemoteType(contentType, filename, accept)) { return { success: false, error: 'The remote file type is not allowed for this uploader' } } const contentLength = Number(response.headers.get('content-length') ?? 0) if ( typeof maxSizeInBytes === 'number' && maxSizeInBytes > 0 && Number.isFinite(contentLength) && contentLength > maxSizeInBytes ) { const maxSizeInMb = Math.round(maxSizeInBytes / (1024 * 1024)) return { success: false, error: `Remote file exceeds ${maxSizeInMb}MB limit` } } const arrayBuffer = await response.arrayBuffer() const buffer = Buffer.from(arrayBuffer) if (buffer.length === 0) return { success: false, error: 'Remote file is empty' } if ( typeof maxSizeInBytes === 'number' && maxSizeInBytes > 0 && buffer.length > maxSizeInBytes ) { const maxSizeInMb = Math.round(maxSizeInBytes / (1024 * 1024)) return { success: false, error: `Remote file exceeds ${maxSizeInMb}MB limit` } } const { key, url: uploadedUrl } = await saveUpload({ buffer, filename, contentType, contentLength: buffer.length, prefix }) const mediaResult = await createMedia({ url: uploadedUrl, filename, contentType, size: buffer.length, width: null, height: null, alt: null, tags: null }) if (!mediaResult.success || !mediaResult.media) { return { success: false, error: mediaResult.error ?? 'Failed to create media record' } } return { success: true, files: [ { id: mediaResult.media.id, key, url: uploadedUrl, filename, size: buffer.length, contentType, width: mediaResult.media.width, height: mediaResult.media.height, alt: mediaResult.media.alt, tags: mediaResult.media.tags ?? undefined } ] } } catch (error) { const message = error instanceof Error ? error.message : 'Failed to upload media from URL' return { success: false, error: message } } }