Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: Mux new_asset_settings Config Pane, Uploader FC #345

Merged
merged 1 commit into from
Feb 27, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
26,349 changes: 26,349 additions & 0 deletions package-lock.json

Large diffs are not rendered by default.

2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -94,7 +94,7 @@
"eslint": "^8.56.0",
"eslint-config-prettier": "^9.1.0",
"eslint-config-react-app": "^7.0.1",
"eslint-config-sanity": "^7.0.1",
"eslint-config-sanity": "^7.0.2",
"eslint-plugin-import": "^2.29.1",
"eslint-plugin-prettier": "^5.1.3",
"eslint-plugin-react-hooks": "^4.6.0",
Expand Down
1 change: 1 addition & 0 deletions src/_exports/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ export const defaultConfig: PluginConfig = {
mp4_support: 'none',
encoding_tier: 'smart',
max_resolution_tier: '1080p',
normalize_audio: false,
defaultSigned: false,
tool: DEFAULT_TOOL_CONFIG,
}
Expand Down
60 changes: 20 additions & 40 deletions src/actions/upload.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ import {catchError, mergeMap, mergeMapTo, switchMap} from 'rxjs/operators'
import type {SanityClient} from 'sanity'

import {createUpChunkObservable} from '../clients/upChunkObservable'
import type {MuxAsset, PluginConfig, UploadConfig} from '../util/types'
import type {MuxAsset, MuxNewAssetSettings, PluginConfig, UploadConfig} from '../util/types'
import {getAsset} from './assets'
import {testSecretsObservable} from './secrets'

Expand All @@ -16,42 +16,32 @@ export function cancelUpload(client: SanityClient, uuid: string) {
})
}

function generateMuxBody(uploadConfig: UploadConfig) {
return {
mp4_support: uploadConfig.mp4_support,
encoding_tier: uploadConfig.encoding_tier,
max_resolution_tier: uploadConfig.max_resolution_tier,
playback_policy: [uploadConfig.signed ? 'signed' : 'public'],
// @TODO: send tracks to backend
}
}

export function uploadUrl({
client,
url,
uploadConfig,
settings,
client,
}: {
uploadConfig: UploadConfig
client: SanityClient
url: string
settings: MuxNewAssetSettings
client: SanityClient
}) {
return testUrl(url).pipe(
switchMap((validUrl) => {
return concat(
of({type: 'url', url: validUrl}),
of({type: 'url' as const, url: validUrl}),
testSecretsObservable(client).pipe(
switchMap((json) => {
if (!json || !json.status) {
return throwError(new Error('Invalid credentials'))
}
const uuid = generateUuid()
const muxBody = {
...generateMuxBody(uploadConfig),
input: validUrl,
}
const muxBody = settings
if (!muxBody.input) muxBody.input = [{type: 'video'}]
muxBody.input[0].url = validUrl

const query = {
muxBody: JSON.stringify(muxBody),
filename: uploadConfig.filename,
filename: validUrl.split('/').slice(-1)[0],
}

const dataset = client.config().dataset
Expand All @@ -75,7 +65,7 @@ export function uploadUrl({
if (!asset) {
return throwError(new Error('No asset document returned'))
}
return of({type: 'success', id: uuid, asset})
return of({type: 'success' as const, id: uuid, asset})
})
)
})
Expand All @@ -86,45 +76,35 @@ export function uploadUrl({
}

export function uploadFile({
uploadConfig,
settings,
client,
file,
}: {
uploadConfig: UploadConfig
settings: MuxNewAssetSettings
client: SanityClient
file: File
}) {
return testFile(file).pipe(
switchMap((fileOptions) => {
return concat(
of({type: 'file', file: fileOptions}),
of({type: 'file' as const, file: fileOptions}),
testSecretsObservable(client).pipe(
switchMap((json) => {
if (!json || !json.status) {
return throwError(() => new Error('Invalid credentials'))
}
const uuid = generateUuid()
const body = {
...generateMuxBody(uploadConfig),

filename: uploadConfig.filename,
}
const body = settings

return concat(
of({type: 'uuid', uuid}),
of({type: 'uuid' as const, uuid}),
defer(() =>
client.observable.request<{
sanityAssetId: string
upload: {
cors_origin: string
id: string
new_asset_settings: Pick<
Required<PluginConfig>,
'mp4_support' | 'encoding_tier' | 'max_resolution_tier'
> & {
passthrough: string
playback_policies: ['public' | 'signed']
}
new_asset_settings: MuxNewAssetSettings
status: 'waiting'
timeout: number
url: string
Expand All @@ -145,7 +125,7 @@ export function uploadFile({
// eslint-disable-next-line no-warning-comments
// @TODO type the observable events
// eslint-disable-next-line max-nested-callbacks
mergeMap((event: any) => {
mergeMap((event) => {
if (event.type !== 'success') {
return of(event)
}
Expand Down Expand Up @@ -276,7 +256,7 @@ export function testUrl(url: string): Observable<string> {

function optionsFromFile(opts: {preserveFilename?: boolean}, file: File) {
if (typeof window === 'undefined' || !(file instanceof window.File)) {
return opts
return undefined
}
return {
name: opts.preserveFilename === false ? undefined : file.name,
Expand Down
6 changes: 5 additions & 1 deletion src/clients/upChunkObservable.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,11 @@ import {UpChunk} from '@mux/upchunk'
import {Observable} from 'rxjs'

export function createUpChunkObservable(uuid: string, uploadUrl: string, source: File) {
return new Observable((subscriber) => {
return new Observable<
| {type: 'pause' | 'resume'; id: string}
| {type: 'success'; id: string}
| {type: 'progress'; percent: number}
>((subscriber) => {
const upchunk = UpChunk.createUpload({
endpoint: uploadUrl,
file: source,
Expand Down
92 changes: 92 additions & 0 deletions src/components/FileInputArea.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,92 @@
import {PropsWithChildren, useRef, useState} from 'react'
import {Box, Button, Card, CardTone, Flex, Inline, Text} from '@sanity/ui'
import {FileInputButton} from './FileInputButton'
import {UploadIcon} from '@sanity/icons'
import {extractDroppedFiles} from '../util/extractFiles'

interface FileInputAreaProps extends PropsWithChildren {
accept?: string
acceptMIMETypes?: string[]
label: React.ReactNode
onSelect: (files: FileList | File[]) => void
}

export default function FileInputArea({
label,
accept,
acceptMIMETypes,
onSelect,
}: FileInputAreaProps) {
const dragEnteredEls = useRef<EventTarget[]>([])
const [dragState, setDragState] = useState<'valid' | 'invalid' | null>(null)

// Stages and validates an upload from dragging+dropping files or folders
const handleDrop: React.DragEventHandler<HTMLDivElement> = (event) => {
setDragState(null)
event.preventDefault()
event.stopPropagation()
extractDroppedFiles(event.nativeEvent.dataTransfer!).then(onSelect)
}

/* ------------------------------- Drag State ------------------------------- */

const handleDragOver: React.DragEventHandler<HTMLDivElement> = (event) => {
event.preventDefault()
event.stopPropagation()
}

const handleDragEnter: React.DragEventHandler<HTMLDivElement> = (event) => {
event.stopPropagation()
dragEnteredEls.current.push(event.target)
const type = event.dataTransfer.items?.[0]?.type
setDragState(
!acceptMIMETypes || acceptMIMETypes.some((mimeType) => type?.match(mimeType))
? 'valid'
: 'invalid'
)
}

const handleDragLeave: React.DragEventHandler<HTMLDivElement> = (event) => {
event.stopPropagation()
const idx = dragEnteredEls.current.indexOf(event.target)
if (idx > -1) {
dragEnteredEls.current.splice(idx, 1)
}
if (dragEnteredEls.current.length === 0) {
setDragState(null)
}
}

let tone: CardTone = 'inherit'
if (dragState) tone = dragState === 'valid' ? 'positive' : 'critical'
return (
<Card border sizing="border" tone={tone} style={{borderStyle: 'dashed'}} padding={3}>
<Flex
align="center"
justify="space-between"
gap={4}
direction={['column', 'column', 'row']}
paddingY={[2, 2, 0]}
sizing="border"
onDrop={handleDrop}
onDragOver={handleDragOver}
onDragLeave={handleDragLeave}
onDragEnter={handleDragEnter}
>
<Flex align="center" justify="center" gap={2} flex={1}>
{label}
</Flex>
<Inline space={2}>
<FileInputButton
mode="ghost"
tone="default"
icon={UploadIcon}
text="Upload"
onSelect={onSelect}
accept={accept}
/>
</Inline>
</Flex>
</Card>
)
}
5 changes: 3 additions & 2 deletions src/components/FileInputButton.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -17,8 +17,9 @@ const Label = styled.label`

export interface FileInputButtonProps extends ButtonProps {
onSelect: (files: FileList) => void
accept?: string
}
export const FileInputButton = ({onSelect, ...props}: FileInputButtonProps) => {
export const FileInputButton = ({onSelect, accept, ...props}: FileInputButtonProps) => {
const inputId = `FileSelect${useId()}`
const inputRef = useRef<HTMLInputElement>(null)
const handleSelect = useCallback<React.ChangeEventHandler<HTMLInputElement>>(
Expand All @@ -33,7 +34,7 @@ export const FileInputButton = ({onSelect, ...props}: FileInputButtonProps) => {
return (
<Label htmlFor={inputId}>
<HiddenInput
accept="video/*"
accept={accept || 'video/*'}
ref={inputRef}
tabIndex={0}
type="file"
Expand Down
4 changes: 2 additions & 2 deletions src/components/Input.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -6,12 +6,12 @@ import {useClient} from '../hooks/useClient'
import {useDialogState} from '../hooks/useDialogState'
import {useMuxPolling} from '../hooks/useMuxPolling'
import {useSecretsDocumentValues} from '../hooks/useSecretsDocumentValues'
import type {PluginConfig, MuxInputProps} from '../util/types'
import Uploader from './__legacy__Uploader'
import type {MuxInputProps, PluginConfig} from '../util/types'
import ConfigureApi from './ConfigureApi'
import ErrorBoundaryCard from './ErrorBoundaryCard'
import {InputFallback} from './Input.styled'
import Onboard from './Onboard'
import Uploader from './Uploader'

export interface InputProps extends MuxInputProps {
config: PluginConfig
Expand Down
Loading