Compare commits

...

2 Commits

Author SHA1 Message Date
Mark McDowall 15f3c64912 Convert App to TypeScript 2024-07-28 17:05:05 -07:00
Mark McDowall 29a9b609c7 Convert Utilities to TypeScript 2024-07-28 17:00:34 -07:00
100 changed files with 872 additions and 868 deletions
.vscode
frontend/src
App
Commands
Components/Page
InteractiveImport/Quality
Series
Store
System/Updates
Utilities
typings
package.jsonyarn.lock

3
.vscode/settings.json vendored Normal file
View File

@ -0,0 +1,3 @@
{
"typescript.tsdk": "node_modules\\typescript\\lib"
}

View File

@ -1,13 +1,19 @@
import { ConnectedRouter } from 'connected-react-router';
import { ConnectedRouter, ConnectedRouterProps } from 'connected-react-router';
import PropTypes from 'prop-types';
import React from 'react';
import DocumentTitle from 'react-document-title';
import { Provider } from 'react-redux';
import { Store } from 'redux';
import PageConnector from 'Components/Page/PageConnector';
import ApplyTheme from './ApplyTheme';
import AppRoutes from './AppRoutes';
function App({ store, history }) {
interface AppProps {
store: Store;
history: ConnectedRouterProps['history'];
}
function App({ store, history }: AppProps) {
return (
<DocumentTitle title={window.Sonarr.instanceName}>
<Provider store={store}>
@ -24,7 +30,7 @@ function App({ store, history }) {
App.propTypes = {
store: PropTypes.object.isRequired,
history: PropTypes.object.isRequired
history: PropTypes.object.isRequired,
};
export default App;

View File

@ -35,60 +35,37 @@ import getPathWithUrlBase from 'Utilities/getPathWithUrlBase';
import CutoffUnmetConnector from 'Wanted/CutoffUnmet/CutoffUnmetConnector';
import MissingConnector from 'Wanted/Missing/MissingConnector';
function AppRoutes(props) {
const {
app
} = props;
function AppRoutes() {
return (
<Switch>
{/*
Series
*/}
<Route
exact={true}
path="/"
component={SeriesIndex}
/>
<Route exact={true} path="/" component={SeriesIndex} />
{
window.Sonarr.urlBase &&
<Route
exact={true}
path="/"
addUrlBase={false}
render={() => {
return (
<Redirect
to={getPathWithUrlBase('/')}
component={app}
/>
);
}}
/>
}
{window.Sonarr.urlBase && (
<Route
exact={true}
path="/"
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
// @ts-ignore
addUrlBase={false}
render={() => {
return <Redirect to={getPathWithUrlBase('/')} />;
}}
/>
)}
<Route
path="/add/new"
component={AddNewSeriesConnector}
/>
<Route path="/add/new" component={AddNewSeriesConnector} />
<Route
path="/add/import"
component={ImportSeries}
/>
<Route path="/add/import" component={ImportSeries} />
<Route
path="/serieseditor"
exact={true}
render={() => {
return (
<Redirect
to={getPathWithUrlBase('/')}
component={app}
/>
);
return <Redirect to={getPathWithUrlBase('/')} />;
}}
/>
@ -96,96 +73,57 @@ function AppRoutes(props) {
path="/seasonpass"
exact={true}
render={() => {
return (
<Redirect
to={getPathWithUrlBase('/')}
component={app}
/>
);
return <Redirect to={getPathWithUrlBase('/')} />;
}}
/>
<Route
path="/series/:titleSlug"
component={SeriesDetailsPageConnector}
/>
<Route path="/series/:titleSlug" component={SeriesDetailsPageConnector} />
{/*
Calendar
*/}
<Route
path="/calendar"
component={CalendarPageConnector}
/>
<Route path="/calendar" component={CalendarPageConnector} />
{/*
Activity
*/}
<Route
path="/activity/history"
component={History}
/>
<Route path="/activity/history" component={History} />
<Route
path="/activity/queue"
component={Queue}
/>
<Route path="/activity/queue" component={Queue} />
<Route
path="/activity/blocklist"
component={Blocklist}
/>
<Route path="/activity/blocklist" component={Blocklist} />
{/*
Wanted
*/}
<Route
path="/wanted/missing"
component={MissingConnector}
/>
<Route path="/wanted/missing" component={MissingConnector} />
<Route
path="/wanted/cutoffunmet"
component={CutoffUnmetConnector}
/>
<Route path="/wanted/cutoffunmet" component={CutoffUnmetConnector} />
{/*
Settings
*/}
<Route
exact={true}
path="/settings"
component={Settings}
/>
<Route exact={true} path="/settings" component={Settings} />
<Route
path="/settings/mediamanagement"
component={MediaManagementConnector}
/>
<Route
path="/settings/profiles"
component={Profiles}
/>
<Route path="/settings/profiles" component={Profiles} />
<Route
path="/settings/quality"
component={QualityConnector}
/>
<Route path="/settings/quality" component={QualityConnector} />
<Route
path="/settings/customformats"
component={CustomFormatSettingsPage}
/>
<Route
path="/settings/indexers"
component={IndexerSettingsConnector}
/>
<Route path="/settings/indexers" component={IndexerSettingsConnector} />
<Route
path="/settings/downloadclients"
@ -197,84 +135,48 @@ function AppRoutes(props) {
component={ImportListSettingsConnector}
/>
<Route
path="/settings/connect"
component={NotificationSettings}
/>
<Route path="/settings/connect" component={NotificationSettings} />
<Route
path="/settings/metadata"
component={MetadataSettings}
/>
<Route path="/settings/metadata" component={MetadataSettings} />
<Route
path="/settings/metadatasource"
component={MetadataSourceSettings}
/>
<Route
path="/settings/tags"
component={TagSettings}
/>
<Route path="/settings/tags" component={TagSettings} />
<Route
path="/settings/general"
component={GeneralSettingsConnector}
/>
<Route path="/settings/general" component={GeneralSettingsConnector} />
<Route
path="/settings/ui"
component={UISettingsConnector}
/>
<Route path="/settings/ui" component={UISettingsConnector} />
{/*
System
*/}
<Route
path="/system/status"
component={Status}
/>
<Route path="/system/status" component={Status} />
<Route
path="/system/tasks"
component={Tasks}
/>
<Route path="/system/tasks" component={Tasks} />
<Route
path="/system/backup"
component={BackupsConnector}
/>
<Route path="/system/backup" component={BackupsConnector} />
<Route
path="/system/updates"
component={Updates}
/>
<Route path="/system/updates" component={Updates} />
<Route
path="/system/events"
component={LogsTableConnector}
/>
<Route path="/system/events" component={LogsTableConnector} />
<Route
path="/system/logs/files"
component={Logs}
/>
<Route path="/system/logs/files" component={Logs} />
{/*
Not Found
*/}
<Route
path="*"
component={NotFound}
/>
<Route path="*" component={NotFound} />
</Switch>
);
}
AppRoutes.propTypes = {
app: PropTypes.func.isRequired
app: PropTypes.func.isRequired,
};
export default AppRoutes;

View File

@ -1,30 +0,0 @@
import PropTypes from 'prop-types';
import React from 'react';
import Modal from 'Components/Modal/Modal';
import AppUpdatedModalContentConnector from './AppUpdatedModalContentConnector';
function AppUpdatedModal(props) {
const {
isOpen,
onModalClose
} = props;
return (
<Modal
isOpen={isOpen}
closeOnBackgroundClick={false}
onModalClose={onModalClose}
>
<AppUpdatedModalContentConnector
onModalClose={onModalClose}
/>
</Modal>
);
}
AppUpdatedModal.propTypes = {
isOpen: PropTypes.bool.isRequired,
onModalClose: PropTypes.func.isRequired
};
export default AppUpdatedModal;

View File

@ -0,0 +1,28 @@
import React, { useCallback } from 'react';
import Modal from 'Components/Modal/Modal';
import AppUpdatedModalContent from './AppUpdatedModalContent';
interface AppUpdatedModalProps {
isOpen: boolean;
onModalClose: (...args: unknown[]) => unknown;
}
function AppUpdatedModal(props: AppUpdatedModalProps) {
const { isOpen, onModalClose } = props;
const handleModalClose = useCallback(() => {
location.reload();
}, []);
return (
<Modal
isOpen={isOpen}
closeOnBackgroundClick={false}
onModalClose={onModalClose}
>
<AppUpdatedModalContent onModalClose={handleModalClose} />
</Modal>
);
}
export default AppUpdatedModal;

View File

@ -1,12 +0,0 @@
import { connect } from 'react-redux';
import AppUpdatedModal from './AppUpdatedModal';
function createMapDispatchToProps(dispatch, props) {
return {
onModalClose() {
location.reload();
}
};
}
export default connect(null, createMapDispatchToProps)(AppUpdatedModal);

View File

@ -1,139 +0,0 @@
import PropTypes from 'prop-types';
import React from 'react';
import Button from 'Components/Link/Button';
import LoadingIndicator from 'Components/Loading/LoadingIndicator';
import InlineMarkdown from 'Components/Markdown/InlineMarkdown';
import ModalBody from 'Components/Modal/ModalBody';
import ModalContent from 'Components/Modal/ModalContent';
import ModalFooter from 'Components/Modal/ModalFooter';
import ModalHeader from 'Components/Modal/ModalHeader';
import { kinds } from 'Helpers/Props';
import UpdateChanges from 'System/Updates/UpdateChanges';
import translate from 'Utilities/String/translate';
import styles from './AppUpdatedModalContent.css';
function mergeUpdates(items, version, prevVersion) {
let installedIndex = items.findIndex((u) => u.version === version);
let installedPreviouslyIndex = items.findIndex((u) => u.version === prevVersion);
if (installedIndex === -1) {
installedIndex = 0;
}
if (installedPreviouslyIndex === -1) {
installedPreviouslyIndex = items.length;
} else if (installedPreviouslyIndex === installedIndex && items.length) {
installedPreviouslyIndex += 1;
}
const appliedUpdates = items.slice(installedIndex, installedPreviouslyIndex);
if (!appliedUpdates.length) {
return null;
}
const appliedChanges = { new: [], fixed: [] };
appliedUpdates.forEach((u) => {
if (u.changes) {
appliedChanges.new.push(... u.changes.new);
appliedChanges.fixed.push(... u.changes.fixed);
}
});
const mergedUpdate = Object.assign({}, appliedUpdates[0], { changes: appliedChanges });
if (!appliedChanges.new.length && !appliedChanges.fixed.length) {
mergedUpdate.changes = null;
}
return mergedUpdate;
}
function AppUpdatedModalContent(props) {
const {
version,
prevVersion,
isPopulated,
error,
items,
onSeeChangesPress,
onModalClose
} = props;
const update = mergeUpdates(items, version, prevVersion);
return (
<ModalContent onModalClose={onModalClose}>
<ModalHeader>
{translate('AppUpdated')}
</ModalHeader>
<ModalBody>
<div>
<InlineMarkdown data={translate('AppUpdatedVersion', { version })} blockClassName={styles.version} />
</div>
{
isPopulated && !error && !!update &&
<div>
{
!update.changes &&
<div className={styles.maintenance}>{translate('MaintenanceRelease')}</div>
}
{
!!update.changes &&
<div>
<div className={styles.changes}>
{translate('WhatsNew')}
</div>
<UpdateChanges
title={translate('New')}
changes={update.changes.new}
/>
<UpdateChanges
title={translate('Fixed')}
changes={update.changes.fixed}
/>
</div>
}
</div>
}
{
!isPopulated && !error &&
<LoadingIndicator />
}
</ModalBody>
<ModalFooter>
<Button
onPress={onSeeChangesPress}
>
{translate('RecentChanges')}
</Button>
<Button
kind={kinds.PRIMARY}
onPress={onModalClose}
>
{translate('Reload')}
</Button>
</ModalFooter>
</ModalContent>
);
}
AppUpdatedModalContent.propTypes = {
version: PropTypes.string.isRequired,
prevVersion: PropTypes.string,
isPopulated: PropTypes.bool.isRequired,
error: PropTypes.object,
items: PropTypes.arrayOf(PropTypes.object).isRequired,
onSeeChangesPress: PropTypes.func.isRequired,
onModalClose: PropTypes.func.isRequired
};
export default AppUpdatedModalContent;

View File

@ -0,0 +1,145 @@
import React, { useCallback, useEffect } from 'react';
import { useDispatch, useSelector } from 'react-redux';
import Button from 'Components/Link/Button';
import LoadingIndicator from 'Components/Loading/LoadingIndicator';
import InlineMarkdown from 'Components/Markdown/InlineMarkdown';
import ModalBody from 'Components/Modal/ModalBody';
import ModalContent from 'Components/Modal/ModalContent';
import ModalFooter from 'Components/Modal/ModalFooter';
import ModalHeader from 'Components/Modal/ModalHeader';
import usePrevious from 'Helpers/Hooks/usePrevious';
import { kinds } from 'Helpers/Props';
import { fetchUpdates } from 'Store/Actions/systemActions';
import UpdateChanges from 'System/Updates/UpdateChanges';
import Update from 'typings/Update';
import translate from 'Utilities/String/translate';
import AppState from './State/AppState';
import styles from './AppUpdatedModalContent.css';
function mergeUpdates(items: Update[], version: string, prevVersion?: string) {
let installedIndex = items.findIndex((u) => u.version === version);
let installedPreviouslyIndex = items.findIndex(
(u) => u.version === prevVersion
);
if (installedIndex === -1) {
installedIndex = 0;
}
if (installedPreviouslyIndex === -1) {
installedPreviouslyIndex = items.length;
} else if (installedPreviouslyIndex === installedIndex && items.length) {
installedPreviouslyIndex += 1;
}
const appliedUpdates = items.slice(installedIndex, installedPreviouslyIndex);
if (!appliedUpdates.length) {
return null;
}
const appliedChanges: Update['changes'] = { new: [], fixed: [] };
appliedUpdates.forEach((u: Update) => {
if (u.changes) {
appliedChanges.new.push(...u.changes.new);
appliedChanges.fixed.push(...u.changes.fixed);
}
});
const mergedUpdate: Update = Object.assign({}, appliedUpdates[0], {
changes: appliedChanges,
});
if (!appliedChanges.new.length && !appliedChanges.fixed.length) {
mergedUpdate.changes = null;
}
return mergedUpdate;
}
interface AppUpdatedModalContentProps {
onModalClose: () => void;
}
function AppUpdatedModalContent(props: AppUpdatedModalContentProps) {
const dispatch = useDispatch();
const { version, prevVersion } = useSelector((state: AppState) => state.app);
const { isPopulated, error, items } = useSelector(
(state: AppState) => state.system.updates
);
const previousVersion = usePrevious(version);
const { onModalClose } = props;
const update = mergeUpdates(items, version, prevVersion);
const handleSeeChangesPress = useCallback(() => {
window.location.href = `${window.Sonarr.urlBase}/system/updates`;
}, []);
useEffect(() => {
dispatch(fetchUpdates());
}, [dispatch]);
useEffect(() => {
if (version !== previousVersion) {
dispatch(fetchUpdates());
}
}, [version, previousVersion, dispatch]);
return (
<ModalContent onModalClose={onModalClose}>
<ModalHeader>{translate('AppUpdated')}</ModalHeader>
<ModalBody>
<div>
<InlineMarkdown
data={translate('AppUpdatedVersion', { version })}
blockClassName={styles.version}
/>
</div>
{isPopulated && !error && !!update ? (
<div>
{update.changes ? (
<div className={styles.maintenance}>
{translate('MaintenanceRelease')}
</div>
) : null}
{update.changes ? (
<div>
<div className={styles.changes}>{translate('WhatsNew')}</div>
<UpdateChanges
title={translate('New')}
changes={update.changes.new}
/>
<UpdateChanges
title={translate('Fixed')}
changes={update.changes.fixed}
/>
</div>
) : null}
</div>
) : null}
{!isPopulated && !error ? <LoadingIndicator /> : null}
</ModalBody>
<ModalFooter>
<Button onPress={handleSeeChangesPress}>
{translate('RecentChanges')}
</Button>
<Button kind={kinds.PRIMARY} onPress={onModalClose}>
{translate('Reload')}
</Button>
</ModalFooter>
</ModalContent>
);
}
export default AppUpdatedModalContent;

View File

@ -1,78 +0,0 @@
import PropTypes from 'prop-types';
import React, { Component } from 'react';
import { connect } from 'react-redux';
import { createSelector } from 'reselect';
import { fetchUpdates } from 'Store/Actions/systemActions';
import AppUpdatedModalContent from './AppUpdatedModalContent';
function createMapStateToProps() {
return createSelector(
(state) => state.app.version,
(state) => state.app.prevVersion,
(state) => state.system.updates,
(version, prevVersion, updates) => {
const {
isPopulated,
error,
items
} = updates;
return {
version,
prevVersion,
isPopulated,
error,
items
};
}
);
}
function createMapDispatchToProps(dispatch, props) {
return {
dispatchFetchUpdates() {
dispatch(fetchUpdates());
},
onSeeChangesPress() {
window.location = `${window.Sonarr.urlBase}/system/updates`;
}
};
}
class AppUpdatedModalContentConnector extends Component {
//
// Lifecycle
componentDidMount() {
this.props.dispatchFetchUpdates();
}
componentDidUpdate(prevProps) {
if (prevProps.version !== this.props.version) {
this.props.dispatchFetchUpdates();
}
}
//
// Render
render() {
const {
dispatchFetchUpdates,
...otherProps
} = this.props;
return (
<AppUpdatedModalContent {...otherProps} />
);
}
}
AppUpdatedModalContentConnector.propTypes = {
version: PropTypes.string.isRequired,
dispatchFetchUpdates: PropTypes.func.isRequired
};
export default connect(createMapStateToProps, createMapDispatchToProps)(AppUpdatedModalContentConnector);

View File

@ -1,13 +1,9 @@
import React, { Fragment, ReactNode, useCallback, useEffect } from 'react';
import { useCallback, useEffect } from 'react';
import { useSelector } from 'react-redux';
import { createSelector } from 'reselect';
import themes from 'Styles/Themes';
import AppState from './State/AppState';
interface ApplyThemeProps {
children: ReactNode;
}
function createThemeSelector() {
return createSelector(
(state: AppState) => state.settings.ui.item.theme || window.Sonarr.theme,
@ -17,7 +13,7 @@ function createThemeSelector() {
);
}
function ApplyTheme({ children }: ApplyThemeProps) {
function ApplyTheme() {
const theme = useSelector(createThemeSelector());
const updateCSSVariables = useCallback(() => {
@ -31,7 +27,7 @@ function ApplyTheme({ children }: ApplyThemeProps) {
updateCSSVariables();
}, [updateCSSVariables, theme]);
return <Fragment>{children}</Fragment>;
return null;
}
export default ApplyTheme;

View File

@ -1,5 +1,4 @@
import PropTypes from 'prop-types';
import React from 'react';
import React, { useCallback } from 'react';
import Button from 'Components/Link/Button';
import Modal from 'Components/Modal/Modal';
import ModalBody from 'Components/Modal/ModalBody';
@ -10,36 +9,31 @@ import { kinds } from 'Helpers/Props';
import translate from 'Utilities/String/translate';
import styles from './ConnectionLostModal.css';
function ConnectionLostModal(props) {
const {
isOpen,
onModalClose
} = props;
interface ConnectionLostModalProps {
isOpen: boolean;
}
function ConnectionLostModal(props: ConnectionLostModalProps) {
const { isOpen } = props;
const handleModalClose = useCallback(() => {
location.reload();
}, []);
return (
<Modal
isOpen={isOpen}
onModalClose={onModalClose}
>
<ModalContent onModalClose={onModalClose}>
<ModalHeader>
{translate('ConnectionLost')}
</ModalHeader>
<Modal isOpen={isOpen} onModalClose={handleModalClose}>
<ModalContent onModalClose={handleModalClose}>
<ModalHeader>{translate('ConnectionLost')}</ModalHeader>
<ModalBody>
<div>
{translate('ConnectionLostToBackend')}
</div>
<div>{translate('ConnectionLostToBackend')}</div>
<div className={styles.automatic}>
{translate('ConnectionLostReconnect')}
</div>
</ModalBody>
<ModalFooter>
<Button
kind={kinds.PRIMARY}
onPress={onModalClose}
>
<Button kind={kinds.PRIMARY} onPress={handleModalClose}>
{translate('Reload')}
</Button>
</ModalFooter>
@ -48,9 +42,4 @@ function ConnectionLostModal(props) {
);
}
ConnectionLostModal.propTypes = {
isOpen: PropTypes.bool.isRequired,
onModalClose: PropTypes.func.isRequired
};
export default ConnectionLostModal;

View File

@ -1,12 +0,0 @@
import { connect } from 'react-redux';
import ConnectionLostModal from './ConnectionLostModal';
function createMapDispatchToProps(dispatch, props) {
return {
onModalClose() {
location.reload();
}
};
}
export default connect(undefined, createMapDispatchToProps)(ConnectionLostModal);

View File

@ -43,6 +43,13 @@ export interface AppSectionSchemaState<T> {
};
}
export interface AppSectionItemSchemaState<T> {
isSchemaFetching: boolean;
isSchemaPopulated: boolean;
schemaError: Error;
schema: T;
}
export interface AppSectionItemState<T> {
isFetching: boolean;
isPopulated: boolean;

View File

@ -35,20 +35,21 @@ export interface PropertyFilter {
export interface Filter {
key: string;
label: string;
filers: PropertyFilter[];
filters: PropertyFilter[];
}
export interface CustomFilter {
id: number;
type: string;
label: string;
filers: PropertyFilter[];
filters: PropertyFilter[];
}
export interface AppSectionState {
isConnected: boolean;
isReconnecting: boolean;
version: string;
prevVersion?: string;
dimensions: {
isSmallScreen: boolean;
width: number;

View File

@ -1,8 +1,8 @@
import AppSectionState, {
AppSectionDeleteState,
AppSectionItemSchemaState,
AppSectionItemState,
AppSectionSaveState,
AppSectionSchemaState,
PagedAppSectionState,
} from 'App/State/AppSectionState';
import Language from 'Language/Language';
@ -40,7 +40,7 @@ export interface NotificationAppState
export interface QualityProfilesAppState
extends AppSectionState<QualityProfile>,
AppSectionSchemaState<QualityProfile> {}
AppSectionItemSchemaState<QualityProfile> {}
export interface ImportListOptionsSettingsAppState
extends AppSectionItemState<ImportListOptionsSettings>,

View File

@ -1,5 +1,16 @@
import ModelBase from 'App/ModelBase';
export type CommandStatus =
| 'queued'
| 'started'
| 'completed'
| 'failed'
| 'aborted'
| 'cancelled'
| 'orphaned';
export type CommandResult = 'unknown' | 'successful' | 'unsuccessful';
export interface CommandBody {
sendUpdatesToClient: boolean;
updateScheduledTask: boolean;
@ -15,6 +26,7 @@ export interface CommandBody {
seriesId?: number;
seriesIds?: number[];
seasonNumber?: number;
[key: string]: string | number | boolean | undefined | number[] | undefined;
}
interface Command extends ModelBase {
@ -23,8 +35,8 @@ interface Command extends ModelBase {
message: string;
body: CommandBody;
priority: string;
status: string;
result: string;
status: CommandStatus;
result: CommandResult;
queued: string;
started: string;
ended: string;

View File

@ -1,8 +1,8 @@
import PropTypes from 'prop-types';
import React, { Component } from 'react';
import AppUpdatedModalConnector from 'App/AppUpdatedModalConnector';
import AppUpdatedModal from 'App/AppUpdatedModal';
import ColorImpairedContext from 'App/ColorImpairedContext';
import ConnectionLostModalConnector from 'App/ConnectionLostModalConnector';
import ConnectionLostModal from 'App/ConnectionLostModal';
import SignalRConnector from 'Components/SignalRConnector';
import AuthenticationRequiredModal from 'FirstRun/AuthenticationRequiredModal';
import locationShape from 'Helpers/Props/Shapes/locationShape';
@ -101,12 +101,12 @@ class Page extends Component {
{children}
</div>
<AppUpdatedModalConnector
<AppUpdatedModal
isOpen={this.state.isUpdatedModalOpen}
onModalClose={this.onUpdatedModalClose}
/>
<ConnectionLostModalConnector
<ConnectionLostModal
isOpen={this.state.isConnectionLostModalOpen}
onModalClose={this.onConnectionLostModalClose}
/>

View File

@ -1,7 +1,6 @@
import React, { useCallback, useEffect, useMemo, useState } from 'react';
import { useDispatch, useSelector } from 'react-redux';
import { createSelector } from 'reselect';
import { Error } from 'App/State/AppSectionState';
import AppState from 'App/State/AppState';
import Alert from 'Components/Alert';
import Form from 'Components/Form/Form';
@ -21,21 +20,14 @@ import { CheckInputChanged } from 'typings/inputs';
import getQualities from 'Utilities/Quality/getQualities';
import translate from 'Utilities/String/translate';
interface QualitySchemaState {
isFetching: boolean;
isPopulated: boolean;
error: Error;
items: Quality[];
}
function createQualitySchemaSelector() {
return createSelector(
(state: AppState) => state.settings.qualityProfiles,
(qualityProfiles): QualitySchemaState => {
(qualityProfiles) => {
const { isSchemaFetching, isSchemaPopulated, schemaError, schema } =
qualityProfiles;
const items = getQualities(schema.items) as Quality[];
const items = getQualities(schema.items);
return {
isFetching: isSchemaFetching,

View File

@ -2,6 +2,20 @@ import ModelBase from 'App/ModelBase';
import Language from 'Language/Language';
export type SeriesType = 'anime' | 'daily' | 'standard';
export type SeriesMonitor =
| 'all'
| 'future'
| 'missing'
| 'existing'
| 'recent'
| 'pilot'
| 'firstSeason'
| 'lastSeason'
| 'monitorSpecials'
| 'unmonitorSpecials'
| 'none';
export type MonitorNewItems = 'all' | 'none';
export interface Image {
coverType: string;
@ -34,7 +48,15 @@ export interface Ratings {
export interface AlternateTitle {
seasonNumber: number;
sceneSeasonNumber?: number;
title: string;
sceneOrigin: 'unknown' | 'unknown:tvdb' | 'mixed' | 'tvdb';
}
export interface SeriesAddOptions {
monitor: SeriesMonitor;
searchForMissingEpisodes: boolean;
searchForCutoffUnmetEpisodes: boolean;
}
interface Series extends ModelBase {
@ -48,6 +70,7 @@ interface Series extends ModelBase {
images: Image[];
imdbId: string;
monitored: boolean;
monitorNewItems: MonitorNewItems;
network: string;
originalLanguage: Language;
overview: string;
@ -74,6 +97,7 @@ interface Series extends ModelBase {
useSceneNumbering: boolean;
year: number;
isSaving?: boolean;
addOptions: SeriesAddOptions;
}
export default Series;

View File

@ -1,5 +1,5 @@
import pages from 'Utilities/pages';
import serverSideCollectionHandlers from 'Utilities/serverSideCollectionHandlers';
import pages from 'Utilities/State/pages';
import serverSideCollectionHandlers from 'Utilities/State/serverSideCollectionHandlers';
import createFetchServerSideCollectionHandler from './createFetchServerSideCollectionHandler';
import createSetServerSideCollectionFilterHandler from './createSetServerSideCollectionFilterHandler';
import createSetServerSideCollectionPageHandler from './createSetServerSideCollectionPageHandler';

View File

@ -1,5 +1,5 @@
import pages from 'Utilities/pages';
import getSectionState from 'Utilities/State/getSectionState';
import pages from 'Utilities/State/pages';
function createSetServerSideCollectionPageHandler(section, page, fetchHandler) {
return function(getState, payload, dispatch) {

View File

@ -5,7 +5,7 @@ import createServerSideCollectionHandlers from 'Store/Actions/Creators/createSer
import createSetSettingValueReducer from 'Store/Actions/Creators/Reducers/createSetSettingValueReducer';
import createSetTableOptionReducer from 'Store/Actions/Creators/Reducers/createSetTableOptionReducer';
import { createThunk, handleThunks } from 'Store/thunks';
import serverSideCollectionHandlers from 'Utilities/serverSideCollectionHandlers';
import serverSideCollectionHandlers from 'Utilities/State/serverSideCollectionHandlers';
//
// Variables

View File

@ -3,7 +3,7 @@ import { batchActions } from 'redux-batched-actions';
import { filterBuilderTypes, filterBuilderValueTypes, sortDirections } from 'Helpers/Props';
import { createThunk, handleThunks } from 'Store/thunks';
import createAjaxRequest from 'Utilities/createAjaxRequest';
import serverSideCollectionHandlers from 'Utilities/serverSideCollectionHandlers';
import serverSideCollectionHandlers from 'Utilities/State/serverSideCollectionHandlers';
import translate from 'Utilities/String/translate';
import { set, updateItem } from './baseActions';
import createHandleActions from './Creators/createHandleActions';

View File

@ -4,7 +4,7 @@ import Icon from 'Components/Icon';
import { filterBuilderTypes, filterBuilderValueTypes, filterTypes, icons, sortDirections } from 'Helpers/Props';
import { createThunk, handleThunks } from 'Store/thunks';
import createAjaxRequest from 'Utilities/createAjaxRequest';
import serverSideCollectionHandlers from 'Utilities/serverSideCollectionHandlers';
import serverSideCollectionHandlers from 'Utilities/State/serverSideCollectionHandlers';
import translate from 'Utilities/String/translate';
import { updateItem } from './baseActions';
import createHandleActions from './Creators/createHandleActions';

View File

@ -6,7 +6,7 @@ import Icon from 'Components/Icon';
import { filterBuilderTypes, filterBuilderValueTypes, icons, sortDirections } from 'Helpers/Props';
import { createThunk, handleThunks } from 'Store/thunks';
import createAjaxRequest from 'Utilities/createAjaxRequest';
import serverSideCollectionHandlers from 'Utilities/serverSideCollectionHandlers';
import serverSideCollectionHandlers from 'Utilities/State/serverSideCollectionHandlers';
import translate from 'Utilities/String/translate';
import { set, updateItem } from './baseActions';
import createFetchHandler from './Creators/createFetchHandler';

View File

@ -3,7 +3,7 @@ import { filterTypes, sortDirections } from 'Helpers/Props';
import { setAppValue } from 'Store/Actions/appActions';
import { createThunk, handleThunks } from 'Store/thunks';
import createAjaxRequest from 'Utilities/createAjaxRequest';
import serverSideCollectionHandlers from 'Utilities/serverSideCollectionHandlers';
import serverSideCollectionHandlers from 'Utilities/State/serverSideCollectionHandlers';
import translate from 'Utilities/String/translate';
import { pingServer } from './appActions';
import { set } from './baseActions';

View File

@ -1,7 +1,7 @@
import { createAction } from 'redux-actions';
import { filterTypes, sortDirections } from 'Helpers/Props';
import { createThunk, handleThunks } from 'Store/thunks';
import serverSideCollectionHandlers from 'Utilities/serverSideCollectionHandlers';
import serverSideCollectionHandlers from 'Utilities/State/serverSideCollectionHandlers';
import translate from 'Utilities/String/translate';
import createBatchToggleEpisodeMonitoredHandler from './Creators/createBatchToggleEpisodeMonitoredHandler';
import createHandleActions from './Creators/createHandleActions';

View File

@ -4,7 +4,7 @@ import createCommandSelector from './createCommandSelector';
function createCommandExecutingSelector(name: string, contraints = {}) {
return createSelector(createCommandSelector(name, contraints), (command) => {
return isCommandExecuting(command);
return command ? isCommandExecuting(command) : false;
});
}

View File

@ -198,8 +198,6 @@ function Updates() {
{hasUpdates && (
<div>
{items.map((update) => {
const hasChanges = !!update.changes;
return (
<div key={update.version} className={styles.update}>
<div className={styles.info}>
@ -249,7 +247,7 @@ function Updates() {
) : null}
</div>
{hasChanges ? (
{update.changes ? (
<div>
<UpdateChanges
title={translate('New')}

View File

@ -1,11 +0,0 @@
export default function getIndexOfFirstCharacter(items, character) {
return items.findIndex((item) => {
const firstCharacter = item.sortTitle.charAt(0);
if (character === '#') {
return !isNaN(firstCharacter);
}
return firstCharacter === character;
});
}

View File

@ -0,0 +1,18 @@
import Series from 'Series/Series';
const STARTS_WITH_NUMBER_REGEX = /^\d/;
export default function getIndexOfFirstCharacter(
items: Series[],
character: string
) {
return items.findIndex((item) => {
const firstCharacter = item.sortTitle.charAt(0);
if (character === '#') {
return STARTS_WITH_NUMBER_REGEX.test(firstCharacter);
}
return firstCharacter === character;
});
}

View File

@ -1,7 +1,8 @@
import _ from 'lodash';
import Command, { CommandBody } from 'Commands/Command';
import isSameCommand from './isSameCommand';
function findCommand(commands, options) {
function findCommand(commands: Command[], options: Partial<CommandBody>) {
return _.findLast(commands, (command) => {
return isSameCommand(command.body, options);
});

View File

@ -1,9 +0,0 @@
function isCommandComplete(command) {
if (!command) {
return false;
}
return command.status === 'complete';
}
export default isCommandComplete;

View File

@ -0,0 +1,11 @@
import Command from 'Commands/Command';
function isCommandComplete(command: Command) {
if (!command) {
return false;
}
return command.status === 'completed';
}
export default isCommandComplete;

View File

@ -1,4 +1,6 @@
function isCommandExecuting(command) {
import Command from 'Commands/Command';
function isCommandExecuting(command?: Command) {
if (!command) {
return false;
}

View File

@ -1,12 +0,0 @@
function isCommandFailed(command) {
if (!command) {
return false;
}
return command.status === 'failed' ||
command.status === 'aborted' ||
command.status === 'cancelled' ||
command.status === 'orphaned';
}
export default isCommandFailed;

View File

@ -0,0 +1,16 @@
import Command from 'Commands/Command';
function isCommandFailed(command: Command) {
if (!command) {
return false;
}
return (
command.status === 'failed' ||
command.status === 'aborted' ||
command.status === 'cancelled' ||
command.status === 'orphaned'
);
}
export default isCommandFailed;

View File

@ -1,24 +0,0 @@
import _ from 'lodash';
function isSameCommand(commandA, commandB) {
if (commandA.name.toLocaleLowerCase() !== commandB.name.toLocaleLowerCase()) {
return false;
}
for (const key in commandB) {
if (key !== 'name') {
const value = commandB[key];
if (Array.isArray(value)) {
if (_.difference(value, commandA[key]).length > 0) {
return false;
}
} else if (value !== commandA[key]) {
return false;
}
}
}
return true;
}
export default isSameCommand;

View File

@ -0,0 +1,50 @@
import { CommandBody } from 'Commands/Command';
function isSameCommand(
commandA: Partial<CommandBody>,
commandB: Partial<CommandBody>
) {
if (
commandA.name?.toLocaleLowerCase() !== commandB.name?.toLocaleLowerCase()
) {
return false;
}
for (const key in commandB) {
if (key !== 'name') {
const value = commandB[key];
if (Array.isArray(value)) {
const sortedB = [...value].sort((a, b) => a - b);
const commandAProp = commandA[key];
const sortedA = Array.isArray(commandAProp)
? [...commandAProp].sort((a, b) => a - b)
: [];
if (sortedA === sortedB) {
return true;
}
if (sortedA == null || sortedB == null) {
return false;
}
if (sortedA.length !== sortedB.length) {
return false;
}
for (let i = 0; i < sortedB.length; ++i) {
if (sortedB[i] !== sortedA[i]) {
return false;
}
}
} else if (value !== commandA[key]) {
return false;
}
}
}
return true;
}
export default isSameCommand;

View File

@ -1,12 +1,17 @@
import _ from 'lodash';
import Episode from 'Episode/Episode';
import { update } from 'Store/Actions/baseActions';
function updateEpisodes(section, episodes, episodeIds, options) {
const data = _.reduce(episodes, (result, item) => {
function updateEpisodes(
section: string,
episodes: Episode[],
episodeIds: number[],
options: Partial<Episode>
) {
const data = episodes.reduce<Episode[]>((result, item) => {
if (episodeIds.indexOf(item.id) > -1) {
result.push({
...item,
...options
...options,
});
} else {
result.push(item);

View File

@ -1,19 +0,0 @@
export default function findSelectedFilters(selectedFilterKey, filters = [], customFilters = []) {
if (!selectedFilterKey) {
return [];
}
let selectedFilter = filters.find((f) => f.key === selectedFilterKey);
if (!selectedFilter) {
selectedFilter = customFilters.find((f) => f.id === selectedFilterKey);
}
if (!selectedFilter) {
// TODO: throw in dev
console.error('Matching filter not found');
return [];
}
return selectedFilter.filters;
}

View File

@ -0,0 +1,27 @@
import { CustomFilter, Filter } from 'App/State/AppState';
export default function findSelectedFilters(
selectedFilterKey: string | number,
filters: Filter[] = [],
customFilters: CustomFilter[] = []
) {
if (!selectedFilterKey) {
return [];
}
let selectedFilter: Filter | CustomFilter | undefined = filters.find(
(f) => f.key === selectedFilterKey
);
if (!selectedFilter) {
selectedFilter = customFilters.find((f) => f.id === selectedFilterKey);
}
if (!selectedFilter) {
// TODO: throw in dev
console.error('Matching filter not found');
return [];
}
return selectedFilter.filters;
}

View File

@ -1,4 +1,11 @@
export default function getFilterValue(filters, filterKey, filterValueKey, defaultValue) {
import { Filter } from 'App/State/AppState';
export default function getFilterValue(
filters: Filter[],
filterKey: string | number,
filterValueKey: string,
defaultValue: string | number | boolean
) {
const filter = filters.find((f) => f.key === filterKey);
if (!filter) {

View File

@ -1,5 +1,4 @@
function convertToBytes(input, power, binaryPrefix) {
function convertToBytes(input: number, power: number, binaryPrefix: boolean) {
const size = Number(input);
if (isNaN(size)) {

View File

@ -1,19 +0,0 @@
import translate from 'Utilities/String/translate';
function formatAge(age, ageHours, ageMinutes) {
age = Math.round(age);
ageHours = parseFloat(ageHours);
ageMinutes = ageMinutes && parseFloat(ageMinutes);
if (age < 2 && ageHours) {
if (ageHours < 2 && !!ageMinutes) {
return `${ageMinutes.toFixed(0)} ${ageHours === 1 ? translate('FormatAgeMinute') : translate('FormatAgeMinutes')}`;
}
return `${ageHours.toFixed(1)} ${ageHours === 1 ? translate('FormatAgeHour') : translate('FormatAgeHours')}`;
}
return `${age} ${age === 1 ? translate('FormatAgeDay') : translate('FormatAgeDays')}`;
}
export default formatAge;

View File

@ -0,0 +1,33 @@
import translate from 'Utilities/String/translate';
function formatAge(
age: string | number,
ageHours: string | number,
ageMinutes: string | number
) {
const ageRounded = Math.round(Number(age));
const ageHoursFloat = parseFloat(String(ageHours));
const ageMinutesFloat = ageMinutes && parseFloat(String(ageMinutes));
if (ageRounded < 2 && ageHoursFloat) {
if (ageHoursFloat < 2 && !!ageMinutesFloat) {
return `${ageMinutesFloat.toFixed(0)} ${
ageHoursFloat === 1
? translate('FormatAgeMinute')
: translate('FormatAgeMinutes')
}`;
}
return `${ageHoursFloat.toFixed(1)} ${
ageHoursFloat === 1
? translate('FormatAgeHour')
: translate('FormatAgeHours')
}`;
}
return `${ageRounded} ${
ageRounded === 1 ? translate('FormatAgeDay') : translate('FormatAgeDays')
}`;
}
export default formatAge;

View File

@ -1,6 +1,10 @@
import { filesize } from 'filesize';
function formatBytes(input) {
function formatBytes(input?: string | number) {
if (!input) {
return '';
}
const size = Number(input);
if (isNaN(size)) {
@ -9,7 +13,7 @@ function formatBytes(input) {
return `${filesize(size, {
base: 2,
round: 1
round: 1,
})}`;
}

View File

@ -1,10 +0,0 @@
function padNumber(input, width, paddingCharacter = 0) {
if (input == null) {
return '';
}
input = `${input}`;
return input.length >= width ? input : new Array(width - input.length + 1).join(paddingCharacter) + input;
}
export default padNumber;

View File

@ -0,0 +1,13 @@
function padNumber(input: number, width: number, paddingCharacter = '0') {
if (input == null) {
return '';
}
const result = `${input}`;
return result.length >= width
? result
: new Array(width - result.length + 1).join(paddingCharacter) + result;
}
export default padNumber;

View File

@ -1,4 +1,4 @@
export default function roundNumber(input, decimalPlaces = 1) {
export default function roundNumber(input: number, decimalPlaces = 1) {
const multiplier = Math.pow(10, decimalPlaces);
return Math.round(input * multiplier) / multiplier;

View File

@ -1,4 +1,12 @@
function getErrorMessage(xhr, fallbackErrorMessage) {
interface AjaxResponse {
responseJSON:
| {
message: string | undefined;
}
| undefined;
}
function getErrorMessage(xhr: AjaxResponse, fallbackErrorMessage?: string) {
if (!xhr || !xhr.responseJSON || !xhr.responseJSON.message) {
return fallbackErrorMessage;
}

View File

@ -1,15 +0,0 @@
function getRemovedItems(prevItems, currentItems, idProp = 'id') {
if (prevItems === currentItems) {
return [];
}
const currentItemIds = new Set();
currentItems.forEach((currentItem) => {
currentItemIds.add(currentItem[idProp]);
});
return prevItems.filter((prevItem) => !currentItemIds.has(prevItem[idProp]));
}
export default getRemovedItems;

View File

@ -1,4 +1,10 @@
function hasDifferentItems(prevItems, currentItems, idProp = 'id') {
import ModelBase from 'App/ModelBase';
function hasDifferentItems<T extends ModelBase>(
prevItems: T[],
currentItems: T[],
idProp: keyof T = 'id'
) {
if (prevItems === currentItems) {
return false;
}

View File

@ -1,4 +1,10 @@
function hasDifferentItemsOrOrder(prevItems, currentItems, idProp = 'id') {
import ModelBase from 'App/ModelBase';
function hasDifferentItemsOrOrder<T extends ModelBase>(
prevItems: T[],
currentItems: T[],
idProp: keyof T = 'id'
) {
if (prevItems === currentItems) {
return false;
}

View File

@ -1,16 +0,0 @@
export default function getQualities(qualities) {
if (!qualities) {
return [];
}
return qualities.reduce((acc, item) => {
if (item.quality) {
acc.push(item.quality);
} else {
const groupQualities = item.items.map((i) => i.quality);
acc.push(...groupQualities);
}
return acc;
}, []);
}

View File

@ -0,0 +1,26 @@
import Quality from 'Quality/Quality';
import { QualityProfileQualityItem } from 'typings/QualityProfile';
export default function getQualities(qualities?: QualityProfileQualityItem[]) {
if (!qualities) {
return [];
}
return qualities.reduce<Quality[]>((acc, item) => {
if (item.quality) {
acc.push(item.quality);
} else {
const groupQualities = item.items.reduce<Quality[]>((acc, i) => {
if (i.quality) {
acc.push(i.quality);
}
return acc;
}, []);
acc.push(...groupQualities);
}
return acc;
}, []);
}

View File

@ -1,26 +0,0 @@
import $ from 'jquery';
module.exports = {
resolutions: {
desktopLarge: 1200,
desktop: 992,
tablet: 768,
mobile: 480
},
isDesktopLarge() {
return $(window).width() < this.resolutions.desktopLarge;
},
isDesktop() {
return $(window).width() < this.resolutions.desktop;
},
isTablet() {
return $(window).width() < this.resolutions.tablet;
},
isMobile() {
return $(window).width() < this.resolutions.mobile;
}
};

View File

@ -0,0 +1,24 @@
module.exports = {
resolutions: {
desktopLarge: 1200,
desktop: 992,
tablet: 768,
mobile: 480,
},
isDesktopLarge() {
return window.innerWidth < this.resolutions.desktopLarge;
},
isDesktop() {
return window.innerWidth < this.resolutions.desktop;
},
isTablet() {
return window.innerWidth < this.resolutions.tablet;
},
isMobile() {
return window.innerWidth < this.resolutions.mobile;
},
};

View File

@ -1,53 +0,0 @@
function filterAlternateTitles(alternateTitles, seriesTitle, useSceneNumbering, seasonNumber, sceneSeasonNumber) {
const globalTitles = [];
const seasonTitles = [];
if (alternateTitles) {
alternateTitles.forEach((alternateTitle) => {
if (alternateTitle.sceneOrigin === 'unknown' || alternateTitle.sceneOrigin === 'unknown:tvdb') {
return;
}
if (alternateTitle.sceneOrigin === 'mixed') {
// For now filter out 'mixed' from the UI, the user will get an rejection during manual search.
return;
}
const hasAltSeasonNumber = (alternateTitle.seasonNumber !== -1 && alternateTitle.seasonNumber !== undefined);
const hasAltSceneSeasonNumber = (alternateTitle.sceneSeasonNumber !== -1 && alternateTitle.sceneSeasonNumber !== undefined);
// Global alias that should be displayed global
if (!hasAltSeasonNumber && !hasAltSceneSeasonNumber &&
(alternateTitle.title !== seriesTitle) &&
(!alternateTitle.sceneOrigin || !useSceneNumbering)) {
globalTitles.push(alternateTitle);
return;
}
// Global alias that should be displayed per episode
if (!hasAltSeasonNumber && !hasAltSceneSeasonNumber && alternateTitle.sceneOrigin && useSceneNumbering) {
seasonTitles.push(alternateTitle);
return;
}
// Apply the alternative mapping (release to scene)
const mappedAltSeasonNumber = hasAltSeasonNumber ? alternateTitle.seasonNumber : alternateTitle.sceneSeasonNumber;
// Select scene or tvdb on the episode
const mappedSeasonNumber = alternateTitle.sceneOrigin === 'tvdb' ? seasonNumber : sceneSeasonNumber;
if (mappedSeasonNumber !== undefined && mappedSeasonNumber === mappedAltSeasonNumber) {
seasonTitles.push(alternateTitle);
return;
}
});
}
if (seasonNumber === undefined) {
return globalTitles;
}
return seasonTitles;
}
export default filterAlternateTitles;

View File

@ -0,0 +1,83 @@
import { AlternateTitle } from 'Series/Series';
function filterAlternateTitles(
alternateTitles: AlternateTitle[],
seriesTitle: string | null,
useSceneNumbering: boolean,
seasonNumber?: number,
sceneSeasonNumber?: number
) {
const globalTitles: AlternateTitle[] = [];
const seasonTitles: AlternateTitle[] = [];
if (alternateTitles) {
alternateTitles.forEach((alternateTitle) => {
if (
alternateTitle.sceneOrigin === 'unknown' ||
alternateTitle.sceneOrigin === 'unknown:tvdb'
) {
return;
}
if (alternateTitle.sceneOrigin === 'mixed') {
// For now filter out 'mixed' from the UI, the user will get an rejection during manual search.
return;
}
const hasAltSeasonNumber =
alternateTitle.seasonNumber !== -1 &&
alternateTitle.seasonNumber !== undefined;
const hasAltSceneSeasonNumber =
alternateTitle.sceneSeasonNumber !== -1 &&
alternateTitle.sceneSeasonNumber !== undefined;
// Global alias that should be displayed global
if (
!hasAltSeasonNumber &&
!hasAltSceneSeasonNumber &&
alternateTitle.title !== seriesTitle &&
(!alternateTitle.sceneOrigin || !useSceneNumbering)
) {
globalTitles.push(alternateTitle);
return;
}
// Global alias that should be displayed per episode
if (
!hasAltSeasonNumber &&
!hasAltSceneSeasonNumber &&
alternateTitle.sceneOrigin &&
useSceneNumbering
) {
seasonTitles.push(alternateTitle);
return;
}
// Apply the alternative mapping (release to scene)
const mappedAltSeasonNumber = hasAltSeasonNumber
? alternateTitle.seasonNumber
: alternateTitle.sceneSeasonNumber;
// Select scene or tvdb on the episode
const mappedSeasonNumber =
alternateTitle.sceneOrigin === 'tvdb'
? seasonNumber
: sceneSeasonNumber;
if (
mappedSeasonNumber !== undefined &&
mappedSeasonNumber === mappedAltSeasonNumber
) {
seasonTitles.push(alternateTitle);
return;
}
});
}
if (seasonNumber === undefined) {
return globalTitles;
}
return seasonTitles;
}
export default filterAlternateTitles;

View File

@ -1,5 +1,22 @@
import Series, {
MonitorNewItems,
SeriesMonitor,
SeriesType,
} from 'Series/Series';
function getNewSeries(series, payload) {
interface NewSeriesPayload {
rootFolderPath: string;
monitor: SeriesMonitor;
monitorNewItems: MonitorNewItems;
qualityProfileId: number;
seriesType: SeriesType;
seasonFolder: boolean;
tags: number[];
searchForMissingEpisodes?: boolean;
searchForCutoffUnmetEpisodes?: boolean;
}
function getNewSeries(series: Series, payload: NewSeriesPayload) {
const {
rootFolderPath,
monitor,
@ -9,13 +26,13 @@ function getNewSeries(series, payload) {
seasonFolder,
tags,
searchForMissingEpisodes = false,
searchForCutoffUnmetEpisodes = false
searchForCutoffUnmetEpisodes = false,
} = payload;
const addOptions = {
monitor,
searchForMissingEpisodes,
searchForCutoffUnmetEpisodes
searchForCutoffUnmetEpisodes,
};
series.addOptions = addOptions;

View File

@ -5,14 +5,14 @@ const monitorNewItemsOptions = [
key: 'all',
get value() {
return translate('MonitorAllSeasons');
}
},
},
{
key: 'none',
get value() {
return translate('MonitorNoNewSeasons');
}
}
},
},
];
export default monitorNewItemsOptions;

View File

@ -5,68 +5,68 @@ const monitorOptions = [
key: 'all',
get value() {
return translate('MonitorAllEpisodes');
}
},
},
{
key: 'future',
get value() {
return translate('MonitorFutureEpisodes');
}
},
},
{
key: 'missing',
get value() {
return translate('MonitorMissingEpisodes');
}
},
},
{
key: 'existing',
get value() {
return translate('MonitorExistingEpisodes');
}
},
},
{
key: 'recent',
get value() {
return translate('MonitorRecentEpisodes');
}
},
},
{
key: 'pilot',
get value() {
return translate('MonitorPilotEpisode');
}
},
},
{
key: 'firstSeason',
get value() {
return translate('MonitorFirstSeason');
}
},
},
{
key: 'lastSeason',
get value() {
return translate('MonitorLastSeason');
}
},
},
{
key: 'monitorSpecials',
get value() {
return translate('MonitorSpecialEpisodes');
}
},
},
{
key: 'unmonitorSpecials',
get value() {
return translate('UnmonitorSpecialEpisodes');
}
},
},
{
key: 'none',
get value() {
return translate('MonitorNoEpisodes');
}
}
},
},
];
export default monitorOptions;

View File

@ -1,5 +0,0 @@
function getNextId(items) {
return items.reduce((id, x) => Math.max(id, x.id), 1) + 1;
}
export default getNextId;

View File

@ -0,0 +1,7 @@
import ModelBase from 'App/ModelBase';
function getNextId<T extends ModelBase>(items: T[]) {
return items.reduce((id, x) => Math.max(id, x.id), 1) + 1;
}
export default getNextId;

View File

@ -1,5 +0,0 @@
export default function combinePath(isWindows, basePath, paths = []) {
const slash = isWindows ? '\\' : '/';
return `${basePath}${slash}${paths.join(slash)}`;
}

View File

@ -0,0 +1,9 @@
export default function combinePath(
isWindows: boolean,
basePath: string,
paths: string[] = []
) {
const slash = isWindows ? '\\' : '/';
return `${basePath}${slash}${paths.join(slash)}`;
}

View File

@ -1,6 +0,0 @@
export default function generateUUIDv4() {
return ([1e7]+-1e3+-4e3+-8e3+-1e11).replace(/[018]/g, (c) =>
// eslint-disable-next-line no-bitwise
(c ^ crypto.getRandomValues(new Uint8Array(1))[0] & 15 >> c / 4).toString(16)
);
}

View File

@ -1,3 +1,3 @@
export default function isString(possibleString) {
export default function isString(possibleString: unknown) {
return typeof possibleString === 'string' || possibleString instanceof String;
}

View File

@ -1,6 +1,6 @@
const regex = /\d+/g;
function naturalExpansion(input) {
function naturalExpansion(input: string) {
if (!input) {
return '';
}

View File

@ -4,13 +4,13 @@ import qs from 'qs';
// See: https://developer.mozilla.org/en-US/docs/Web/API/HTMLHyperlinkElementUtils
const anchor = document.createElement('a');
export default function parseUrl(url) {
export default function parseUrl(url: string) {
anchor.href = url;
// The `origin`, `password`, and `username` properties are unavailable in
// Opera Presto. We synthesize `origin` if it's not present. While `password`
// and `username` are ignored intentionally.
const properties = _.pick(
const properties: Record<string, string | number | boolean | object> = _.pick(
anchor,
'hash',
'host',
@ -23,11 +23,11 @@ export default function parseUrl(url) {
'search'
);
properties.isAbsolute = (/^[\w:]*\/\//).test(url);
properties.isAbsolute = /^[\w:]*\/\//.test(url);
if (properties.search) {
// Remove leading ? from querystring before parsing.
properties.params = qs.parse(properties.search.substring(1));
properties.params = qs.parse((properties.search as string).substring(1));
} else {
properties.params = {};
}

View File

@ -1,17 +0,0 @@
import _ from 'lodash';
function split(input, separator = ',') {
if (!input) {
return [];
}
return _.reduce(input.split(separator), (result, s) => {
if (s) {
result.push(s);
}
return result;
}, []);
}
export default split;

View File

@ -0,0 +1,15 @@
function split(input: string, separator = ',') {
if (!input) {
return [];
}
return input.split(separator).reduce<string[]>((acc, s) => {
if (s) {
acc.push(s);
}
return acc;
}, []);
}
export default split;

View File

@ -1,6 +1,6 @@
const regex = /\b\w+/g;
function titleCase(input) {
function titleCase(input: string | undefined) {
if (!input) {
return '';
}

View File

@ -1,17 +0,0 @@
export default function areAllSelected(selectedState) {
let allSelected = true;
let allUnselected = true;
Object.keys(selectedState).forEach((key) => {
if (selectedState[key]) {
allUnselected = false;
} else {
allSelected = false;
}
});
return {
allSelected,
allUnselected
};
}

View File

@ -0,0 +1,19 @@
import { SelectedState } from 'Helpers/Hooks/useSelectState';
export default function areAllSelected(selectedState: SelectedState) {
let allSelected = true;
let allUnselected = true;
Object.values(selectedState).forEach((value) => {
if (value) {
allUnselected = false;
} else {
allSelected = false;
}
});
return {
allSelected,
allUnselected,
};
}

View File

@ -1,23 +0,0 @@
import _ from 'lodash';
function getToggledRange(items, id, lastToggled) {
const lastToggledIndex = _.findIndex(items, { id: lastToggled });
const changedIndex = _.findIndex(items, { id });
let lower = 0;
let upper = 0;
if (lastToggledIndex > changedIndex) {
lower = changedIndex;
upper = lastToggledIndex + 1;
} else {
lower = lastToggledIndex;
upper = changedIndex;
}
return {
lower,
upper
};
}
export default getToggledRange;

View File

@ -0,0 +1,27 @@
import ModelBase from 'App/ModelBase';
function getToggledRange<T extends ModelBase>(
items: T[],
id: number,
lastToggled: number
) {
const lastToggledIndex = items.findIndex((item) => item.id === lastToggled);
const changedIndex = items.findIndex((item) => item.id === id);
let lower = 0;
let upper = 0;
if (lastToggledIndex > changedIndex) {
lower = changedIndex;
upper = lastToggledIndex + 1;
} else {
lower = lastToggledIndex;
upper = changedIndex;
}
return {
lower,
upper,
};
}
export default getToggledRange;

View File

@ -1,16 +0,0 @@
import areAllSelected from './areAllSelected';
export default function removeOldSelectedState(state, prevItems) {
const selectedState = {
...state.selectedState
};
prevItems.forEach((item) => {
delete selectedState[item.id];
});
return {
...areAllSelected(selectedState),
selectedState
};
}

View File

@ -0,0 +1,21 @@
import ModelBase from 'App/ModelBase';
import { SelectState } from 'Helpers/Hooks/useSelectState';
import areAllSelected from './areAllSelected';
export default function removeOldSelectedState<T extends ModelBase>(
state: SelectState,
prevItems: T[]
) {
const selectedState = {
...state.selectedState,
};
prevItems.forEach((item) => {
delete selectedState[item.id];
});
return {
...areAllSelected(selectedState),
selectedState,
};
}

View File

@ -1,17 +0,0 @@
import _ from 'lodash';
function selectAll(selectedState, selected) {
const newSelectedState = _.reduce(Object.keys(selectedState), (result, item) => {
result[item] = selected;
return result;
}, {});
return {
allSelected: selected,
allUnselected: !selected,
lastToggled: null,
selectedState: newSelectedState
};
}
export default selectAll;

View File

@ -0,0 +1,19 @@
import { SelectedState } from 'Helpers/Hooks/useSelectState';
function selectAll(selectedState: SelectedState, selected: boolean) {
const newSelectedState = Object.keys(selectedState).reduce<
Record<number, boolean>
>((acc, item) => {
acc[Number(item)] = selected;
return acc;
}, {});
return {
allSelected: selected,
allUnselected: !selected,
lastToggled: null,
selectedState: newSelectedState,
};
}
export default selectAll;

View File

@ -1,11 +1,19 @@
import ModelBase from 'App/ModelBase';
import { SelectState } from 'Helpers/Hooks/useSelectState';
import areAllSelected from './areAllSelected';
import getToggledRange from './getToggledRange';
function toggleSelected(selectedState, items, id, selected, shiftKey) {
const lastToggled = selectedState.lastToggled;
function toggleSelected<T extends ModelBase>(
selectState: SelectState,
items: T[],
id: number,
selected: boolean,
shiftKey: boolean
) {
const lastToggled = selectState.lastToggled;
const nextSelectedState = {
...selectedState.selectedState,
[id]: selected
...selectState.selectedState,
[id]: selected,
};
if (selected == null) {
@ -23,7 +31,7 @@ function toggleSelected(selectedState, items, id, selected, shiftKey) {
return {
...areAllSelected(nextSelectedState),
lastToggled: id,
selectedState: nextSelectedState
selectedState: nextSelectedState,
};
}

View File

@ -3,7 +3,6 @@ import MobileDetect from 'mobile-detect';
const mobileDetect = new MobileDetect(window.navigator.userAgent);
export function isMobile() {
return mobileDetect.mobile() != null;
}

View File

@ -1,3 +0,0 @@
export default function getPathWithUrlBase(path) {
return `${window.Sonarr.urlBase}${path}`;
}

View File

@ -0,0 +1,3 @@
export default function getPathWithUrlBase(path: string) {
return `${window.Sonarr.urlBase}${path}`;
}

View File

@ -1,19 +1,24 @@
let currentPopulator = null;
let currentReasons = [];
type Populator = () => void;
export function registerPagePopulator(populator, reasons = []) {
let currentPopulator: Populator | null = null;
let currentReasons: string[] = [];
export function registerPagePopulator(
populator: Populator,
reasons: string[] = []
) {
currentPopulator = populator;
currentReasons = reasons;
}
export function unregisterPagePopulator(populator) {
export function unregisterPagePopulator(populator: Populator) {
if (currentPopulator === populator) {
currentPopulator = null;
currentReasons = [];
}
}
export function repopulatePage(reason) {
export function repopulatePage(reason: string) {
if (!currentPopulator) {
return;
}

View File

@ -1,18 +1,17 @@
import $ from 'jquery';
import _ from 'lodash';
import createAjaxRequest from './createAjaxRequest';
function flattenProviderData(providerData) {
return _.reduce(Object.keys(providerData), (result, key) => {
return Object.keys(providerData).reduce((acc, key) => {
const property = providerData[key];
if (key === 'fields') {
result[key] = property;
acc[key] = property;
} else {
result[key] = property.value;
acc[key] = property.value;
}
return result;
return acc;
}, {});
}

View File

@ -8,6 +8,6 @@ export function isLocked() {
return scrollLock;
}
export function setScrollLock(locked) {
export function setScrollLock(locked: boolean) {
scrollLock = locked;
}

View File

@ -1,6 +0,0 @@
const sectionTypes = {
COLLECTION: 'collection',
MODEL: 'model'
};
export default sectionTypes;

View File

@ -13,7 +13,7 @@ interface Update {
installedOn: string;
installable: boolean;
latest: boolean;
changes: Changes;
changes: Changes | null;
hash: string;
}

View File

@ -92,6 +92,8 @@
"@babel/preset-react": "7.24.1",
"@babel/preset-typescript": "7.24.1",
"@types/lodash": "4.14.194",
"@types/qs": "6.9.15",
"@types/react-document-title": "2.0.9",
"@types/react-lazyload": "3.2.0",
"@types/react-router-dom": "5.3.3",
"@types/react-text-truncate": "0.14.1",

View File

@ -1458,6 +1458,18 @@
resolved "https://registry.yarnpkg.com/@types/prop-types/-/prop-types-15.7.12.tgz#12bb1e2be27293c1406acb6af1c3f3a1481d98c6"
integrity sha512-5zvhXYtRNRluoE/jAp4GVsSduVUzNWKkOZrCDBWYtE7biZywwdC2AcEzg+cSMLFRfVgeAFqpfNabiPjxFddV1Q==
"@types/qs@6.9.15":
version "6.9.15"
resolved "https://registry.yarnpkg.com/@types/qs/-/qs-6.9.15.tgz#adde8a060ec9c305a82de1babc1056e73bd64dce"
integrity sha512-uXHQKES6DQKKCLh441Xv/dwxOq1TVS3JPUMlEqoEglvlhR6Mxnlew/Xq/LRVHpLyk7iK3zODe1qYHIMltO7XGg==
"@types/react-document-title@2.0.9":
version "2.0.9"
resolved "https://registry.yarnpkg.com/@types/react-document-title/-/react-document-title-2.0.9.tgz#65fd57e6086ef8ced5ad45ac8a439dd878ca71d6"
integrity sha512-Q8bSnESgyVoMCo0vAKJj2N4wD/yl7EnutaFntKpaL/edUUo4kTNH8M6A5iCoje9sknRdLx7cfB39cpdTNr5Z+Q==
dependencies:
"@types/react" "*"
"@types/react-dom@18.2.25":
version "18.2.25"
resolved "https://registry.yarnpkg.com/@types/react-dom/-/react-dom-18.2.25.tgz#2946a30081f53e7c8d585eb138277245caedc521"