diff --git a/CHANGELOG.md b/CHANGELOG.md index c5264f9d..381b5570 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -26,10 +26,12 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 - Stream log parsing refactored to use factory pattern: Simplified `ChannelService.parse_and_store_stream_info()` to route parsing through specialized log parsers instead of inline program-specific logic (~150 lines of code removed) - Stream profile names in fixtures updated to use proper capitalization (ffmpeg → FFmpeg, streamlink → Streamlink) - Frontend component refactoring for improved code organization and maintainability - Thanks [@nick4810](https://github.com/nick4810) - - Extracted large nested components into separate files (RecordingCard, RecordingDetailsModal, RecurringRuleModal, RecordingSynopsis) - - Moved business logic from components into dedicated utility files (dateTimeUtils, RecordingCardUtils, RecordingDetailsModalUtils, RecurringRuleModalUtils, DVRUtils) - - Lazy loaded heavy components (SuperuserForm, RecordingDetailsModal) with loading fallbacks + - Extracted large nested components into separate files (RecordingCard, RecordingDetailsModal, RecurringRuleModal, RecordingSynopsis, GuideRow, HourTimeline, PluginCard, ProgramRecordingModal, SeriesRecordingModal, Field) + - Moved business logic from components into dedicated utility files (dateTimeUtils, RecordingCardUtils, RecordingDetailsModalUtils, RecurringRuleModalUtils, DVRUtils, guideUtils, PluginsUtils, PluginCardUtils, notificationUtils) + - Lazy loaded heavy components (SuperuserForm, RecordingDetailsModal, ProgramRecordingModal, SeriesRecordingModal, PluginCard) with loading fallbacks - Removed unused Dashboard and Home pages + - Guide page refactoring: Extracted GuideRow and HourTimeline components, moved grid calculations and utility functions to guideUtils.js, added loading states for initial data fetching, improved performance through better memoization + - Plugins page refactoring: Extracted PluginCard and Field components, added Zustand store for plugin state management, improved plugin action confirmation handling, better separation of concerns between UI and business logic - Logo loading optimization: Logos now load only after both Channels and Streams tables complete loading to prevent blocking initial page render, with rendering gated by table readiness to ensure data loads before visual elements - M3U stream URLs now use `build_absolute_uri_with_port()` for consistency with EPG and logo URLs, ensuring uniform port handling across all M3U file URLs - Settings and Logos page refactoring for improved readability and separation of concerns - Thanks [@nick4810](https://github.com/nick4810) diff --git a/frontend/src/components/Field.jsx b/frontend/src/components/Field.jsx new file mode 100644 index 00000000..1293bf7b --- /dev/null +++ b/frontend/src/components/Field.jsx @@ -0,0 +1,47 @@ +import { NumberInput, Select, Switch, TextInput } from '@mantine/core'; +import React from 'react'; + +export const Field = ({ field, value, onChange }) => { + const common = { label: field.label, description: field.help_text }; + const effective = value ?? field.default; + switch (field.type) { + case 'boolean': + return ( + onChange(field.id, e.currentTarget.checked)} + label={field.label} + description={field.help_text} + /> + ); + case 'number': + return ( + onChange(field.id, v)} + {...common} + /> + ); + case 'select': + return ( + ({ - value: o.value + '', - label: o.label, - }))} - onChange={(v) => onChange(field.id, v)} - {...common} - /> - ); - case 'string': - default: - return ( - onChange(field.id, e.currentTarget.value)} - {...common} - /> - ); - } -}; +const PluginsList = ({ onRequestDelete, onRequireTrust, onRequestConfirm }) => { + const plugins = usePluginStore((state) => state.plugins); + const loading = usePluginStore((state) => state.loading); + const hasFetchedRef = useRef(false); -const PluginCard = ({ - plugin, - onSaveSettings, - onRunAction, - onToggleEnabled, - onRequireTrust, - onRequestDelete, -}) => { - const [settings, setSettings] = useState(plugin.settings || {}); - const [saving, setSaving] = useState(false); - const [running, setRunning] = useState(false); - const [enabled, setEnabled] = useState(!!plugin.enabled); - const [lastResult, setLastResult] = useState(null); - const [confirmOpen, setConfirmOpen] = useState(false); - const [confirmConfig, setConfirmConfig] = useState({ - title: '', - message: '', - onConfirm: null, - }); + useEffect(() => { + if (!hasFetchedRef.current) { + hasFetchedRef.current = true; + usePluginStore.getState().fetchPlugins(); + } + }, []); - // Keep local enabled state in sync with props (e.g., after import + enable) - React.useEffect(() => { - setEnabled(!!plugin.enabled); - }, [plugin.enabled]); - // Sync settings if plugin changes identity - React.useEffect(() => { - setSettings(plugin.settings || {}); - }, [plugin.key]); + const handleTogglePluginEnabled = async (key, next) => { + const resp = await setPluginEnabled(key, next); - const updateField = (id, val) => { - setSettings((prev) => ({ ...prev, [id]: val })); - }; - - const save = async () => { - setSaving(true); - try { - await onSaveSettings(plugin.key, settings); - notifications.show({ - title: 'Saved', - message: `${plugin.name} settings updated`, - color: 'green', + if (resp?.success) { + usePluginStore.getState().updatePlugin(key, { + enabled: next, + ever_enabled: resp?.ever_enabled, }); - } finally { - setSaving(false); } }; - const missing = plugin.missing; + if (loading && plugins.length === 0) { + return ; + } + return ( - - -
- {plugin.name} - - {plugin.description} + <> + {plugins.length > 0 && + + + }> + {plugins.map((p) => ( + + ))} + + + + } + + {plugins.length === 0 && ( + + + No plugins found. Drop a plugin into /data/plugins{' '} + and reload. -
- - onRequestDelete && onRequestDelete(plugin)} - > - - - - v{plugin.version || '1.0.0'} - - { - const next = e.currentTarget.checked; - if (next && !plugin.ever_enabled && onRequireTrust) { - const ok = await onRequireTrust(plugin); - if (!ok) { - // Revert - setEnabled(false); - return; - } - } - setEnabled(next); - const resp = await onToggleEnabled(plugin.key, next); - if (next && resp?.ever_enabled) { - plugin.ever_enabled = true; - } - }} - size="xs" - onLabel="On" - offLabel="Off" - disabled={missing} - /> - -
- - {missing && ( - - Missing plugin files. Re-import or delete this entry. - + )} - - {!missing && plugin.fields && plugin.fields.length > 0 && ( - - {plugin.fields.map((f) => ( - - ))} - - - - - )} - - {!missing && plugin.actions && plugin.actions.length > 0 && ( - <> - - - {plugin.actions.map((a) => ( - -
- {a.label} - {a.description && ( - - {a.description} - - )} -
- -
- ))} - {running && ( - - Running action… please wait - - )} - {!running && lastResult?.file && ( - - Output: {lastResult.file} - - )} - {!running && lastResult?.error && ( - - Error: {String(lastResult.error)} - - )} -
- - )} - { - setConfirmOpen(false); - setConfirmConfig({ title: '', message: '', onConfirm: null }); - }} - title={confirmConfig.title} - centered - > - - {confirmConfig.message} - - - - - - -
+ ); }; export default function PluginsPage() { - const [loading, setLoading] = useState(true); - const [plugins, setPlugins] = useState([]); const [importOpen, setImportOpen] = useState(false); const [importFile, setImportFile] = useState(null); const [importing, setImporting] = useState(false); @@ -358,118 +113,172 @@ export default function PluginsPage() { const [deleteOpen, setDeleteOpen] = useState(false); const [deleteTarget, setDeleteTarget] = useState(null); const [deleting, setDeleting] = useState(false); - const [uploadNoticeId, setUploadNoticeId] = useState(null); + const [confirmOpen, setConfirmOpen] = useState(false); + const [confirmConfig, setConfirmConfig] = useState({ + title: '', + message: '', + resolve: null, + }); - const load = async () => { - setLoading(true); - try { - const list = await API.getPlugins(); - setPlugins(list); - } finally { - setLoading(false); - } + const handleReload = () => { + usePluginStore.getState().invalidatePlugins(); }; - useEffect(() => { - load(); + const handleRequestDelete = useCallback((pl) => { + setDeleteTarget(pl); + setDeleteOpen(true); }, []); - const requireTrust = (plugin) => { + const requireTrust = useCallback((plugin) => { return new Promise((resolve) => { setTrustResolve(() => resolve); setTrustOpen(true); }); + }, []); + + const showImportForm = useCallback(() => { + setImportOpen(true); + setImported(null); + setImportFile(null); + setEnableAfterImport(false); + }, []); + + const requestConfirm = useCallback((title, message) => { + return new Promise((resolve) => { + setConfirmConfig({ title, message, resolve }); + setConfirmOpen(true); + }); + }, []); + + const handleImportPlugin = () => { + return async () => { + setImporting(true); + const id = showNotification({ + title: 'Uploading plugin', + message: 'Backend may restart; please wait…', + loading: true, + autoClose: false, + withCloseButton: false, + }); + try { + const resp = await importPlugin(importFile); + if (resp?.success && resp.plugin) { + setImported(resp.plugin); + usePluginStore.getState().invalidatePlugins(); + + updateNotification({ + id, + loading: false, + color: 'green', + title: 'Imported', + message: + 'Plugin imported. If the app briefly disconnected, it should be back now.', + autoClose: 3000, + }); + } else { + updateNotification({ + id, + loading: false, + color: 'red', + title: 'Import failed', + message: resp?.error || 'Unknown error', + autoClose: 5000, + }); + } + } catch (e) { + // API.importPlugin already showed a concise error; just update the loading notice + updateNotification({ + id, + loading: false, + color: 'red', + title: 'Import failed', + message: + (e?.body && (e.body.error || e.body.detail)) || + e?.message || + 'Failed', + autoClose: 5000, + }); + } finally { + setImporting(false); + } + }; }; + const handleEnablePlugin = () => { + return async () => { + if (!imported) return; + + const proceed = imported.ever_enabled || (await requireTrust(imported)); + if (proceed) { + const resp = await setPluginEnabled(imported.key, true); + if (resp?.success) { + usePluginStore.getState().updatePlugin(imported.key, { enabled: true, ever_enabled: true }); + + showNotification({ + title: imported.name, + message: 'Plugin enabled', + color: 'green', + }); + } + setImportOpen(false); + setImported(null); + setEnableAfterImport(false); + } + }; + }; + + const handleDeletePlugin = () => { + return async () => { + if (!deleteTarget) return; + setDeleting(true); + try { + const resp = await deletePluginByKey(deleteTarget.key); + if (resp?.success) { + usePluginStore.getState().removePlugin(deleteTarget.key); + + showNotification({ + title: deleteTarget.name, + message: 'Plugin deleted', + color: 'green', + }); + } + setDeleteOpen(false); + setDeleteTarget(null); + } finally { + setDeleting(false); + } + }; + }; + + const handleConfirm = useCallback((confirmed) => { + const resolver = confirmConfig.resolve; + setConfirmOpen(false); + setConfirmConfig({ title: '', message: '', resolve: null }); + if (resolver) resolver(confirmed); + }, [confirmConfig.resolve]); + return ( - + Plugins - - { - await API.reloadPlugins(); - await load(); - }} - title="Reload" - > + - {loading ? ( - - ) : ( - <> - - {plugins.map((p) => ( - { - const resp = await API.setPluginEnabled(key, next); - if (resp?.ever_enabled !== undefined) { - setPlugins((prev) => - prev.map((pl) => - pl.key === key - ? { - ...pl, - ever_enabled: resp.ever_enabled, - enabled: resp.enabled, - } - : pl - ) - ); - } else { - setPlugins((prev) => - prev.map((pl) => - pl.key === key ? { ...pl, enabled: next } : pl - ) - ); - } - return resp; - }} - onRequireTrust={requireTrust} - onRequestDelete={(plugin) => { - setDeleteTarget(plugin); - setDeleteOpen(true); - }} - /> - ))} - - {plugins.length === 0 && ( - - - No plugins found. Drop a plugin into /data/plugins{' '} - and reload. - - - )} - - )} + + {/* Import Plugin Modal */} { - setImporting(true); - const id = notifications.show({ - title: 'Uploading plugin', - message: 'Backend may restart; please wait…', - loading: true, - autoClose: false, - withCloseButton: false, - }); - setUploadNoticeId(id); - try { - const resp = await API.importPlugin(importFile); - if (resp?.success && resp.plugin) { - setImported(resp.plugin); - setPlugins((prev) => [ - resp.plugin, - ...prev.filter((p) => p.key !== resp.plugin.key), - ]); - notifications.update({ - id, - loading: false, - color: 'green', - title: 'Imported', - message: - 'Plugin imported. If the app briefly disconnected, it should be back now.', - autoClose: 3000, - }); - } else { - notifications.update({ - id, - loading: false, - color: 'red', - title: 'Import failed', - message: resp?.error || 'Unknown error', - autoClose: 5000, - }); - } - } catch (e) { - // API.importPlugin already showed a concise error; just update the loading notice - notifications.update({ - id, - loading: false, - color: 'red', - title: 'Import failed', - message: - (e?.body && (e.body.error || e.body.detail)) || - e?.message || - 'Failed', - autoClose: 5000, - }); - } finally { - setImporting(false); - setUploadNoticeId(null); - } - }} + onClick={handleImportPlugin()} > Upload @@ -612,36 +367,7 @@ export default function PluginsPage() { @@ -727,33 +453,37 @@ export default function PluginsPage() { size="xs" color="red" loading={deleting} - onClick={async () => { - if (!deleteTarget) return; - setDeleting(true); - try { - const resp = await API.deletePlugin(deleteTarget.key); - if (resp?.success) { - setPlugins((prev) => - prev.filter((p) => p.key !== deleteTarget.key) - ); - notifications.show({ - title: deleteTarget.name, - message: 'Plugin deleted', - color: 'green', - }); - } - setDeleteOpen(false); - setDeleteTarget(null); - } finally { - setDeleting(false); - } - }} + onClick={handleDeletePlugin()} > Delete - + + {/* Confirmation modal */} + handleConfirm(false)} + title={confirmConfig.title} + centered + > + + {confirmConfig.message} + + + + + + + ); } diff --git a/frontend/src/pages/guideUtils.js b/frontend/src/pages/guideUtils.js index 1f4ff671..68bb74b2 100644 --- a/frontend/src/pages/guideUtils.js +++ b/frontend/src/pages/guideUtils.js @@ -1,7 +1,26 @@ -import dayjs from 'dayjs'; +import { + convertToMs, + initializeTime, + startOfDay, + isBefore, + isAfter, + isSame, + add, + diff, + format, + getNow, + getNowMs, + roundToNearest +} from '../utils/dateTimeUtils.js'; +import API from '../api.js'; export const PROGRAM_HEIGHT = 90; export const EXPANDED_PROGRAM_HEIGHT = 180; +/** Layout constants */ +export const CHANNEL_WIDTH = 120; // Width of the channel/logo column +export const HOUR_WIDTH = 450; // Increased from 300 to 450 to make each program wider +export const MINUTE_INCREMENT = 15; // For positioning programs every 15 min +export const MINUTE_BLOCK_WIDTH = HOUR_WIDTH / (60 / MINUTE_INCREMENT); export function buildChannelIdMap(channels, tvgsById, epgs = {}) { const map = new Map(); @@ -38,25 +57,32 @@ export function buildChannelIdMap(channels, tvgsById, epgs = {}) { return map; } -export function mapProgramsByChannel(programs, channelIdByTvgId) { +export const mapProgramsByChannel = (programs, channelIdByTvgId) => { if (!programs?.length || !channelIdByTvgId?.size) { return new Map(); } const map = new Map(); + const nowMs = getNowMs(); + programs.forEach((program) => { const channelIds = channelIdByTvgId.get(String(program.tvg_id)); if (!channelIds || channelIds.length === 0) { return; } - const startMs = program.startMs ?? dayjs(program.start_time).valueOf(); - const endMs = program.endMs ?? dayjs(program.end_time).valueOf(); + const startMs = program.startMs ?? convertToMs(program.start_time); + const endMs = program.endMs ?? convertToMs(program.end_time); const programData = { ...program, startMs, endMs, + programStart: initializeTime(program.startMs), + programEnd: initializeTime(program.endMs), + // Precompute live/past status + isLive: nowMs >= program.startMs && nowMs < program.endMs, + isPast: nowMs >= program.endMs, }; // Add this program to all channels that share the same TVG ID @@ -73,7 +99,7 @@ export function mapProgramsByChannel(programs, channelIdByTvgId) { }); return map; -} +}; export function computeRowHeights( filteredChannels, @@ -94,3 +120,282 @@ export function computeRowHeights( return expanded ? expandedHeight : defaultHeight; }); } + +export const fetchPrograms = async () => { + console.log('Fetching program grid...'); + const fetched = await API.getGrid(); // GETs your EPG grid + console.log(`Received ${fetched.length} programs`); + + return fetched.map((program) => { + return { + ...program, + startMs: convertToMs(program.start_time), + endMs: convertToMs(program.end_time), + }; + }); +}; + +export const sortChannels = (channels) => { + // Include ALL channels, sorted by channel number - don't filter by EPG data + const sortedChannels = Object.values(channels).sort( + (a, b) => + (a.channel_number || Infinity) - (b.channel_number || Infinity) + ); + + console.log(`Using all ${sortedChannels.length} available channels`); + return sortedChannels; +} + +export const filterGuideChannels = (guideChannels, searchQuery, selectedGroupId, selectedProfileId, profiles) => { + return guideChannels.filter((channel) => { + // Search filter + if (searchQuery) { + if (!channel.name.toLowerCase().includes(searchQuery.toLowerCase())) return false; + } + + // Channel group filter + if (selectedGroupId !== 'all') { + if (channel.channel_group_id !== parseInt(selectedGroupId)) return false; + } + + // Profile filter + if (selectedProfileId !== 'all') { + const profileChannels = profiles[selectedProfileId]?.channels || []; + const enabledChannelIds = Array.isArray(profileChannels) + ? profileChannels.filter((pc) => pc.enabled).map((pc) => pc.id) + : profiles[selectedProfileId]?.channels instanceof Set + ? Array.from(profiles[selectedProfileId].channels) + : []; + + if (!enabledChannelIds.includes(channel.id)) return false; + } + + return true; + }); +} + +export const calculateEarliestProgramStart = (programs, defaultStart) => { + if (!programs.length) return defaultStart; + return programs.reduce((acc, p) => { + const s = initializeTime(p.start_time); + return isBefore(s, acc) ? s : acc; + }, defaultStart); +} + +export const calculateLatestProgramEnd = (programs, defaultEnd) => { + if (!programs.length) return defaultEnd; + return programs.reduce((acc, p) => { + const e = initializeTime(p.end_time); + return isAfter(e, acc) ? e : acc; + }, defaultEnd); +} + +export const calculateStart = (earliestProgramStart, defaultStart) => { + return isBefore(earliestProgramStart, defaultStart) + ? earliestProgramStart + : defaultStart; +} + +export const calculateEnd = (latestProgramEnd, defaultEnd) => { + return isAfter(latestProgramEnd, defaultEnd) ? latestProgramEnd : defaultEnd; +} + +export const mapChannelsById = (guideChannels) => { + const map = new Map(); + guideChannels.forEach((channel) => { + map.set(channel.id, channel); + }); + return map; +} + +export const mapRecordingsByProgramId = (recordings) => { + const map = new Map(); + (recordings || []).forEach((recording) => { + const programId = recording?.custom_properties?.program?.id; + if (programId != null) { + map.set(programId, recording); + } + }); + return map; +} + +export const formatTime = (time, dateFormat) => { + const today = startOfDay(getNow()); + const tomorrow = add(today, 1, 'day'); + const weekLater = add(today, 7, 'day'); + const day = startOfDay(time); + + if (isSame(day, today, 'day')) { + return 'Today'; + } else if (isSame(day, tomorrow, 'day')) { + return 'Tomorrow'; + } else if (isBefore(day, weekLater)) { + // Within a week, show day name + return format(time, 'dddd'); + } else { + // Beyond a week, show month and day + return format(time, dateFormat); + } +} + +export const calculateHourTimeline = (start, end, formatDayLabel) => { + const hours = []; + let current = start; + let currentDay = null; + + while (isBefore(current, end)) { + // Check if we're entering a new day + const day = startOfDay(current); + const isNewDay = !currentDay || !isSame(day, currentDay, 'day'); + + if (isNewDay) { + currentDay = day; + } + + // Add day information to our hour object + hours.push({ + time: current, + isNewDay, + dayLabel: formatDayLabel(current), + }); + + current = add(current, 1, 'hour'); + } + return hours; +} + +export const calculateNowPosition = (now, start, end) => { + if (isBefore(now, start) || isAfter(now, end)) return -1; + const minutesSinceStart = diff(now, start, 'minute'); + return (minutesSinceStart / MINUTE_INCREMENT) * MINUTE_BLOCK_WIDTH; +}; + +export const calculateScrollPosition = (now, start) => { + const roundedNow = roundToNearest(now, 30); + const nowOffset = diff(roundedNow, start, 'minute'); + const scrollPosition = + (nowOffset / MINUTE_INCREMENT) * MINUTE_BLOCK_WIDTH - MINUTE_BLOCK_WIDTH; + + return Math.max(scrollPosition, 0); +}; + +export const matchChannelByTvgId = (channelIdByTvgId, channelById, tvgId) => { + const channelIds = channelIdByTvgId.get(String(tvgId)); + if (!channelIds || channelIds.length === 0) { + return null; + } + // Return the first channel that matches this TVG ID + return channelById.get(channelIds[0]) || null; +} + +export const fetchRules = async () => { + return await API.listSeriesRules(); +} + +export const getRuleByProgram = (rules, program) => { + return (rules || []).find( + (r) => + String(r.tvg_id) === String(program.tvg_id) && + (!r.title || r.title === program.title) + ); +} + +export const createRecording = async (channel, program) => { + await API.createRecording({ + channel: `${channel.id}`, + start_time: program.start_time, + end_time: program.end_time, + custom_properties: { program }, + }); +} + +export const createSeriesRule = async (program, mode) => { + await API.createSeriesRule({ + tvg_id: program.tvg_id, + mode, + title: program.title, + }); +} + +export const evaluateSeriesRule = async (program) => { + await API.evaluateSeriesRules(program.tvg_id); +} + +export const calculateLeftScrollPosition = (program, start) => { + const programStartMs = + program.startMs ?? convertToMs(program.start_time); + const startOffsetMinutes = (programStartMs - convertToMs(start)) / 60000; + + return (startOffsetMinutes / MINUTE_INCREMENT) * MINUTE_BLOCK_WIDTH; +}; + +export const calculateDesiredScrollPosition = (leftPx) => { + return Math.max(0, leftPx - 20); +} + +export const calculateScrollPositionByTimeClick = (event, clickedTime, start) => { + const rect = event.currentTarget.getBoundingClientRect(); + const clickPositionX = event.clientX - rect.left; + const percentageAcross = clickPositionX / rect.width; + const minuteWithinHour = percentageAcross * 60; + + const snappedMinute = Math.round(minuteWithinHour / 15) * 15; + + const adjustedTime = (snappedMinute === 60) + ? add(clickedTime, 1, 'hour').minute(0) + : clickedTime.minute(snappedMinute); + + const snappedOffset = diff(adjustedTime, start, 'minute'); + return (snappedOffset / MINUTE_INCREMENT) * MINUTE_BLOCK_WIDTH; +}; + +export const getGroupOptions = (channelGroups, guideChannels) => { + const options = [{ value: 'all', label: 'All Channel Groups' }]; + + if (channelGroups && guideChannels.length > 0) { + // Get unique channel group IDs from the channels that have program data + const usedGroupIds = new Set(); + guideChannels.forEach((channel) => { + if (channel.channel_group_id) { + usedGroupIds.add(channel.channel_group_id); + } + }); + // Only add groups that are actually used by channels in the guide + Object.values(channelGroups) + .filter((group) => usedGroupIds.has(group.id)) + .sort((a, b) => a.name.localeCompare(b.name)) // Sort alphabetically + .forEach((group) => { + options.push({ + value: group.id.toString(), + label: group.name, + }); + }); + } + return options; +} + +export const getProfileOptions = (profiles) => { + const options = [{ value: 'all', label: 'All Profiles' }]; + + if (profiles) { + Object.values(profiles).forEach((profile) => { + if (profile.id !== '0') { + // Skip the 'All' default profile + options.push({ + value: profile.id.toString(), + label: profile.name, + }); + } + }); + } + + return options; +} + +export const deleteSeriesRuleByTvgId = async (tvg_id) => { + await API.deleteSeriesRule(tvg_id); +} + +export const evaluateSeriesRulesByTvgId = async (tvg_id) => { + await API.evaluateSeriesRules(tvg_id); +} \ No newline at end of file diff --git a/frontend/src/store/plugins.jsx b/frontend/src/store/plugins.jsx new file mode 100644 index 00000000..e8d0b065 --- /dev/null +++ b/frontend/src/store/plugins.jsx @@ -0,0 +1,41 @@ +import { create } from 'zustand'; +import API from '../api'; + +export const usePluginStore = create((set, get) => ({ + plugins: [], + loading: false, + error: null, + + fetchPlugins: async () => { + set({ loading: true, error: null }); + try { + const response = await API.getPlugins(); + set({ plugins: response || [], loading: false }); + } catch (error) { + set({ error, loading: false }); + } + }, + + updatePlugin: (key, updates) => { + set((state) => ({ + plugins: state.plugins.map((p) => + p.key === key ? { ...p, ...updates } : p + ), + })); + }, + + addPlugin: (plugin) => { + set((state) => ({ plugins: [...state.plugins, plugin] })); + }, + + removePlugin: (key) => { + set((state) => ({ + plugins: state.plugins.filter((p) => p.key !== key), + })); + }, + + invalidatePlugins: () => { + set({ plugins: [] }); + get().fetchPlugins(); + }, +})); \ No newline at end of file diff --git a/frontend/src/utils/cards/PluginCardUtils.js b/frontend/src/utils/cards/PluginCardUtils.js new file mode 100644 index 00000000..8752e019 --- /dev/null +++ b/frontend/src/utils/cards/PluginCardUtils.js @@ -0,0 +1,24 @@ +export const getConfirmationDetails = (action, plugin, settings) => { + const actionConfirm = action.confirm; + const confirmField = (plugin.fields || []).find((f) => f.id === 'confirm'); + let requireConfirm = false; + let confirmTitle = `Run ${action.label}?`; + let confirmMessage = `You're about to run "${action.label}" from "${plugin.name}".`; + + if (actionConfirm) { + if (typeof actionConfirm === 'boolean') { + requireConfirm = actionConfirm; + } else if (typeof actionConfirm === 'object') { + requireConfirm = actionConfirm.required !== false; + if (actionConfirm.title) confirmTitle = actionConfirm.title; + if (actionConfirm.message) confirmMessage = actionConfirm.message; + } + } else if (confirmField) { + const settingVal = settings?.confirm; + const effectiveConfirm = + (settingVal !== undefined ? settingVal : confirmField.default) ?? false; + requireConfirm = !!effectiveConfirm; + } + + return { requireConfirm, confirmTitle, confirmMessage }; +}; diff --git a/frontend/src/utils/dateTimeUtils.js b/frontend/src/utils/dateTimeUtils.js index 7b6c6f2f..64a50947 100644 --- a/frontend/src/utils/dateTimeUtils.js +++ b/frontend/src/utils/dateTimeUtils.js @@ -73,15 +73,15 @@ export const useTimeHelpers = () => { (value) => { if (!value) return dayjs.invalid(); try { - return dayjs(value).tz(timeZone); + return initializeTime(value).tz(timeZone); } catch (error) { - return dayjs(value); + return initializeTime(value); } }, [timeZone] ); - const userNow = useCallback(() => dayjs().tz(timeZone), [timeZone]); + const userNow = useCallback(() => getNow().tz(timeZone), [timeZone]); return { timeZone, toUserTime, userNow }; }; @@ -113,7 +113,7 @@ export const toTimeString = (value) => { if (parsed.isValid()) return parsed.format('HH:mm'); return value; } - const parsed = dayjs(value); + const parsed = initializeTime(value); return parsed.isValid() ? parsed.format('HH:mm') : '00:00'; }; diff --git a/frontend/src/utils/pages/PluginsUtils.js b/frontend/src/utils/pages/PluginsUtils.js new file mode 100644 index 00000000..bae98e93 --- /dev/null +++ b/frontend/src/utils/pages/PluginsUtils.js @@ -0,0 +1,17 @@ +import API from '../../api.js'; + +export const updatePluginSettings = async (key, settings) => { + return await API.updatePluginSettings(key, settings); +}; +export const runPluginAction = async (key, actionId) => { + return await API.runPluginAction(key, actionId); +}; +export const setPluginEnabled = async (key, next) => { + return await API.setPluginEnabled(key, next); +}; +export const importPlugin = async (importFile) => { + return await API.importPlugin(importFile); +}; +export const deletePluginByKey = (key) => { + return API.deletePlugin(key); +}; \ No newline at end of file