diff --git a/web/src/api/channels.test.ts b/web/src/api/channels.test.ts index 81b73e8d6..aa0cd2512 100644 --- a/web/src/api/channels.test.ts +++ b/web/src/api/channels.test.ts @@ -1,5 +1,13 @@ import { beforeEach, describe, expect, it, vi } from 'vitest'; -import { getChannelById, updateChannel, type UpdateChannelRequest } from './channels'; +import { + createChannel, + getChannelById, + getChannelStreamSelectors, + getMusicVideoCreditsTemplates, + updateChannel, + type CreateChannelRequest, + type UpdateChannelRequest +} from './channels'; const sampleChannel = { id: 5, @@ -90,3 +98,69 @@ describe('updateChannel', () => { expect(JSON.parse(init?.body as string)).toMatchObject({ name: 'Renamed', number: '5' }); }); }); + +describe('createChannel', () => { + beforeEach(() => { + window.localStorage.clear(); + vi.restoreAllMocks(); + }); + + it('POSTs the request body to /api/channels and returns the created view model', async () => { + const fetchSpy = vi.spyOn(window, 'fetch').mockResolvedValue( + new Response(JSON.stringify(sampleChannel), { + headers: { 'Content-Type': 'application/json' }, + status: 200 + }) + ); + + const body = { ...sampleChannel, id: undefined } as unknown as CreateChannelRequest; + + await expect(createChannel(body)).resolves.toMatchObject({ id: 5 }); + + const [url, init] = fetchSpy.mock.calls[0]; + expect(url).toBe('/api/channels'); + expect((init?.method ?? '').toUpperCase()).toBe('POST'); + }); +}); + +describe('getMusicVideoCreditsTemplates', () => { + beforeEach(() => { + window.localStorage.clear(); + vi.restoreAllMocks(); + }); + + it('GETs /api/channels/music-video-credits-templates', async () => { + const fetchSpy = vi.spyOn(window, 'fetch').mockResolvedValue( + new Response(JSON.stringify(['default']), { + headers: { 'Content-Type': 'application/json' }, + status: 200 + }) + ); + + await expect(getMusicVideoCreditsTemplates()).resolves.toEqual(['default']); + + const [url] = fetchSpy.mock.calls[0]; + expect(url).toBe('/api/channels/music-video-credits-templates'); + }); +}); + +describe('getChannelStreamSelectors', () => { + beforeEach(() => { + window.localStorage.clear(); + vi.restoreAllMocks(); + }); + + it('GETs /api/channels/stream-selectors', async () => { + const fetchSpy = vi.spyOn(window, 'fetch').mockResolvedValue( + new Response(JSON.stringify(['selector.py']), { + headers: { 'Content-Type': 'application/json' }, + status: 200 + }) + ); + + await expect(getChannelStreamSelectors()).resolves.toEqual(['selector.py']); + + const [url] = fetchSpy.mock.calls[0]; + expect(url).toBe('/api/channels/stream-selectors'); + }); +}); diff --git a/web/src/api/channels.ts b/web/src/api/channels.ts index 00da8a20f..6ecb4cfb4 100644 --- a/web/src/api/channels.ts +++ b/web/src/api/channels.ts @@ -11,6 +11,7 @@ export type BulkMoveChannelsToGroupRequest = components['schemas']['BulkMoveChan export type BulkDeleteChannelsRequest = components['schemas']['BulkDeleteChannelsRequest']; export type CreateChannelFromLineupRequest = components['schemas']['CreateChannelFromLineupRequest']; export type CreateChannelFromLineupResponseModel = components['schemas']['CreateChannelFromLineupResponseModel']; +export type CreateChannelRequest = components['schemas']['CreateChannelRequest']; export interface ChannelsScreenData { channels: ChannelSummary[]; @@ -46,6 +47,21 @@ export function updateChannel(channelId: number, body: UpdateChannelRequest): Pr }); } +export function createChannel(body: CreateChannelRequest): Promise { + return request('/api/channels', { + body, + method: 'POST' + }); +} + +export function getMusicVideoCreditsTemplates(): Promise { + return request('/api/channels/music-video-credits-templates'); +} + +export function getChannelStreamSelectors(): Promise { + return request('/api/channels/stream-selectors'); +} + export async function getChannelsScreenData(): Promise { const [channels, channelStates] = await Promise.all([ getChannels(), diff --git a/web/src/api/index.ts b/web/src/api/index.ts index 44f27363b..7462359dc 100644 --- a/web/src/api/index.ts +++ b/web/src/api/index.ts @@ -12,6 +12,7 @@ export * from './ffmpegProfiles'; export * from './fillerPresets'; export * from './guide'; export * from './imageFolders'; +export * from './languages'; export * from './libraries'; export * from './libraryBrowse'; export * from './logs'; diff --git a/web/src/api/languages.test.ts b/web/src/api/languages.test.ts new file mode 100644 index 000000000..4e97dc5d3 --- /dev/null +++ b/web/src/api/languages.test.ts @@ -0,0 +1,33 @@ +import { beforeEach, describe, expect, it, vi } from 'vitest'; +import { getLanguages } from './languages'; + +function jsonResponse(body: unknown, status = 200): Response { + return new Response(JSON.stringify(body), { headers: { 'Content-Type': 'application/json' }, status }); +} + +describe('getLanguages', () => { + beforeEach(() => { + window.localStorage.clear(); + vi.restoreAllMocks(); + }); + + it('GETs /api/languages and returns the list', async () => { + const fetchSpy = vi.spyOn(window, 'fetch').mockResolvedValue( + jsonResponse([{ code: 'eng', englishName: 'English' }]) + ); + + await expect(getLanguages()).resolves.toEqual([{ code: 'eng', englishName: 'English' }]); + + const [url, init] = fetchSpy.mock.calls[0]; + expect(url).toBe('/api/languages'); + expect((init?.method ?? 'GET').toUpperCase()).toBe('GET'); + }); + + it('rejects with the ApiError status on failure', async () => { + vi.spyOn(window, 'fetch').mockResolvedValue( + jsonResponse({ status: 500, title: 'Internal Server Error' }, 500) + ); + + await expect(getLanguages()).rejects.toMatchObject({ status: 500 }); + }); +}); diff --git a/web/src/api/languages.ts b/web/src/api/languages.ts new file mode 100644 index 000000000..7ea8a93d8 --- /dev/null +++ b/web/src/api/languages.ts @@ -0,0 +1,20 @@ +import { ApiError, request } from './client'; +import type { components } from './generated/v1'; + +export type LanguageCode = components['schemas']['LanguageCodeResponseModel']; + +export function getLanguages(): Promise { + return request('/api/languages'); +} + +export function messageFromLanguagesError(error: unknown, fallback = 'Unable to load languages'): string { + if (error instanceof ApiError) { + return error.detail ?? error.message; + } + + if (error instanceof Error) { + return error.message; + } + + return fallback; +} diff --git a/web/src/screens/ChannelEditScreen.test.tsx b/web/src/screens/ChannelEditScreen.test.tsx index e12e0f46c..df5e86c1c 100644 --- a/web/src/screens/ChannelEditScreen.test.tsx +++ b/web/src/screens/ChannelEditScreen.test.tsx @@ -50,23 +50,27 @@ function json(body: unknown, status = 200): Response { } interface FetchOptions { + channelOverrides?: Record; channelStatus?: number; onPut?: (body: unknown) => void; + putResponseOverrides?: Record; } -function mockApi({ channelStatus = 200, onPut }: FetchOptions = {}) { +function mockApi({ channelOverrides = {}, channelStatus = 200, onPut, putResponseOverrides = {} }: FetchOptions = {}) { + const loadedChannel = { ...channel, ...channelOverrides }; + return vi.spyOn(window, 'fetch').mockImplementation((input, init) => { const url = typeof input === 'string' ? input : input instanceof URL ? input.toString() : (input as Request).url; const method = (init?.method ?? 'GET').toUpperCase(); if (url === '/api/channels/5' && method === 'PUT') { onPut?.(JSON.parse(init?.body as string)); - return Promise.resolve(json({ ...channel, name: 'Renamed' })); + return Promise.resolve(json({ ...loadedChannel, name: 'Renamed', ...putResponseOverrides })); } if (url === '/api/channels/5') { return channelStatus === 200 - ? Promise.resolve(json(channel)) + ? Promise.resolve(json(loadedChannel)) : Promise.resolve(json({ status: channelStatus, title: 'Not Found' }, channelStatus)); } @@ -86,6 +90,18 @@ function mockApi({ channelStatus = 200, onPut }: FetchOptions = {}) { return Promise.resolve(json([{ id: 5, number: '5', name: 'Cartoons', group: 'ChicoryTV' }])); } + if (url === '/api/languages') { + return Promise.resolve(json([{ code: 'eng', englishName: 'English' }])); + } + + if (url === '/api/channels/music-video-credits-templates') { + return Promise.resolve(json(['default'])); + } + + if (url === '/api/channels/stream-selectors') { + return Promise.resolve(json(['selector.py'])); + } + return Promise.resolve(json({ status: 404, title: 'Not Found' }, 404)); }); } @@ -158,4 +174,165 @@ describe('ChannelEditScreen', () => { expect(await screen.findByText('Channel not found.')).toBeInTheDocument(); expect(screen.getByRole('button', { name: 'Back to channels' })).toBeInTheDocument(); }); + + describe('external logo URL (Blazor ChannelEditor parity)', () => { + it('hydrates the URL field from an external-URL logo and treats the uploaded logo as empty', async () => { + mockApi({ + channelOverrides: { logo: { path: 'https://example.com/old-logo.png', contentType: '', isExternalUrl: true } } + }); + render(); + + await screen.findByDisplayValue('Cartoons'); + fireEvent.click(screen.getByRole('button', { name: /^Branding/ })); + + expect(await screen.findByDisplayValue('https://example.com/old-logo.png')).toBeInTheDocument(); + // The preview shows the external URL, not an uploaded-logo path. + expect(screen.getByRole('img', { name: 'Cartoons' })).toHaveAttribute('src', 'https://example.com/old-logo.png'); + }); + + it('sends an external URL as the logo, winning over any previously uploaded logo, on save', async () => { + const puts: unknown[] = []; + mockApi({ + channelOverrides: { logo: { path: 'iptv/logos/uploaded.png', contentType: 'image/png' } }, + onPut: (body) => puts.push(body) + }); + render(); + + await screen.findByDisplayValue('Cartoons'); + fireEvent.click(screen.getByRole('button', { name: /^Branding/ })); + + const urlInput = screen.getByPlaceholderText('https://example.com/logo.png'); + fireEvent.change(urlInput, { target: { value: 'https://example.com/new-logo.png' } }); + + const saveButton = await screen.findByRole('button', { name: 'Save changes' }); + fireEvent.click(saveButton); + + await waitFor(() => expect(puts).toHaveLength(1)); + + expect(puts[0]).toMatchObject({ + logo: { path: 'https://example.com/new-logo.png', contentType: '' } + }); + }); + + it('shows an inline error and blocks save for a non-http(s) URL', async () => { + mockApi(); + render(); + + await screen.findByDisplayValue('Cartoons'); + fireEvent.click(screen.getByRole('button', { name: /^Branding/ })); + + const urlInput = screen.getByPlaceholderText('https://example.com/logo.png'); + fireEvent.change(urlInput, { target: { value: 'not-a-url' } }); + + expect(await screen.findByText('Enter a valid http(s) URL')).toBeInTheDocument(); + expect(screen.getByRole('button', { name: 'Save changes' })).toBeDisabled(); + }); + + it('clears the external URL field when a file is uploaded', async () => { + mockApi(); + vi.spyOn(window, 'fetch').mockImplementation((input, init) => { + const url = typeof input === 'string' ? input : input instanceof URL ? input.toString() : (input as Request).url; + const method = (init?.method ?? 'GET').toUpperCase(); + + if (url === '/api/artwork/uploads' && method === 'POST') { + return Promise.resolve(json({ path: 'iptv/logos/new.png', contentType: 'image/png' })); + } + + if (url === '/api/channels/5') { + return Promise.resolve(json(channel)); + } + + if (url === '/api/ffmpeg/profiles') { + return Promise.resolve(json([{ id: 1, name: 'Default profile' }])); + } + + if (url === '/api/watermarks') { + return Promise.resolve(json([{ id: 2, name: 'Corner bug' }])); + } + + if (url === '/api/filler-presets') { + return Promise.resolve(json([{ id: 3, name: 'Bumpers' }])); + } + + if (url === '/api/channels') { + return Promise.resolve(json([{ id: 5, number: '5', name: 'Cartoons', group: 'ChicoryTV' }])); + } + + if (url === '/api/languages') { + return Promise.resolve(json([{ code: 'eng', englishName: 'English' }])); + } + + if (url === '/api/channels/music-video-credits-templates') { + return Promise.resolve(json(['default'])); + } + + if (url === '/api/channels/stream-selectors') { + return Promise.resolve(json(['selector.py'])); + } + + return Promise.resolve(json({ status: 404, title: 'Not Found' }, 404)); + }); + + render(); + + await screen.findByDisplayValue('Cartoons'); + fireEvent.click(screen.getByRole('button', { name: /^Branding/ })); + + const urlInput = screen.getByPlaceholderText('https://example.com/logo.png'); + fireEvent.change(urlInput, { target: { value: 'https://example.com/new-logo.png' } }); + expect(urlInput).toHaveValue('https://example.com/new-logo.png'); + + const file = new File(['x'], 'logo.png', { type: 'image/png' }); + const fileInput = document.querySelector('input[type="file"]') as HTMLInputElement; + fireEvent.change(fileInput, { target: { files: [file] } }); + + await waitFor(() => expect(urlInput).toHaveValue('')); + }); + }); + + describe('picker fields (languages, credits template, stream selector)', () => { + it('keeps a preferred audio language selectable even when missing from the language list', async () => { + mockApi({ channelOverrides: { preferredAudioLanguageCode: 'spa' } }); + render(); + + await screen.findByDisplayValue('Cartoons'); + fireEvent.click(screen.getByRole('button', { name: /^Stream selection/ })); + + const select = await screen.findByDisplayValue('spa'); + expect(select).toBeInTheDocument(); + expect(select.tagName).toBe('SELECT'); + }); + + it('populates the preferred audio language select from GET /api/languages', async () => { + mockApi(); + render(); + + await screen.findByDisplayValue('Cartoons'); + fireEvent.click(screen.getByRole('button', { name: /^Stream selection/ })); + + // Both the preferred-audio and preferred-subtitle language selects populate from the + // same GET /api/languages list. + expect((await screen.findAllByRole('option', { name: 'English' })).length).toBe(2); + }); + + it('keeps a music video credits template selectable even when missing from the template list', async () => { + mockApi({ channelOverrides: { musicVideoCreditsMode: 'GenerateSubtitles', musicVideoCreditsTemplate: 'legacy-template' } }); + render(); + + await screen.findByDisplayValue('Cartoons'); + fireEvent.click(screen.getByRole('button', { name: /^Music video/ })); + + expect(await screen.findByDisplayValue('legacy-template')).toBeInTheDocument(); + }); + + it('keeps a custom stream selector selectable even when missing from the selector list', async () => { + mockApi({ channelOverrides: { streamSelectorMode: 'Custom', streamSelector: 'legacy-selector.py' } }); + render(); + + await screen.findByDisplayValue('Cartoons'); + fireEvent.click(screen.getByRole('button', { name: /^Stream selection/ })); + + expect(await screen.findByDisplayValue('legacy-selector.py')).toBeInTheDocument(); + }); + }); }); diff --git a/web/src/screens/ChannelEditScreen.tsx b/web/src/screens/ChannelEditScreen.tsx index 3d1904cb3..928f1d8bd 100644 --- a/web/src/screens/ChannelEditScreen.tsx +++ b/web/src/screens/ChannelEditScreen.tsx @@ -17,8 +17,11 @@ import { ApiError, getChannelById, getChannels, + getChannelStreamSelectors, getFFmpegProfiles, getFillerPresets, + getLanguages, + getMusicVideoCreditsTemplates, getWatermarks, messageFromError, updateChannel, @@ -27,6 +30,7 @@ import { type ChannelSummary, type FFmpegProfile, type FillerPreset, + type LanguageCode, type UpdateChannelRequest, type Watermark } from '../api'; @@ -111,6 +115,12 @@ function channelIdFromPathname(pathname: string): number | null { return Number.isInteger(id) && id > 0 ? id : null; } +// Blazor parity (ChannelEditor.razor + ChannelEditViewModel.ToUpdate): an external logo URL is +// tracked as separate form state from the uploaded-logo ArtworkContentTypeModel, and wins over it +// on submit. When hydrating a channel whose logo IS an external URL, the uploaded-logo state is +// treated as empty so the two fields never disagree. +const EMPTY_LOGO: NonNullable = { path: '', contentType: '' }; + // The PUT body is the GET response minus the read-only id / playoutCount / webEncodedName // fields, so hydration is a straight field copy. function draftFromChannel(channel: Channel): UpdateChannelRequest { @@ -121,7 +131,7 @@ function draftFromChannel(channel: Channel): UpdateChannelRequest { categories: channel.categories, ffmpegProfileId: channel.ffmpegProfileId, slugSeconds: channel.slugSeconds, - logo: channel.logo, + logo: channel.logo?.isExternalUrl ? EMPTY_LOGO : channel.logo, streamSelectorMode: channel.streamSelectorMode, streamSelector: channel.streamSelector, preferredAudioLanguageCode: channel.preferredAudioLanguageCode, @@ -149,6 +159,64 @@ function numberOrEmpty(value: null | number | undefined): string { return value == null ? '' : String(value); } +function externalLogoUrlFromChannel(channel: Channel): string { + return channel.logo?.isExternalUrl ? (channel.logo.path ?? '') : ''; +} + +// Blazor parity: the URL field only needs to look like http(s) when non-blank; blank means +// "no external URL" and is always valid. +function isValidExternalUrl(value: string): boolean { + const trimmed = value.trim(); + + if (!trimmed) { + return true; + } + + try { + const url = new URL(trimmed); + return url.protocol === 'http:' || url.protocol === 'https:'; + } catch { + return false; + } +} + +interface StringOption { + label: string; + value: string; +} + +// Builds a "(none)" + list Select's options, keeping the channel's currently-stored value +// selectable even if it's absent from the reference list (e.g. a language the media library +// doesn't use, or a template/selector file that's been removed from disk since save) so loading +// an existing channel never silently changes the value. +function optionsKeepingCurrent( + entries: StringOption[], + current: null | string | undefined, + noneLabel = '(none)' +): StringOption[] { + const options: StringOption[] = [{ label: noneLabel, value: '' }, ...entries]; + + if (current && !options.some((option) => option.value === current)) { + options.push({ label: current, value: current }); + } + + return options; +} + +function languageOptions(languages: LanguageCode[], current: null | string | undefined): StringOption[] { + return optionsKeepingCurrent( + languages.map((language) => ({ label: language.englishName ?? language.code ?? '', value: language.code ?? '' })), + current + ); +} + +function stringListOptions(values: string[], current: null | string | undefined): StringOption[] { + return optionsKeepingCurrent( + values.map((value) => ({ label: value, value })), + current + ); +} + function sortByChannelNumber(channels: ChannelSummary[]): ChannelSummary[] { return [...channels].sort((left, right) => { const leftNumber = Number.parseFloat(left.number); @@ -207,6 +275,9 @@ interface ReferenceData { fillerPresets: FillerPreset[]; watermarks: Watermark[]; ffmpegProfiles: FFmpegProfile[]; + languages: LanguageCode[]; + musicVideoCreditsTemplates: string[]; + streamSelectors: string[]; } /* ---------- panes ---------- */ @@ -431,9 +502,11 @@ function StreamingPane({ } function SelectionPane({ + data, draft, set }: { + data: ReferenceData; draft: UpdateChannelRequest; set: (patch: Partial) => void; }) { @@ -458,13 +531,12 @@ function SelectionPane({ {isDefault ? ( <> - - + + set({ streamSelector: event.target.value || null })} + options={stringListOptions(data.streamSelectors, draft.streamSelector)} size="sm" - style={{ fontFamily: 'var(--font-mono)' }} value={draft.streamSelector ?? ''} /> @@ -518,9 +589,11 @@ function SelectionPane({ } function MusicPane({ + data, draft, set }: { + data: ReferenceData; draft: UpdateChannelRequest; set: (patch: Partial) => void; }) { @@ -544,12 +617,12 @@ function MusicPane({ /> - set({ musicVideoCreditsTemplate: event.target.value || null })} + options={stringListOptions(data.musicVideoCreditsTemplates, draft.musicVideoCreditsTemplate)} size="sm" - style={{ fontFamily: 'var(--font-mono)' }} value={draft.musicVideoCreditsTemplate ?? ''} /> @@ -573,24 +646,31 @@ function MusicPane({ function BrandingPane({ data, draft, + externalLogoUrl, logoPreview, + onChangeExternalLogoUrl, onUploadLogo, set, uploadError, - uploading + uploading, + urlError }: { data: ReferenceData; draft: UpdateChannelRequest; + externalLogoUrl: string; logoPreview: string | null; + onChangeExternalLogoUrl: (value: string) => void; onUploadLogo: (file: File) => void; set: (patch: Partial) => void; uploadError: string | null; uploading: boolean; + urlError: string | null; }) { const fileInputRef = useRef(null); const hlsDirect = draft.streamingMode === 'HttpLiveStreamingDirect'; const existingLogo = draft.logo?.urlWithContentType ?? draft.logo?.path ?? null; - const previewSrc = logoPreview ?? existingLogo; + const trimmedUrl = externalLogoUrl.trim(); + const previewSrc = trimmedUrl ? externalLogoUrl : (logoPreview ?? existingLogo); return ( @@ -629,6 +709,20 @@ function BrandingPane({ /> + + onChangeExternalLogoUrl(event.target.value)} + placeholder="https://example.com/logo.png" + size="sm" + value={externalLogoUrl} + /> +