-
Notifications
You must be signed in to change notification settings - Fork 10
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Merge pull request #4197 from serlo/feat/image-upload-rework-staging-…
…only feat(image): add new upload code for testing
- Loading branch information
Showing
6 changed files
with
158 additions
and
14 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,4 @@ | ||
import type { EditorVariant } from '@editor/package/storage-format' | ||
import { createContext } from 'react' | ||
|
||
export const EditorVariantContext = createContext<EditorVariant>('unknown') |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,90 @@ | ||
import { EditorVariantContext } from '@editor/core/contexts/editor-variant-context' | ||
import { type EditorVariant } from '@editor/package/storage-format' | ||
import { type UploadHandler } from '@editor/plugin' | ||
import { useContext } from 'react' | ||
|
||
import { handleError, validateFile } from './validate-file' | ||
|
||
export function useUploadFile(oldFileUploader: UploadHandler<string>) { | ||
const editorVariant = useContext(EditorVariantContext) | ||
return shouldUseNewUpload() | ||
? (file: File) => uploadFile(file, editorVariant) | ||
: oldFileUploader | ||
} | ||
|
||
// while testing | ||
export function shouldUseNewUpload() { | ||
if (typeof window === 'undefined') return false | ||
const host = window.location.hostname | ||
const isDevOrPreviewOrStaging = | ||
(host.startsWith('frontend-git') && host.endsWith('vercel.app')) || | ||
host.endsWith('serlo-staging.dev') || | ||
host === 'localhost' || | ||
process.env.NODE_ENV === 'development' || | ||
host.endsWith('serlo.dev') | ||
|
||
if (isDevOrPreviewOrStaging) { | ||
// eslint-disable-next-line no-console | ||
console.warn('using new upload method and temporary bucket') | ||
} | ||
return isDevOrPreviewOrStaging | ||
} | ||
|
||
export async function uploadFile(file: File, editorVariant: EditorVariant) { | ||
const validated = validateFile(file) | ||
if (!validated) return Promise.reject() | ||
|
||
const data = await getSignedUrlAndSrc(file.type, editorVariant) | ||
if (!data) return Promise.reject('Could not get signed URL') | ||
|
||
const { signedUrl, imgSrc } = data | ||
|
||
const success = await uploadToBucket(file, signedUrl) | ||
if (!success) return Promise.reject('Could not upload file') | ||
return Promise.resolve(imgSrc) | ||
} | ||
|
||
const signedUrlHost = | ||
process.env.NODE_ENV === 'development' | ||
? 'editor.serlo.dev' | ||
: 'editor.serlo.dev' // TODO: Change to production bucket after testing | ||
|
||
async function getSignedUrlAndSrc( | ||
mimeType: string, | ||
editorVariant: EditorVariant | ||
) { | ||
const url = `https://${signedUrlHost}/media/presigned-url?mimeType=${encodeURIComponent(mimeType)}&editorVariant=${encodeURIComponent(editorVariant)}` | ||
|
||
const result = await fetch(url).catch((e) => { | ||
// eslint-disable-next-line no-console | ||
console.error(e) | ||
handleError(errorMessage) | ||
}) | ||
|
||
const data = (await result?.json()) as { signedUrl: string; imgSrc: string } | ||
return data | ||
} | ||
|
||
const errorMessage = 'Error while uploading' | ||
|
||
async function uploadToBucket(file: File, signedUrl: string) { | ||
const response = await fetch(signedUrl, { | ||
method: 'PUT', | ||
body: file, | ||
headers: { | ||
'Content-Type': file.type, | ||
'Access-Control-Allow-Origin': '*', | ||
}, | ||
}).catch((e) => { | ||
// eslint-disable-next-line no-console | ||
console.error(e) | ||
handleError(errorMessage) | ||
return | ||
}) | ||
|
||
if (!response || response.status !== 200) { | ||
handleError(errorMessage) | ||
return | ||
} | ||
return true | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,45 @@ | ||
import { showToastNotice } from '@editor/editor-ui/show-toast-notice' | ||
|
||
export enum FileErrorCode { | ||
TOO_MANY_FILES, | ||
NO_FILE_SELECTED, | ||
BAD_EXTENSION, | ||
FILE_TOO_BIG, | ||
UPLOAD_FAILED, | ||
} | ||
|
||
export interface FileError { | ||
errorCode: FileErrorCode | ||
message: string | ||
} | ||
const maxFileSize = 2 * 1024 * 1024 | ||
const allowedExtensions = ['gif', 'jpg', 'jpeg', 'png', 'svg', 'webp'] | ||
|
||
export function validateFile(file: File) { | ||
// TODO: i18n and make error messages actually helpful | ||
if (!file) { | ||
handleError('No file selected') | ||
return false | ||
} | ||
if (!matchesAllowedExtensions(file.name)) { | ||
handleError('Not an accepted file type') | ||
return false | ||
} | ||
if (file.size > maxFileSize) { | ||
handleError('File is too big') | ||
return false | ||
} | ||
|
||
return true | ||
} | ||
|
||
function matchesAllowedExtensions(fileName: string) { | ||
const extension = fileName.toLowerCase().slice(fileName.lastIndexOf('.') + 1) | ||
return allowedExtensions.includes(extension) | ||
} | ||
|
||
export function handleError(message: string) { | ||
// eslint-disable-next-line no-console | ||
console.error(message) | ||
showToastNotice(message, 'warning') | ||
} |