diff --git a/.devcontainer/Sonarr.code-workspace b/.devcontainer/Sonarr.code-workspace new file mode 100644 index 000000000..a46158e44 --- /dev/null +++ b/.devcontainer/Sonarr.code-workspace @@ -0,0 +1,13 @@ +// This file is used to open the backend and frontend in the same workspace, which is necessary as +// the frontend has vscode settings that are distinct from the backend +{ + "folders": [ + { + "path": ".." + }, + { + "path": "../frontend" + } + ], + "settings": {} +} diff --git a/.devcontainer/devcontainer.json b/.devcontainer/devcontainer.json new file mode 100644 index 000000000..629a2aa21 --- /dev/null +++ b/.devcontainer/devcontainer.json @@ -0,0 +1,19 @@ +// For format details, see https://aka.ms/devcontainer.json. For config options, see the +// README at: https://github.com/devcontainers/templates/tree/main/src/dotnet +{ + "name": "Sonarr", + "image": "mcr.microsoft.com/devcontainers/dotnet:1-6.0", + "features": { + "ghcr.io/devcontainers/features/node:1": { + "nodeGypDependencies": true, + "version": "16", + "nvmVersion": "latest" + } + }, + "forwardPorts": [8989], + "customizations": { + "vscode": { + "extensions": ["esbenp.prettier-vscode"] + } + } +} diff --git a/.editorconfig b/.editorconfig index dad58944a..6d6c3a13f 100644 --- a/.editorconfig +++ b/.editorconfig @@ -2,14 +2,274 @@ # editorconfig.org root = true -[*.{cs,html,js,hbs}] +# NOTE: Requires **VS2019 16.3** or later + +# Stylecop.ruleset +# Description: Rules for Sonarr + +# Code files +[*.cs] charset = utf-8 trim_trailing_whitespace = true insert_final_newline = true indent_style = space indent_size = 4 -[*.less] +# Sort using and Import directives with System.* appearing first +dotnet_sort_system_directives_first = true + +# Avoid "this." and "Me." if not necessary +dotnet_style_qualification_for_field = false:refactoring +dotnet_style_qualification_for_property = false:refactoring +dotnet_style_qualification_for_method = false:refactoring +dotnet_style_qualification_for_event = false:refactoring + +# Indentation preferences +csharp_indent_block_contents = true +csharp_indent_braces = false +csharp_indent_case_contents = true +csharp_indent_case_contents_when_block = true +csharp_indent_switch_labels = true +csharp_indent_labels = flush_left + +dotnet_style_qualification_for_field = false:suggestion +dotnet_style_qualification_for_property = false:suggestion +dotnet_style_qualification_for_method = false:suggestion +dotnet_style_qualification_for_event = false:suggestion +dotnet_naming_style.instance_field_style.capitalization = camel_case +dotnet_naming_style.instance_field_style.required_prefix = _ + +# Prefer "var" everywhere +csharp_style_var_for_built_in_types = true +csharp_style_var_when_type_is_apparent = true +csharp_style_var_elsewhere = true +# Prefer "out" variables to be declared inline +csharp_style_inlined_variable_declaration = true + +# Using directive is unnecessary. +dotnet_diagnostic.IDE0005.severity = error +# Use var instead of explicit type +dotnet_diagnostic.IDE0007.severity = error +# Inline variable declaration +dotnet_diagnostic.IDE0018.severity = error + +# Stylecop Rules +dotnet_diagnostic.SA0001.severity = none +dotnet_diagnostic.SA1025.severity = none +dotnet_diagnostic.SA1101.severity = none +dotnet_diagnostic.SA1116.severity = none +dotnet_diagnostic.SA1118.severity = none +dotnet_diagnostic.SA1122.severity = none +dotnet_diagnostic.SA1201.severity = suggestion +dotnet_diagnostic.SA1202.severity = suggestion +dotnet_diagnostic.SA1204.severity = suggestion +dotnet_diagnostic.SA1300.severity = none +dotnet_diagnostic.SA1303.severity = none +dotnet_diagnostic.SA1304.severity = none +dotnet_diagnostic.SA1306.severity = none +dotnet_diagnostic.SA1309.severity = none +dotnet_diagnostic.SA1310.severity = none +dotnet_diagnostic.SA1401.severity = none +dotnet_diagnostic.SA1402.severity = none +dotnet_diagnostic.SA1404.severity = suggestion +dotnet_diagnostic.SA1405.severity = suggestion +dotnet_diagnostic.SA1406.severity = suggestion +dotnet_diagnostic.SA1410.severity = suggestion +dotnet_diagnostic.SA1411.severity = suggestion +dotnet_diagnostic.SA1413.severity = none +dotnet_diagnostic.SA1512.severity = none +dotnet_diagnostic.SA1516.severity = none +dotnet_diagnostic.SA1600.severity = none +dotnet_diagnostic.SA1601.severity = none +dotnet_diagnostic.SA1602.severity = none +dotnet_diagnostic.SA1604.severity = none +dotnet_diagnostic.SA1605.severity = none +dotnet_diagnostic.SA1606.severity = none +dotnet_diagnostic.SA1607.severity = none +dotnet_diagnostic.SA1608.severity = none +dotnet_diagnostic.SA1610.severity = none +dotnet_diagnostic.SA1611.severity = none +dotnet_diagnostic.SA1612.severity = none +dotnet_diagnostic.SA1613.severity = none +dotnet_diagnostic.SA1614.severity = none +dotnet_diagnostic.SA1615.severity = none +dotnet_diagnostic.SA1616.severity = none +dotnet_diagnostic.SA1617.severity = none +dotnet_diagnostic.SA1618.severity = none +dotnet_diagnostic.SA1619.severity = none +dotnet_diagnostic.SA1620.severity = none +dotnet_diagnostic.SA1621.severity = none +dotnet_diagnostic.SA1622.severity = none +dotnet_diagnostic.SA1623.severity = none +dotnet_diagnostic.SA1624.severity = none +dotnet_diagnostic.SA1625.severity = none +dotnet_diagnostic.SA1626.severity = none +dotnet_diagnostic.SA1627.severity = none +dotnet_diagnostic.SA1629.severity = none +dotnet_diagnostic.SA1633.severity = none +dotnet_diagnostic.SA1634.severity = none +dotnet_diagnostic.SA1635.severity = none +dotnet_diagnostic.SA1636.severity = none +dotnet_diagnostic.SA1637.severity = none +dotnet_diagnostic.SA1638.severity = none +dotnet_diagnostic.SA1640.severity = none +dotnet_diagnostic.SA1641.severity = none +dotnet_diagnostic.SA1642.severity = none +dotnet_diagnostic.SA1643.severity = none +dotnet_diagnostic.SA1648.severity = none +dotnet_diagnostic.SA1649.severity = none +dotnet_diagnostic.SA1651.severity = none +dotnet_diagnostic.SX1309.severity = warning + +# Microsoft Analyzers that fail and need to be sorted thru +dotnet_diagnostic.ASP0000.severity = suggestion +dotnet_diagnostic.CA1000.severity = suggestion +dotnet_diagnostic.CA1001.severity = suggestion +dotnet_diagnostic.CA1002.severity = suggestion +dotnet_diagnostic.CA1003.severity = suggestion +dotnet_diagnostic.CA1008.severity = suggestion +dotnet_diagnostic.CA1010.severity = suggestion +dotnet_diagnostic.CA1012.severity = suggestion +dotnet_diagnostic.CA1014.severity = suggestion +dotnet_diagnostic.CA1016.severity = suggestion +dotnet_diagnostic.CA1017.severity = suggestion +dotnet_diagnostic.CA1018.severity = suggestion +dotnet_diagnostic.CA1019.severity = suggestion +dotnet_diagnostic.CA1021.severity = suggestion +dotnet_diagnostic.CA1024.severity = suggestion +dotnet_diagnostic.CA1027.severity = suggestion +dotnet_diagnostic.CA1028.severity = suggestion +dotnet_diagnostic.CA1030.severity = suggestion +dotnet_diagnostic.CA1031.severity = suggestion +dotnet_diagnostic.CA1032.severity = suggestion +dotnet_diagnostic.CA1033.severity = suggestion +dotnet_diagnostic.CA1034.severity = suggestion +dotnet_diagnostic.CA1036.severity = suggestion +dotnet_diagnostic.CA1040.severity = suggestion +dotnet_diagnostic.CA1041.severity = suggestion +dotnet_diagnostic.CA1043.severity = suggestion +dotnet_diagnostic.CA1044.severity = suggestion +dotnet_diagnostic.CA1050.severity = suggestion +dotnet_diagnostic.CA1051.severity = suggestion +dotnet_diagnostic.CA1052.severity = suggestion +dotnet_diagnostic.CA1054.severity = suggestion +dotnet_diagnostic.CA1055.severity = suggestion +dotnet_diagnostic.CA1056.severity = suggestion +dotnet_diagnostic.CA1058.severity = suggestion +dotnet_diagnostic.CA1060.severity = suggestion +dotnet_diagnostic.CA1061.severity = suggestion +dotnet_diagnostic.CA1062.severity = suggestion +dotnet_diagnostic.CA1063.severity = suggestion +dotnet_diagnostic.CA1064.severity = suggestion +dotnet_diagnostic.CA1065.severity = suggestion +dotnet_diagnostic.CA1066.severity = suggestion +dotnet_diagnostic.CA1067.severity = suggestion +dotnet_diagnostic.CA1068.severity = suggestion +dotnet_diagnostic.CA1069.severity = suggestion +dotnet_diagnostic.CA1200.severity = suggestion +dotnet_diagnostic.CA1303.severity = suggestion +dotnet_diagnostic.CA1304.severity = suggestion +dotnet_diagnostic.CA1305.severity = suggestion +dotnet_diagnostic.CA1307.severity = suggestion +dotnet_diagnostic.CA1308.severity = suggestion +dotnet_diagnostic.CA1309.severity = suggestion +dotnet_diagnostic.CA1310.severity = suggestion +dotnet_diagnostic.CA1401.severity = suggestion +dotnet_diagnostic.CA1416.severity = suggestion +dotnet_diagnostic.CA1419.severity = suggestion +dotnet_diagnostic.CA1507.severity = suggestion +dotnet_diagnostic.CA1508.severity = suggestion +dotnet_diagnostic.CA1707.severity = suggestion +dotnet_diagnostic.CA1708.severity = suggestion +dotnet_diagnostic.CA1710.severity = suggestion +dotnet_diagnostic.CA1711.severity = suggestion +dotnet_diagnostic.CA1712.severity = suggestion +dotnet_diagnostic.CA1714.severity = suggestion +dotnet_diagnostic.CA1715.severity = suggestion +dotnet_diagnostic.CA1716.severity = suggestion +dotnet_diagnostic.CA1717.severity = suggestion +dotnet_diagnostic.CA1720.severity = suggestion +dotnet_diagnostic.CA1721.severity = suggestion +dotnet_diagnostic.CA1724.severity = suggestion +dotnet_diagnostic.CA1725.severity = suggestion +dotnet_diagnostic.CA1806.severity = suggestion +dotnet_diagnostic.CA1810.severity = suggestion +dotnet_diagnostic.CA1812.severity = suggestion +dotnet_diagnostic.CA1813.severity = suggestion +dotnet_diagnostic.CA1814.severity = suggestion +dotnet_diagnostic.CA1815.severity = suggestion +dotnet_diagnostic.CA1816.severity = suggestion +dotnet_diagnostic.CA1819.severity = suggestion +dotnet_diagnostic.CA1822.severity = suggestion +dotnet_diagnostic.CA1823.severity = suggestion +dotnet_diagnostic.CA1824.severity = suggestion +dotnet_diagnostic.CA1825.severity = suggestion +dotnet_diagnostic.CA2000.severity = suggestion +dotnet_diagnostic.CA2002.severity = suggestion +dotnet_diagnostic.CA2007.severity = suggestion +dotnet_diagnostic.CA2008.severity = suggestion +dotnet_diagnostic.CA2012.severity = suggestion +dotnet_diagnostic.CA2013.severity = suggestion +dotnet_diagnostic.CA2100.severity = suggestion +dotnet_diagnostic.CA2101.severity = suggestion +dotnet_diagnostic.CA2119.severity = suggestion +dotnet_diagnostic.CA2153.severity = suggestion +dotnet_diagnostic.CA2200.severity = suggestion +dotnet_diagnostic.CA2201.severity = suggestion +dotnet_diagnostic.CA2207.severity = suggestion +dotnet_diagnostic.CA2208.severity = suggestion +dotnet_diagnostic.CA2211.severity = suggestion +dotnet_diagnostic.CA2213.severity = suggestion +dotnet_diagnostic.CA2214.severity = suggestion +dotnet_diagnostic.CA2215.severity = suggestion +dotnet_diagnostic.CA2216.severity = suggestion +dotnet_diagnostic.CA2219.severity = suggestion +dotnet_diagnostic.CA2225.severity = suggestion +dotnet_diagnostic.CA2226.severity = suggestion +dotnet_diagnostic.CA2227.severity = suggestion +dotnet_diagnostic.CA2229.severity = suggestion +dotnet_diagnostic.CA2231.severity = suggestion +dotnet_diagnostic.CA2234.severity = suggestion +dotnet_diagnostic.CA2235.severity = suggestion +dotnet_diagnostic.CA2237.severity = suggestion +dotnet_diagnostic.CA2241.severity = suggestion +dotnet_diagnostic.CA2242.severity = suggestion +dotnet_diagnostic.CA2243.severity = suggestion +dotnet_diagnostic.CA2244.severity = suggestion +dotnet_diagnostic.CA2245.severity = suggestion +dotnet_diagnostic.CA2246.severity = suggestion +dotnet_diagnostic.CA2249.severity = suggestion +dotnet_diagnostic.CA2251.severity = suggestion +dotnet_diagnostic.CA3061.severity = suggestion +dotnet_diagnostic.CA3075.severity = suggestion +dotnet_diagnostic.CA3076.severity = suggestion +dotnet_diagnostic.CA3077.severity = suggestion +dotnet_diagnostic.CA3147.severity = suggestion +dotnet_diagnostic.CA5350.severity = suggestion +dotnet_diagnostic.CA5351.severity = suggestion +dotnet_diagnostic.CA5359.severity = suggestion +dotnet_diagnostic.CA5360.severity = suggestion +dotnet_diagnostic.CA5363.severity = suggestion +dotnet_diagnostic.CA5364.severity = suggestion +dotnet_diagnostic.CA5365.severity = suggestion +dotnet_diagnostic.CA5366.severity = suggestion +dotnet_diagnostic.CA5368.severity = suggestion +dotnet_diagnostic.CA5369.severity = suggestion +dotnet_diagnostic.CA5370.severity = suggestion +dotnet_diagnostic.CA5371.severity = suggestion +dotnet_diagnostic.CA5372.severity = suggestion +dotnet_diagnostic.CA5373.severity = suggestion +dotnet_diagnostic.CA5374.severity = suggestion +dotnet_diagnostic.CA5379.severity = suggestion +dotnet_diagnostic.CA5384.severity = suggestion +dotnet_diagnostic.CA5385.severity = suggestion +dotnet_diagnostic.CA5392.severity = suggestion +dotnet_diagnostic.CA5394.severity = suggestion +dotnet_diagnostic.CA5397.severity = suggestion + +dotnet_diagnostic.SYSLIB0006.severity = none + +[*.{js,html,hbs,less,css,ts,tsx}] charset = utf-8 trim_trailing_whitespace = true insert_final_newline = true diff --git a/.gitattributes b/.gitattributes index 1b274cb93..f3e639368 100644 --- a/.gitattributes +++ b/.gitattributes @@ -1,22 +1,12 @@ # Auto detect text files and perform LF normalization -*text eol=lf +* text=auto + +# Explicitly set bash scripts to have unix endings +# when checked out on windows +*.sh text eol=lf +distribution/debian/* text eol=lf +distribution/osx/Sonarr text eol=lf # Custom for Visual Studio *.cs diff=csharp *.sln merge=union -*.csproj merge=union -*.vbproj merge=union -*.fsproj merge=union -*.dbproj merge=union - -# Standard to msysgit -*.doc diff=astextplain -*.DOC diff=astextplain -*.docx diff=astextplain -*.DOCX diff=astextplain -*.dot diff=astextplain -*.DOT diff=astextplain -*.pdf diff=astextplain -*.PDF diff=astextplain -*.rtf diff=astextplain -*.RTF diff=astextplain \ No newline at end of file diff --git a/.github/ISSUE_TEMPLATE.md b/.github/ISSUE_TEMPLATE.md deleted file mode 100644 index 81d55846a..000000000 --- a/.github/ISSUE_TEMPLATE.md +++ /dev/null @@ -1,40 +0,0 @@ - - -## Support / Questions - -Please use https://forums.sonarr.tv/ for support. Support requests or questions will be redirected to the forums and the issue will be closed. - - - -## Bug Report - -### System Information/Logs - -**Sonarr Version:** - -**Operating System:** - -**.net Framework (Windows) or mono (macOS/Linux) Version:** - -**Link to Log Files (debug or trace):** - -**Browser (for UI bugs):** - -### Additional Information - - - -## Feature Request - -### What problem are you looking to solve? - -### Other Information diff --git a/.github/ISSUE_TEMPLATE/bug_report.yml b/.github/ISSUE_TEMPLATE/bug_report.yml new file mode 100644 index 000000000..4e4eedb66 --- /dev/null +++ b/.github/ISSUE_TEMPLATE/bug_report.yml @@ -0,0 +1,81 @@ +name: Bug Report +description: 'Only bug reports for v4 will be accepted, older versions are no longer receiving bug fixes and support issues will be closed immediately.' +labels: ['needs-triage'] +body: +- type: checkboxes + attributes: + label: Is there an existing issue for this? + description: Please search to see if an open or closed issue already exists for the bug you encountered. If a bug exists and it is closed as complete it may not yet be in a stable release. + options: + - label: I have searched the existing open and closed issues + required: true +- type: textarea + attributes: + label: Current Behavior + description: A concise description of what you're experiencing. + validations: + required: true +- type: textarea + attributes: + label: Expected Behavior + description: A concise description of what you expected to happen. + validations: + required: true +- type: textarea + attributes: + label: Steps To Reproduce + description: Steps to reproduce the behavior. + placeholder: | + 1. In this environment... + 2. With this config... + 3. Run '...' + 4. See error... + validations: + required: false +- type: textarea + attributes: + label: Environment + description: | + examples: + - **OS**: Ubuntu 22.04 + - **Sonarr**: Sonarr 4.0.0.766 + - **Docker Install**: Yes + - **Using Reverse Proxy**: No + - **Browser**: Firefox 90 (If UI related) + - **Database**: Sqlite 3.41.2 + value: | + - OS: + - Sonarr: + - Docker Install: + - Using Reverse Proxy: + - Browser: + - Database: + render: markdown + validations: + required: true +- type: dropdown + attributes: + label: What branch are you running? + options: + - Main + - Develop + - Other (This issue will be closed) + validations: + required: true +- type: textarea + attributes: + label: Trace Logs? + description: | + Trace Logs (https://wiki.servarr.com/sonarr/troubleshooting#logging-and-log-files) + ***Generally speaking, all bug reports must have trace logs provided.*** + *** Info Logs are not trace logs. If the logs do not say trace and are not from a file like `*.trace.*.txt` they are not trace logs.*** + validations: + required: true +- type: textarea + attributes: + label: Anything else? + description: | + Links? Screenshots? References? Anything that will give us more context about the issue you are encountering! + Tip: You can attach images or log files by clicking this area to highlight it and then dragging files in. + validations: + required: false diff --git a/.github/ISSUE_TEMPLATE/config.yml b/.github/ISSUE_TEMPLATE/config.yml new file mode 100644 index 000000000..2fb2fa0a1 --- /dev/null +++ b/.github/ISSUE_TEMPLATE/config.yml @@ -0,0 +1,14 @@ +blank_issues_enabled: false +contact_links: + - name: Support via Discord + url: https://discord.gg/M6BvZn5 + about: Chat with users and devs on support and setup related topics. + - name: Support via Reddit + url: https://reddit.com/r/Sonarr + about: Discuss and search through support topics. + - name: Support via Forums + url: https://forums.sonarr.tv/ + about: Discuss and search through support topics. + - name: Support via IRC + url: https://web.libera.chat/?channels=#sonarr + about: Chat with users and devs on support and setup related topics. \ No newline at end of file diff --git a/.github/ISSUE_TEMPLATE/feature_request.yml b/.github/ISSUE_TEMPLATE/feature_request.yml new file mode 100644 index 000000000..cd224373c --- /dev/null +++ b/.github/ISSUE_TEMPLATE/feature_request.yml @@ -0,0 +1,37 @@ +name: Feature Request +description: 'Suggest an idea for Sonarr' +labels: ['needs-triage'] +body: +- type: checkboxes + attributes: + label: Is there an existing issue for this? + description: Please search to see if an open or closed issue already exists for the feature you are requesting. If a feature request exists and it is closed as complete it may not yet be in a stable release. + options: + - label: I have searched the existing open and closed issues + required: true +- type: textarea + attributes: + label: Is your feature request related to a problem? Please describe + description: A clear and concise description of what the problem is. + validations: + required: true +- type: textarea + attributes: + label: Describe the solution you'd like + description: A clear and concise description of what you want to happen. + validations: + required: true +- type: textarea + attributes: + label: Describe alternatives you've considered + description: A clear and concise description of any alternative solutions or features you've considered. + validations: + required: true +- type: textarea + attributes: + label: Anything else? + description: | + Links? References? Mockups? Anything that will give us more context about the feature you are encountering! + Tip: You can attach images or log files by clicking this area to highlight it and then dragging files in. + validations: + required: false diff --git a/.github/PULL_REQUEST_TEMPLATE.md b/.github/PULL_REQUEST_TEMPLATE.md index e0d682009..25b1761f9 100644 --- a/.github/PULL_REQUEST_TEMPLATE.md +++ b/.github/PULL_REQUEST_TEMPLATE.md @@ -1,14 +1,15 @@ -#### Database Migration -YES | NO - #### Description A few sentences describing the overall goals of the pull request's commits. -#### Todos -- [ ] Tests -- [ ] Documentation + + +#### Screenshots for UI Changes + + +#### Database Migration +YES - ### #### Issues Fixed or Closed by this PR +* Closes # -* diff --git a/.github/SUPPORT.md b/.github/SUPPORT.md deleted file mode 100644 index c6cf56c79..000000000 --- a/.github/SUPPORT.md +++ /dev/null @@ -1,7 +0,0 @@ -## Support - -There are a number of frequently asked questions that have been answered in our [FAQ](https://github.com/Sonarr/Sonarr/wiki/FAQ) - -The [wiki](https://github.com/Sonarr/Sonarr/wiki) contains other information and guides - -If you have a support question, please use the [support forums](https://forums.sonarr.tv/). diff --git a/.github/actions/archive/action.yml b/.github/actions/archive/action.yml new file mode 100644 index 000000000..83e8a8ea9 --- /dev/null +++ b/.github/actions/archive/action.yml @@ -0,0 +1,29 @@ +name: Archive +description: Archive binaries for deployment + +inputs: + os: + description: 'OS that the packaging is running on' + required: true + artifact: + description: 'Binary artifact' + required: true + archive_type: + description: 'File type to use for the final package' + required: true + branch: + description: 'Git branch used for this build' + required: true + major_version: + description: 'Sonarr major version' + required: true + version: + description: 'Sonarr version' + required: true + +runs: + using: 'composite' + steps: + - name: Archive Artifact + uses: thedoctor0/zip-release@0.7.5 + diff --git a/.github/actions/package/action.yml b/.github/actions/package/action.yml new file mode 100644 index 000000000..99c4d4ff1 --- /dev/null +++ b/.github/actions/package/action.yml @@ -0,0 +1,78 @@ +name: Package +description: Packages binaries for deployment + +inputs: + platform: + description: 'Binary platform' + required: true + framework: + description: '.net framework' + required: true + artifact: + description: 'Binary artifact' + required: true + branch: + description: 'Git branch used for this build' + required: true + major_version: + description: 'Sonarr major version' + required: true + version: + description: 'Sonarr version' + required: true + +runs: + using: 'composite' + steps: + - name: Download Artifact + uses: actions/download-artifact@v4 + with: + name: ${{ inputs.artifact }} + path: _output + + - name: Download UI Artifact + uses: actions/download-artifact@v4 + with: + name: build_ui + path: _output/UI + + - name: Configure Environment Variables + shell: bash + run: | + echo "FRAMEWORK=${{ inputs.framework }}" >> "$GITHUB_ENV" + echo "BRANCH=${{ inputs.branch }}" >> "$GITHUB_ENV" + echo "SONARR_MAJOR_VERSION=${{ inputs.major_version }}" >> "$GITHUB_ENV" + echo "SONARR_VERSION=${{ inputs.version }}" >> "$GITHUB_ENV" + + - name: Create Packages + shell: bash + run: $GITHUB_ACTION_PATH/package.sh + + - name: Create Windows Installer (x64) + if: ${{ inputs.platform == 'windows' }} + working-directory: distribution/windows/setup + shell: cmd + run: | + SET RUNTIME=win-x64 + + build.bat + + - name: Create Windows Installer (x86) + if: ${{ inputs.platform == 'windows' }} + working-directory: distribution/windows/setup + shell: cmd + run: | + SET RUNTIME=win-x86 + + build.bat + + - name: Upload Artifact + uses: actions/upload-artifact@v4 + with: + name: release_${{ inputs.platform }} + compression-level: 0 + if-no-files-found: error + path: | + _artifacts/*.exe + _artifacts/*.tar.gz + _artifacts/*.zip diff --git a/.github/actions/package/package.sh b/.github/actions/package/package.sh new file mode 100755 index 000000000..8dce60585 --- /dev/null +++ b/.github/actions/package/package.sh @@ -0,0 +1,67 @@ +#!/bin/bash + +outputFolder=_output +artifactsFolder=_artifacts +uiFolder="$outputFolder/UI" +framework="${FRAMEWORK:=net6.0}" + +rm -rf $artifactsFolder +mkdir $artifactsFolder + +for runtime in _output/* +do + name="${runtime##*/}" + folderName="$runtime/$framework" + sonarrFolder="$folderName/Sonarr" + archiveName="Sonarr.$BRANCH.$SONARR_VERSION.$name" + + if [[ "$name" == 'UI' ]]; then + continue + fi + + echo "Creating package for $name" + + echo "Copying UI" + cp -r $uiFolder $sonarrFolder + + echo "Setting permissions" + find $sonarrFolder -name "ffprobe" -exec chmod a+x {} \; + find $sonarrFolder -name "Sonarr" -exec chmod a+x {} \; + find $sonarrFolder -name "Sonarr.Update" -exec chmod a+x {} \; + + if [[ "$name" == *"osx"* ]]; then + echo "Creating macOS package" + + packageName="$name-app" + packageFolder="$outputFolder/$packageName" + + rm -rf $packageFolder + mkdir $packageFolder + + cp -r distribution/macOS/Sonarr.app $packageFolder + mkdir -p $packageFolder/Sonarr.app/Contents/MacOS + + echo "Copying Binaries" + cp -r $sonarrFolder/* $packageFolder/Sonarr.app/Contents/MacOS + + echo "Removing Update Folder" + rm -r $packageFolder/Sonarr.app/Contents/MacOS/Sonarr.Update + + echo "Packaging macOS app Artifact" + (cd $packageFolder; zip -rq "../../$artifactsFolder/$archiveName-app.zip" ./Sonarr.app) + fi + + echo "Packaging Artifact" + if [[ "$name" == *"linux"* ]] || [[ "$name" == *"osx"* ]] || [[ "$name" == *"freebsd"* ]]; then + tar -zcf "./$artifactsFolder/$archiveName.tar.gz" -C $folderName Sonarr + fi + + if [[ "$name" == *"win"* ]]; then + if [ "$RUNNER_OS" = "Windows" ] + then + (cd $folderName; 7z a -tzip "../../../$artifactsFolder/$archiveName.zip" ./Sonarr) + else + (cd $folderName; zip -rq "../../../$artifactsFolder/$archiveName.zip" ./Sonarr) + fi + fi +done diff --git a/.github/actions/publish-test-artifact/action.yml b/.github/actions/publish-test-artifact/action.yml new file mode 100644 index 000000000..af3642043 --- /dev/null +++ b/.github/actions/publish-test-artifact/action.yml @@ -0,0 +1,18 @@ +name: Publish Test Artifact +description: Publishes a test artifact + +inputs: + framework: + description: '.net framework' + required: true + runtime: + description: '.net runtime' + required: true + +runs: + using: 'composite' + steps: + - uses: actions/upload-artifact@v4 + with: + name: tests-${{ inputs.runtime }} + path: _tests/${{ inputs.framework }}/${{ inputs.runtime }}/publish/**/* diff --git a/.github/actions/test/action.yml b/.github/actions/test/action.yml new file mode 100644 index 000000000..bd62f4830 --- /dev/null +++ b/.github/actions/test/action.yml @@ -0,0 +1,87 @@ +name: Test +description: Runs unit/integration tests + +inputs: + use_postgres: + description: 'Whether postgres should be used for the database' + os: + description: 'OS that the tests are running on' + required: true + artifact: + description: 'Test binary artifact' + required: true + pattern: + description: 'Pattern for DLLs' + required: true + filter: + description: 'Filter for tests' + required: true + integration_tests: + description: 'True if running integration tests' + binary_artifact: + description: 'Binary artifact for integration tests' + binary_path: + description: 'Path witin binary artifact for integration tests' + +runs: + using: 'composite' + steps: + - name: Setup .NET + uses: actions/setup-dotnet@v4 + + - name: Setup Postgres + if: ${{ inputs.use_postgres }} + uses: ikalnytskyi/action-setup-postgres@v4 + + - name: Setup Test Variables + shell: bash + run: | + echo "RESULTS_NAME=${{ inputs.integration_tests && 'integation-' || 'unit-' }}${{ inputs.artifact }}${{ inputs.use_postgres && '-postgres' }}" >> "$GITHUB_ENV" + + - name: Setup Postgres Environment Variables + if: ${{ inputs.use_postgres }} + shell: bash + run: | + echo "Sonarr__Postgres__Host=localhost" >> "$GITHUB_ENV" + echo "Sonarr__Postgres__Port=5432" >> "$GITHUB_ENV" + echo "Sonarr__Postgres__User=postgres" >> "$GITHUB_ENV" + echo "Sonarr__Postgres__Password=postgres" >> "$GITHUB_ENV" + + - name: Download Artifact + uses: actions/download-artifact@v4 + with: + name: ${{ inputs.artifact }} + path: _tests + + - name: Download Binary Artifact + if: ${{ inputs.integration_tests }} + uses: actions/download-artifact@v4 + with: + name: ${{ inputs.binary_artifact }} + path: _output + + - name: Set up binary artifact + if: ${{ inputs.binary_path != '' }} + shell: bash + run: mv ./_output/${{inputs.binary_path}} _tests/bin + + - name: Make executable + if: startsWith(inputs.os, 'windows') != true + shell: bash + run: chmod +x ./_tests/Sonarr.Test.Dummy && chmod +x ./_tests/ffprobe + + - name: Make Sonarr binary executable + if: ${{ inputs.integration_tests && !startsWith(inputs.os, 'windows') }} + shell: bash + run: chmod +x ./_tests/bin/Sonarr + + - name: Run tests + shell: bash + run: dotnet test ./_tests/Sonarr.*.Test.dll --filter "${{ inputs.filter }}" --logger "trx;LogFileName=${{ env.RESULTS_NAME }}.trx" --logger "GitHubActions;summary.includePassedTests=true;summary.includeSkippedTests=true" + + - name: Upload Test Results + if: ${{ !cancelled() }} + uses: actions/upload-artifact@v4 + with: + name: results-${{ env.RESULTS_NAME }} + path: TestResults/*.trx diff --git a/.github/dependabot.yml b/.github/dependabot.yml new file mode 100644 index 000000000..f33a02cd1 --- /dev/null +++ b/.github/dependabot.yml @@ -0,0 +1,12 @@ +# To get started with Dependabot version updates, you'll need to specify which +# package ecosystems to update and where the package manifests are located. +# Please see the documentation for more information: +# https://docs.github.com/github/administering-a-repository/configuration-options-for-dependency-updates +# https://containers.dev/guide/dependabot + +version: 2 +updates: + - package-ecosystem: "devcontainers" + directory: "/" + schedule: + interval: weekly diff --git a/.github/labeler.yml b/.github/labeler.yml new file mode 100644 index 000000000..fdd66d11a --- /dev/null +++ b/.github/labeler.yml @@ -0,0 +1,23 @@ +'connection': + - changed-files: + - any-glob-to-any-file: src/NzbDrone.Core/Notifications/**/* + +'db-migration': + - changed-files: + - any-glob-to-any-file: src/NzbDrone.Core/Datastore/Migration/* + +'download-client': + - changed-files: + - any-glob-to-any-file: src/NzbDrone.Core/Download/Clients/**/* + +'indexer': + - changed-files: + - any-glob-to-any-file: src/NzbDrone.Core/Indexers/**/* + +'parsing': + - changed-files: + - any-glob-to-any-file: src/NzbDrone.Core/Parser/**/* + +'ui-only': + - changed-files: + - any-glob-to-all-files: frontend/**/* diff --git a/.github/release.yml b/.github/release.yml new file mode 100644 index 000000000..87eb8f2fe --- /dev/null +++ b/.github/release.yml @@ -0,0 +1,9 @@ + changelog: + exclude: + authors: + - Weblate + - SonarrBot + categories: + - title: Changes + labels: + - '*' diff --git a/.github/workflows/api_docs.yml b/.github/workflows/api_docs.yml new file mode 100644 index 000000000..dfd8ce0e2 --- /dev/null +++ b/.github/workflows/api_docs.yml @@ -0,0 +1,52 @@ +name: 'API Docs' + +on: + workflow_dispatch: + schedule: + - cron: '0 0 * * 1' + push: + branches: + - develop + paths: + - ".github/workflows/api_docs.yml" + - "docs.sh" + - "src/Sonarr.Api.*/**" + - "src/Sonarr.Http/**" + - "src/**/*.csproj" + - "src/*" + +concurrency: + group: ${{ github.workflow }}-${{ github.ref }} + cancel-in-progress: true + +jobs: + api_docs: + runs-on: ubuntu-latest + if: github.repository == 'Sonarr/Sonarr' + permissions: + contents: write + steps: + - uses: actions/checkout@v4 + + - name: Setup dotnet + uses: actions/setup-dotnet@v4 + id: setup-dotnet + + - name: Create openapi.json + run: ./docs.sh Linux + + - name: Commit API Docs Change + continue-on-error: true + run: | + git config --global user.email "development@sonarr.tv" + git config --global user.name "Sonarr" + git checkout -b api-docs + git add src + if git status | grep -q modified + then + git commit -am 'Automated API Docs update' -m "ignore-downstream" + git push -f --set-upstream origin api-docs + curl -X POST -H "Authorization: Bearer ${{ secrets.OPENAPI_PAT }}" -H "Accept: application/vnd.github+json" https://api.github.com/repos/sonarr/sonarr/pulls -d '{"head":"api-docs","base":"develop","title":"Update API docs"}' + else + echo "No changes since last run" + fi diff --git a/.github/workflows/build.yml b/.github/workflows/build.yml new file mode 100644 index 000000000..52f9d5678 --- /dev/null +++ b/.github/workflows/build.yml @@ -0,0 +1,257 @@ +name: Build + +on: + push: + branches: + - develop + - main + paths-ignore: + - "src/Sonarr.Api.*/openapi.json" + pull_request: + branches: + - develop + paths-ignore: + - "src/NzbDrone.Core/Localization/Core/**" + - "src/Sonarr.Api.*/openapi.json" + +concurrency: + group: ${{ github.workflow }}-${{ github.event.pull_request.number || github.ref }} + cancel-in-progress: true + +env: + FRAMEWORK: net6.0 + RAW_BRANCH_NAME: ${{ github.head_ref || github.ref_name }} + SONARR_MAJOR_VERSION: 4 + VERSION: 4.0.14 + +jobs: + backend: + runs-on: windows-latest + outputs: + framework: ${{ steps.variables.outputs.framework }} + major_version: ${{ steps.variables.outputs.major_version }} + version: ${{ steps.variables.outputs.version }} + steps: + - name: Check out + uses: actions/checkout@v4 + + - name: Setup .NET + uses: actions/setup-dotnet@v4 + + - name: Setup Environment Variables + id: variables + shell: bash + run: | + # Add 800 to the build number because GitHub won't let us pick an arbitrary starting point + SONARR_VERSION="${{ env.VERSION }}.$((${{ github.run_number }}+800))" + DOTNET_VERSION=$(jq -r '.sdk.version' global.json) + + echo "SDK_PATH=${{ env.DOTNET_ROOT }}/sdk/${DOTNET_VERSION}" >> "$GITHUB_ENV" + echo "SONARR_VERSION=$SONARR_VERSION" >> "$GITHUB_ENV" + echo "BRANCH=${RAW_BRANCH_NAME//\//-}" >> "$GITHUB_ENV" + + echo "framework=${{ env.FRAMEWORK }}" >> "$GITHUB_OUTPUT" + echo "major_version=${{ env.SONARR_MAJOR_VERSION }}" >> "$GITHUB_OUTPUT" + echo "version=$SONARR_VERSION" >> "$GITHUB_OUTPUT" + + - name: Enable Extra Platforms In SDK + shell: bash + run: ./build.sh --enable-extra-platforms-in-sdk + + - name: Build Backend + shell: bash + run: ./build.sh --backend --enable-extra-platforms --packages + + # Test Artifacts + + - name: Publish win-x64 Test Artifact + uses: ./.github/actions/publish-test-artifact + with: + framework: ${{ env.FRAMEWORK }} + runtime: win-x64 + + - name: Publish linux-x64 Test Artifact + uses: ./.github/actions/publish-test-artifact + with: + framework: ${{ env.FRAMEWORK }} + runtime: linux-x64 + + - name: Publish osx-arm64 Test Artifact + uses: ./.github/actions/publish-test-artifact + with: + framework: ${{ env.FRAMEWORK }} + runtime: osx-arm64 + + # Build Artifacts (grouped by OS) + + - name: Publish FreeBSD Artifact + uses: actions/upload-artifact@v4 + with: + name: build_freebsd + path: _artifacts/freebsd-*/**/* + - name: Publish Linux Artifact + uses: actions/upload-artifact@v4 + with: + name: build_linux + path: _artifacts/linux-*/**/* + - name: Publish macOS Artifact + uses: actions/upload-artifact@v4 + with: + name: build_macos + path: _artifacts/osx-*/**/* + - name: Publish Windows Artifact + uses: actions/upload-artifact@v4 + with: + name: build_windows + path: _artifacts/win-*/**/* + + frontend: + runs-on: ubuntu-latest + steps: + - name: Check out + uses: actions/checkout@v4 + + - name: Volta + uses: volta-cli/action@v4 + + - name: Yarn Install + run: yarn install + + - name: Lint + run: yarn lint + + - name: Stylelint + run: yarn stylelint -f github + + - name: Build + run: yarn build --env production + + - name: Publish UI Artifact + uses: actions/upload-artifact@v4 + with: + name: build_ui + path: _output/UI/**/* + + unit_test: + needs: backend + strategy: + fail-fast: false + matrix: + os: [ubuntu-latest, macos-latest, windows-latest] + include: + - os: ubuntu-latest + artifact: tests-linux-x64 + filter: TestCategory!=ManualTest&TestCategory!=WINDOWS&TestCategory!=IntegrationTest&TestCategory!=AutomationTest + - os: macos-latest + artifact: tests-osx-arm64 + filter: TestCategory!=ManualTest&TestCategory!=WINDOWS&TestCategory!=IntegrationTest&TestCategory!=AutomationTest + - os: windows-latest + artifact: tests-win-x64 + filter: TestCategory!=ManualTest&TestCategory!=LINUX&TestCategory!=IntegrationTest&TestCategory!=AutomationTest + runs-on: ${{ matrix.os }} + steps: + - name: Check out + uses: actions/checkout@v4 + + - name: Test + uses: ./.github/actions/test + with: + os: ${{ matrix.os }} + artifact: ${{ matrix.artifact }} + pattern: Sonarr.*.Test.dll + filter: ${{ matrix.filter }} + + unit_test_postgres: + needs: backend + runs-on: ubuntu-latest + steps: + - name: Check out + uses: actions/checkout@v4 + + - name: Test + uses: ./.github/actions/test + with: + os: ubuntu-latest + artifact: tests-linux-x64 + pattern: Sonarr.*.Test.dll + filter: TestCategory!=ManualTest&TestCategory!=WINDOWS&TestCategory!=IntegrationTest&TestCategory!=AutomationTest + use_postgres: true + + integration_test: + needs: backend + strategy: + fail-fast: false + matrix: + os: [ubuntu-latest, macos-latest, windows-latest] + include: + - os: ubuntu-latest + artifact: tests-linux-x64 + filter: TestCategory!=ManualTest&TestCategory!=WINDOWS&TestCategory=IntegrationTest + binary_artifact: build_linux + binary_path: linux-x64/${{ needs.backend.outputs.framework }}/Sonarr + - os: macos-latest + artifact: tests-osx-arm64 + filter: TestCategory!=ManualTest&TestCategory!=WINDOWS&TestCategory=IntegrationTest + binary_artifact: build_macos + binary_path: osx-arm64/${{ needs.backend.outputs.framework }}/Sonarr + - os: windows-latest + artifact: tests-win-x64 + filter: TestCategory!=ManualTest&TestCategory!=LINUX&TestCategory=IntegrationTest + binary_artifact: build_windows + binary_path: win-x64/${{ needs.backend.outputs.framework }}/Sonarr + runs-on: ${{ matrix.os }} + steps: + - name: Check out + uses: actions/checkout@v4 + + - name: Test + uses: ./.github/actions/test + with: + os: ${{ matrix.os }} + artifact: ${{ matrix.artifact }} + pattern: Sonarr.*.Test.dll + filter: ${{ matrix.filter }} + integration_tests: true + binary_artifact: ${{ matrix.binary_artifact }} + binary_path: ${{ matrix.binary_path }} + + deploy: + if: ${{ github.ref_name == 'develop' || github.ref_name == 'main' }} + needs: [backend, frontend, unit_test, unit_test_postgres, integration_test] + secrets: inherit + uses: ./.github/workflows/deploy.yml + with: + framework: ${{ needs.backend.outputs.framework }} + branch: ${{ github.ref_name }} + major_version: ${{ needs.backend.outputs.major_version }} + version: ${{ needs.backend.outputs.version }} + + notify: + name: Discord Notification + needs: + [ + backend, + frontend, + unit_test, + unit_test_postgres, + integration_test, + deploy, + ] + if: ${{ !cancelled() && (github.ref_name == 'develop' || github.ref_name == 'main') }} + env: + STATUS: ${{ contains(needs.*.result, 'failure') && 'failure' || 'success' }} + runs-on: ubuntu-latest + + steps: + - name: Notify + uses: tsickert/discord-webhook@v6.0.0 + with: + webhook-url: ${{ secrets.DISCORD_WEBHOOK_URL }} + username: "GitHub Actions" + avatar-url: "https://github.githubassets.com/images/modules/logos_page/GitHub-Mark.png" + embed-title: "${{ github.workflow }}: ${{ env.STATUS == 'success' && 'Success' || 'Failure' }}" + embed-url: "https://github.com/${{ github.repository }}/actions/runs/${{ github.run_id }}" + embed-description: | + **Branch** ${{ github.ref }} + **Build** ${{ needs.backend.outputs.version }} + embed-color: ${{ env.STATUS == 'success' && '3066993' || '15158332' }} diff --git a/.github/workflows/conflict_labeler.yml b/.github/workflows/conflict_labeler.yml new file mode 100644 index 000000000..e9afb71a3 --- /dev/null +++ b/.github/workflows/conflict_labeler.yml @@ -0,0 +1,26 @@ +name: Merge Conflict Labeler + +on: + push: + branches: + - develop + pull_request_target: + branches: + - develop + types: [synchronize] + +jobs: + label: + name: Labeling + runs-on: ubuntu-latest + if: ${{ github.repository == 'Sonarr/Sonarr' }} + permissions: + contents: read + pull-requests: write + steps: + - name: Apply label + uses: eps1lon/actions-label-merge-conflict@v3 + with: + dirtyLabel: 'merge-conflict' + repoToken: '${{ secrets.GITHUB_TOKEN }}' + \ No newline at end of file diff --git a/.github/workflows/deploy.yml b/.github/workflows/deploy.yml new file mode 100644 index 000000000..4fa5b54ee --- /dev/null +++ b/.github/workflows/deploy.yml @@ -0,0 +1,160 @@ +name: Deploy + +on: + workflow_call: + inputs: + framework: + description: '.net framework' + type: string + required: true + branch: + description: 'Git branch used for this build' + type: string + required: true + major_version: + description: 'Sonarr major version' + type: string + required: true + version: + description: 'Sonarr version' + type: string + required: true + secrets: + SERVICES_API_KEY: + required: true + +jobs: + package: + strategy: + matrix: + platform: [freebsd, linux, macos, windows] + include: + - platform: freebsd + os: ubuntu-latest + - platform: linux + os: ubuntu-latest + - platform: macos + os: ubuntu-latest + - platform: windows + os: windows-latest + + runs-on: ${{ matrix.os }} + steps: + - name: Check out + uses: actions/checkout@v4 + + - name: Package + uses: ./.github/actions/package + with: + framework: ${{ inputs.framework }} + platform: ${{ matrix.platform }} + artifact: build_${{ matrix.platform }} + branch: ${{ inputs.branch }} + major_version: ${{ inputs.major_version }} + version: ${{ inputs.version }} + + release: + needs: package + runs-on: ubuntu-latest + permissions: + contents: write + steps: + - name: Check out + uses: actions/checkout@v4 + + - name: Download release artifacts + uses: actions/download-artifact@v4 + with: + path: _artifacts + pattern: release_* + merge-multiple: true + + - name: Get Previous Release + id: previous-release + uses: cardinalby/git-get-release-action@v1 + env: + GITHUB_TOKEN: ${{ github.token }} + with: + latest: true + prerelease: ${{ inputs.branch != 'main' }} + + - name: Generate Release Notes + id: generate-release-notes + uses: actions/github-script@v7 + with: + github-token: ${{ github.token }} + result-encoding: string + script: | + const { data } = await github.rest.repos.generateReleaseNotes({ + owner: context.repo.owner, + repo: context.repo.repo, + tag_name: 'v${{ inputs.version }}', + target_commitish: '${{ github.sha }}', + previous_tag_name: '${{ steps.previous-release.outputs.tag_name }}', + }) + return data.body + + - name: Create release + uses: ncipollo/release-action@v1 + with: + artifacts: _artifacts/Sonarr.* + commit: ${{ github.sha }} + generateReleaseNotes: false + body: ${{ steps.generate-release-notes.outputs.result }} + name: ${{ inputs.version }} + prerelease: ${{ inputs.branch != 'main' }} + skipIfReleaseExists: true + tag: v${{ inputs.version }} + + - name: Publish to Services + shell: bash + working-directory: _artifacts + run: | + branch=${{ inputs.branch }} + version=${{ inputs.version }} + lastCommit=${{ github.sha }} + + hashes="[" + + addHash() { + path=$1 + os=$2 + arch=$3 + type=$4 + + local hash=$(sha256sum *.$version.$path | awk '{ print $1; }') + echo "{ \""Os\"": \""$os\"", \""Arch\"": \""$arch\"", \""Type\"": \""$type\"", \""Hash\"": \""$hash\"" }" + } + + hashes="$hashes $(addHash "linux-arm.tar.gz" "linux" "arm" "archive")" + hashes="$hashes, $(addHash "linux-arm64.tar.gz" "linux" "arm64" "archive")" + hashes="$hashes, $(addHash "linux-x64.tar.gz" "linux" "x64" "archive")" + # hashes="$hashes, $(addHash "linux-x86.tar.gz" "linux" "x86" "archive")" + + # hashes="$hashes, $(addHash "linux-musl-arm.tar.gz" "linuxmusl" "arm" "archive")" + hashes="$hashes, $(addHash "linux-musl-arm64.tar.gz" "linuxmusl" "arm64" "archive")" + hashes="$hashes, $(addHash "linux-musl-x64.tar.gz" "linuxmusl" "x64" "archive")" + + hashes="$hashes, $(addHash "osx-arm64.tar.gz" "osx" "arm64" "archive")" + hashes="$hashes, $(addHash "osx-x64.tar.gz" "osx" "x64" "archive")" + + hashes="$hashes, $(addHash "osx-arm64-app.zip" "osx" "arm64" "installer")" + hashes="$hashes, $(addHash "osx-x64-app.zip" "osx" "x64" "installer")" + + hashes="$hashes, $(addHash "win-x64.zip" "windows" "x64" "archive")" + hashes="$hashes, $(addHash "win-x86.zip" "windows" "x86" "archive")" + + hashes="$hashes, $(addHash "win-x64-installer.exe" "windows" "x64" "installer")" + hashes="$hashes, $(addHash "win-x86-installer.exe" "windows" "x86" "installer")" + + hashes="$hashes, $(addHash "freebsd-x64.tar.gz" "freebsd" "x64" "archive")" + + hashes="$hashes ]" + + json="{\""branch\"":\""$branch\"", \""version\"":\""$version\"", \""lastCommit\"":\""$lastCommit\"", \""hashes\"":$hashes, \""gitHubRelease\"":true}" + url="https://services.sonarr.tv/v1/update" + + echo "Publishing update $version ($branch) to: $url" + echo "$json" + + curl -H "Content-Type: application/json" -H "X-Api-Key: ${{ secrets.SERVICES_API_KEY }}" -X POST -d "$json" --fail-with-body $url diff --git a/.github/workflows/labeler.yml b/.github/workflows/labeler.yml new file mode 100644 index 000000000..df54c0fff --- /dev/null +++ b/.github/workflows/labeler.yml @@ -0,0 +1,13 @@ +name: "Pull Request Labeler" +on: + - pull_request_target + +jobs: + triage: + permissions: + contents: read + pull-requests: write + runs-on: ubuntu-latest + if: github.repository == 'Sonarr/Sonarr' + steps: + - uses: actions/labeler@v5 diff --git a/.github/workflows/lock.yml b/.github/workflows/lock.yml new file mode 100644 index 000000000..d775234db --- /dev/null +++ b/.github/workflows/lock.yml @@ -0,0 +1,22 @@ +name: 'Lock threads' + +on: + workflow_dispatch: + schedule: + - cron: '0 0 * * *' + +jobs: + lock: + runs-on: ubuntu-latest + if: github.repository == 'Sonarr/Sonarr' + steps: + - uses: dessant/lock-threads@v5 + with: + github-token: ${{ github.token }} + issue-inactive-days: '90' + exclude-issue-created-before: '' + exclude-any-issue-labels: 'one-day-maybe' + add-issue-labels: '' + issue-comment: '' + issue-lock-reason: 'resolved' + process-only: '' diff --git a/.github/workflows/support-requests.yml b/.github/workflows/support-requests.yml new file mode 100644 index 000000000..adf5a8c4a --- /dev/null +++ b/.github/workflows/support-requests.yml @@ -0,0 +1,29 @@ +name: 'Support Requests' + +on: + issues: + types: [labeled, unlabeled, reopened] + +permissions: + issues: write + +jobs: + action: + runs-on: ubuntu-latest + if: github.repository == 'Sonarr/Sonarr' + steps: + - uses: dessant/support-requests@v4 + with: + github-token: ${{ github.token }} + support-label: 'support' + issue-comment: > + :wave: @{issue-author}, we use the issue tracker exclusively + for bug reports and feature requests. However, this issue appears + to be a support request. Please use one of the support channels: + [forums](https://forums.sonarr.tv/), [subreddit](https://www.reddit.com/r/sonarr/), + [discord](https://discord.gg/Ex7FmFK), or [IRC](https://web.libera.chat/?channels=#sonarr) + for support/questions. + close-issue: true + issue-close-reason: 'not planned' + lock-issue: false + issue-lock-reason: 'off-topic' diff --git a/.gitignore b/.gitignore index 8762d35b3..d17209556 100644 --- a/.gitignore +++ b/.gitignore @@ -45,6 +45,10 @@ _dotCover* # DevExpress CodeRush src/.cr/ +# Emacs +*~ +\#*\# + # NCrunch *.ncrunch* .*crunch*.local.xml @@ -80,7 +84,6 @@ TestResults [Tt]est[Rr]esult* *.Cache ClientBin -[Ss]tyle[Cc]op.* ~$* *.dbmdl Generated_Code #added for RIA/Silverlight projects @@ -113,25 +116,52 @@ src/UI/.idea/* *log.txt node_modules/ _output* +_artifacts _rawPackage/ _dotTrace* -_tests/ +_tests* +_publish* +_temp* *.Result.xml +coverage*.xml +coverage*.json setup/Output/ *.~is - -UI.Phantom/ +.mono #VS outout folders bin obj output/* +# .NET Core +project.lock.json +project.fragment.lock.json +artifacts/ +**/Properties/launchSettings.json + +# Packages +Sonarr_*/ +Sonarr_*.zip +Sonarr_*.gz +gecko.zip +geckodriver.exe #OS X metadata files ._* +.DS_Store _start _temp_*/**/* +# Windows thumbnail cache files +Thumbs.db + src/.idea/ +/distribution/windows/setup/output/* + +# API doc generation +.config/ + +# Ignore Jetbrains IntelliJ Workspace Directories +.idea/ diff --git a/.gitmodules b/.gitmodules deleted file mode 100644 index bc941f3dd..000000000 --- a/.gitmodules +++ /dev/null @@ -1,4 +0,0 @@ -[submodule "src/ExternalModules/CurlSharp"] - path = src/ExternalModules/CurlSharp - url = https://github.com/Sonarr/CurlSharp.git - branch = master diff --git a/.idea/.name b/.idea/.name deleted file mode 100644 index 02629676e..000000000 --- a/.idea/.name +++ /dev/null @@ -1 +0,0 @@ -Sonarr \ No newline at end of file diff --git a/.idea/Sonarr.iml b/.idea/Sonarr.iml deleted file mode 100644 index aeec84bf6..000000000 --- a/.idea/Sonarr.iml +++ /dev/null @@ -1,25 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - \ No newline at end of file diff --git a/.idea/codeStyleSettings.xml b/.idea/codeStyleSettings.xml deleted file mode 100644 index 7598f4c8e..000000000 --- a/.idea/codeStyleSettings.xml +++ /dev/null @@ -1,59 +0,0 @@ - - - - - - \ No newline at end of file diff --git a/.idea/encodings.xml b/.idea/encodings.xml deleted file mode 100644 index 97626ba45..000000000 --- a/.idea/encodings.xml +++ /dev/null @@ -1,6 +0,0 @@ - - - - - - \ No newline at end of file diff --git a/.idea/jsLibraryMappings.xml b/.idea/jsLibraryMappings.xml deleted file mode 100644 index b8387eb1b..000000000 --- a/.idea/jsLibraryMappings.xml +++ /dev/null @@ -1,6 +0,0 @@ - - - - - - \ No newline at end of file diff --git a/.idea/libraries/Sonarr_node_modules.xml b/.idea/libraries/Sonarr_node_modules.xml deleted file mode 100644 index 4eeebc5cc..000000000 --- a/.idea/libraries/Sonarr_node_modules.xml +++ /dev/null @@ -1,14 +0,0 @@ - - - - - - - - - - \ No newline at end of file diff --git a/.idea/misc.xml b/.idea/misc.xml deleted file mode 100644 index 19f74da8e..000000000 --- a/.idea/misc.xml +++ /dev/null @@ -1,14 +0,0 @@ - - - - - - - - - - - - - - \ No newline at end of file diff --git a/.idea/modules.xml b/.idea/modules.xml deleted file mode 100644 index 7cc2cf51b..000000000 --- a/.idea/modules.xml +++ /dev/null @@ -1,8 +0,0 @@ - - - - - - - - \ No newline at end of file diff --git a/.idea/vcs.xml b/.idea/vcs.xml deleted file mode 100644 index 94a25f7f4..000000000 --- a/.idea/vcs.xml +++ /dev/null @@ -1,6 +0,0 @@ - - - - - - \ No newline at end of file diff --git a/.vscode/extensions.json b/.vscode/extensions.json new file mode 100644 index 000000000..7a36fefe1 --- /dev/null +++ b/.vscode/extensions.json @@ -0,0 +1,7 @@ +{ + "recommendations": [ + "esbenp.prettier-vscode", + "ms-dotnettools.csdevkit", + "ms-vscode-remote.remote-containers" + ] +} diff --git a/.vscode/launch.json b/.vscode/launch.json new file mode 100644 index 000000000..6ea80f418 --- /dev/null +++ b/.vscode/launch.json @@ -0,0 +1,26 @@ +{ + "version": "0.2.0", + "configurations": [ + { + // Use IntelliSense to find out which attributes exist for C# debugging + // Use hover for the description of the existing attributes + // For further information visit https://github.com/dotnet/vscode-csharp/blob/main/debugger-launchjson.md + "name": "Run Sonarr", + "type": "coreclr", + "request": "launch", + "preLaunchTask": "build dotnet", + // If you have changed target frameworks, make sure to update the program path. + "program": "${workspaceFolder}/_output/net6.0/Sonarr", + "args": [], + "cwd": "${workspaceFolder}", + // For more information about the 'console' field, see https://aka.ms/VSCode-CS-LaunchJson-Console + "console": "integratedTerminal", + "stopAtEntry": false + }, + { + "name": ".NET Core Attach", + "type": "coreclr", + "request": "attach" + } + ] +} diff --git a/.vscode/settings.json b/.vscode/settings.json new file mode 100644 index 000000000..44aeb4060 --- /dev/null +++ b/.vscode/settings.json @@ -0,0 +1,3 @@ +{ + "typescript.tsdk": "node_modules\\typescript\\lib" +} diff --git a/.vscode/tasks.json b/.vscode/tasks.json new file mode 100644 index 000000000..cfd41d42f --- /dev/null +++ b/.vscode/tasks.json @@ -0,0 +1,44 @@ +{ + "version": "2.0.0", + "tasks": [ + { + "label": "build dotnet", + "command": "dotnet", + "type": "process", + "args": [ + "msbuild", + "-restore", + "${workspaceFolder}/src/Sonarr.sln", + "-p:GenerateFullPaths=true", + "-p:Configuration=Debug", + "-p:Platform=Posix", + "-consoleloggerparameters:NoSummary;ForceNoAlign" + ], + "problemMatcher": "$msCompile" + }, + { + "label": "publish", + "command": "dotnet", + "type": "process", + "args": [ + "publish", + "${workspaceFolder}/src/Sonarr.sln", + "-property:GenerateFullPaths=true", + "-consoleloggerparameters:NoSummary;ForceNoAlign" + ], + "problemMatcher": "$msCompile" + }, + { + "label": "watch", + "command": "dotnet", + "type": "process", + "args": [ + "watch", + "run", + "--project", + "${workspaceFolder}/src/Sonarr.sln" + ], + "problemMatcher": "$msCompile" + } + ] +} diff --git a/.yarnrc b/.yarnrc new file mode 100644 index 000000000..268da3ea9 --- /dev/null +++ b/.yarnrc @@ -0,0 +1,2 @@ +save-exact true +registry "https://registry.yarnpkg.com" diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index ab945cb0c..9eedd495b 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -3,39 +3,40 @@ We're always looking for people to help make Sonarr even better, there are a number of ways to contribute. ## Documentation ## -Setup guides, FAQ, the more information we have on the wiki the better. +Setup guides, [FAQ](https://wiki.servarr.com/sonarr/faq), the more information we have on the [wiki](https://wiki.servarr.com/sonarr) the better. ## Development ## ### Tools required ### -- Visual Studio 2015 -- HTML/Javascript editor of choice (Sublime Text/Webstorm/Atom/etc) -- npm (node package manager) -- git +- Visual Studio 2019 or higher (https://www.visualstudio.com/vs/). The community version is free and works (https://www.visualstudio.com/downloads/). +- HTML/Javascript editor of choice (VS Code/Sublime Text/Webstorm/Atom/etc) +- [Git](https://git-scm.com/downloads) +- [NodeJS](https://nodejs.org/en/download/) (Node 10.X.X or higher) +- [Yarn](https://yarnpkg.com/) ### Getting started ### -1. Fork Sonarr -2. Clone (develop branch) *you may need pull in submodules separately if you client doesn't clone them automatically (CurlSharp)* -3. Run `npm install` -4. Run `npm start` - Used to compile the UI components and copy them. - Leave this window open. - If you have gulp globally installed you can use `gulp watch` instead -5. Compile in Visual Studio +1. Fork Sonarr +2. Clone the repository into your development machine. [*info*](https://docs.github.com/en/get-started/quickstart/fork-a-repo) +3. Install the required Node Packages `yarn install` +4. Start webpack to monitor your dev environment for any frontend changes that need post processing using `yarn start` command. +5. Build the project in Visual Studio, Setting startup project to `Sonarr.Console` and framework to `x86` +6. Debug the project in Visual Studio +7. Open http://localhost:8989 ### Contributing Code ### - If you're adding a new, already requested feature, please comment on [Github Issues](https://github.com/Sonarr/Sonarr/issues "Github Issues") so work is not duplicated (If you want to add something not already on there, please talk to us first) -- Rebase from Sonarr's develop branch, don't merge +- Rebase from Sonarr's `develop` branch, don't merge - Make meaningful commits, or squash them - Feel free to make a pull request before work is complete, this will let us see where its at and make comments/suggest improvements -- Reach out to us on the forums or on IRC if you have any questions +- Reach out to us on our [forums](https://forums.sonarr.tv/), [subreddit](https://www.reddit.com/r/sonarr/), [discord](https://discord.gg/Ex7FmFK), or [IRC](https://web.libera.chat/?channels=#sonarr) if you have any questions - Add tests (unit/integration) - Commit with *nix line endings for consistency (We checkout Windows and commit *nix) - One feature/bug fix per pull request to keep things clean and easy to understand -- Use 4 spaces instead of tabs, this is the default for VS 2012 and WebStorm (to my knowledge) +- Use 4 spaces instead of tabs, this should be the default for VS 2019 and WebStorm ### Pull Requesting ### -- Only make pull requests to develop, never master, if you make a PR to master we'll comment on it and close it +- Only make pull requests to develop (currently `develop`), never `main`, if you make a PR to master we'll comment on it and close it - You're probably going to get some comments or questions from us, they will be to ensure consistency and maintainability - We'll try to respond to pull requests as soon as possible, if its been a day or two, please reach out to us, we may have missed it - Each PR should come from its own [feature branch](http://martinfowler.com/bliki/FeatureBranch.html) not develop in your fork, it should have a meaningful branch name (what is being added/fixed) diff --git a/FUNDING.yml b/FUNDING.yml new file mode 100644 index 000000000..7808f0da4 --- /dev/null +++ b/FUNDING.yml @@ -0,0 +1,12 @@ +# These are supported funding model platforms + +github: # Replace with up to 4 GitHub Sponsors-enabled usernames e.g., [user1, user2] +patreon: # Replace with a single Patreon username +open_collective: sonarr +ko_fi: # Replace with a single Ko-fi username +tidelift: # Replace with a single Tidelift platform-name/package-name e.g., npm/babel +community_bridge: # Replace with a single Community Bridge project-name e.g., cloud-foundry +liberapay: # Replace with a single Liberapay username +issuehunt: # Replace with a single IssueHunt username +otechie: # Replace with a single Otechie username +custom: # Replace with up to 4 custom sponsorship URLs e.g., ['link1', 'link2'] diff --git a/Logo/1024.png b/Logo/1024.png index 589664f1b..e0096e4ab 100644 Binary files a/Logo/1024.png and b/Logo/1024.png differ diff --git a/Logo/128.png b/Logo/128.png index b41422f1f..3d70e729f 100644 Binary files a/Logo/128.png and b/Logo/128.png differ diff --git a/Logo/16.png b/Logo/16.png index 970de87d5..62d07b987 100644 Binary files a/Logo/16.png and b/Logo/16.png differ diff --git a/Logo/256.png b/Logo/256.png index 32b4f7ebc..d4f68e845 100644 Binary files a/Logo/256.png and b/Logo/256.png differ diff --git a/Logo/32.png b/Logo/32.png index 54adf351f..8194401cf 100644 Binary files a/Logo/32.png and b/Logo/32.png differ diff --git a/Logo/400.png b/Logo/400.png index 95cf56b7b..2304bfe66 100644 Binary files a/Logo/400.png and b/Logo/400.png differ diff --git a/Logo/48.png b/Logo/48.png index e69b68ad6..00a4a7db9 100644 Binary files a/Logo/48.png and b/Logo/48.png differ diff --git a/Logo/512.png b/Logo/512.png index 1ce56cd75..dba1774db 100644 Binary files a/Logo/512.png and b/Logo/512.png differ diff --git a/Logo/64.png b/Logo/64.png index 06a0d4c1d..512c82eb0 100644 Binary files a/Logo/64.png and b/Logo/64.png differ diff --git a/Logo/72.png b/Logo/72.png new file mode 100644 index 000000000..b81e4098f Binary files /dev/null and b/Logo/72.png differ diff --git a/Logo/800.png b/Logo/800.png index fe518d5f3..47ee02383 100644 Binary files a/Logo/800.png and b/Logo/800.png differ diff --git a/Logo/96-Outline-White.png b/Logo/96-Outline-White.png index 087d747f0..bb06242f0 100644 Binary files a/Logo/96-Outline-White.png and b/Logo/96-Outline-White.png differ diff --git a/Logo/Sonarr.svg b/Logo/Sonarr.svg index cc8e1370e..b0a721893 100644 --- a/Logo/Sonarr.svg +++ b/Logo/Sonarr.svg @@ -1,240 +1,9 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + + + + + + + + + \ No newline at end of file diff --git a/Logo/sonarr-simple.svg b/Logo/sonarr-simple.svg new file mode 100644 index 000000000..b0a721893 --- /dev/null +++ b/Logo/sonarr-simple.svg @@ -0,0 +1,9 @@ + + + + + + + + + \ No newline at end of file diff --git a/README.md b/README.md index 86de5a1fe..d43366f93 100644 --- a/README.md +++ b/README.md @@ -1,52 +1,85 @@ -# Sonarr +# Sonarr Sonarr + +[![Translated](https://translate.servarr.com/widget/servarr/sonarr/svg-badge.svg)](https://translate.servarr.com/engage/servarr/) +[![Backers on Open Collective](https://opencollective.com/Sonarr/backers/badge.svg)](#backers) +[![Sponsors on Open Collective](https://opencollective.com/Sonarr/sponsors/badge.svg)](#sponsors) +[![Mega Sponsors on Open Collective](https://opencollective.com/Sonarr/megasponsors/badge.svg)](#mega-sponsors) Sonarr is a PVR for Usenet and BitTorrent users. It can monitor multiple RSS feeds for new episodes of your favorite shows and will grab, sort and rename them. It can also be configured to automatically upgrade the quality of files already downloaded when a better quality format becomes available. -## Major Features Include: +## Getting Started -* Support for major platforms: Windows, Linux, macOS, Raspberry Pi, etc. -* Automatically detects new episodes -* Can scan your existing library and download any missing episodes -* Can watch for better quality of the episodes you already have and do an automatic upgrade. *eg. from DVD to Blu-Ray* -* Automatic failed download handling will try another release if one fails -* Manual search so you can pick any release or to see why a release was not downloaded automatically -* Fully configurable episode renaming -* Full integration with SABnzbd and NZBGet -* Full integration with Kodi, Plex (notification, library update, metadata) -* Full support for specials and multi-episode releases -* And a beautiful UI +- [Download/Installation](https://sonarr.tv/#downloads-v3) +- [FAQ](https://wiki.servarr.com/sonarr/faq) +- [Wiki](https://wiki.servarr.com/Sonarr) +- [v4 Beta API Documentation](https://sonarr.tv/docs/api) +- [Donate](https://sonarr.tv/donate) -## Configuring Development Environment: +## Support -### Requirements +Note: GitHub Issues are for Bugs and Feature Requests Only -* Visual Studio 2015 (https://www.visualstudio.com/vs/) -* [Git](https://git-scm.com/downloads) -* [NodeJS](https://nodejs.org/en/download/) +- [Forums](https://forums.sonarr.tv/) +- [Discord](https://discord.gg/M6BvZn5) +- [GitHub - Bugs and Feature Requests Only](https://github.com/Sonarr/Sonarr/issues) +- [IRC](https://web.libera.chat/?channels=#sonarr) +- [Reddit](https://www.reddit.com/r/sonarr) +- [Wiki](https://wiki.servarr.com/sonarr) -### Setup +## Features -* Make sure all the required software mentioned above are installed. -* Clone the repository into your development machine. [*info*](https://help.github.com/articles/working-with-repositories) -* Grab the submodules `git submodule init && git submodule update` -* Install the required Node Packages `npm install` -* Start gulp to monitor your dev environment for any changes that need post processing using `npm start` command. +### Current Features -*Please note gulp must be running at all times while you are working with Sonarr client source files.* +- Support for major platforms: Windows, Linux, macOS, Raspberry Pi, etc. +- Automatically detects new episodes +- Can scan your existing library and download any missing episodes +- Can watch for better quality of the episodes you already have and do an automatic upgrade. _eg. from DVD to Blu-Ray_ +- Automatic failed download handling will try another release if one fails +- Manual search so you can pick any release or to see why a release was not downloaded automatically +- Fully configurable episode renaming +- Full integration with SABnzbd and NZBGet +- Full integration with Kodi, Plex (notification, library update, metadata) +- Full support for specials and multi-episode releases +- And a beautiful UI + +## Contributing ### Development -* Open `NzbDrone.sln` in Visual Studio -* Make sure `NzbDrone.Console` is set as the startup project +This project exists thanks to all the people who contribute. [Contribute](CONTRIBUTING.md). -### License + -* [GNU GPL v3](http://www.gnu.org/licenses/gpl.html) -* Copyright 2010-2017 +### Supporters -### Sponsors +This project would not be possible without the support of our users and software providers. +[**Become a sponsor or backer**](https://opencollective.com/sonarr) to help us out! -* [JetBrains](http://www.jetbrains.com/) for providing us with free licenses to their great tools - * [ReSharper](http://www.jetbrains.com/resharper/) - * [WebStorm](http://www.jetbrains.com/webstorm/) - * [TeamCity](http://www.jetbrains.com/teamcity/) +#### Mega Sponsors + +[![Sponsors](https://opencollective.com/sonarr/tiers/mega-sponsor.svg?width=890)](https://opencollective.com/sonarr/contribute/mega-sponsor-21443/checkout) + +#### Sponsors + +[![Flexible Sponsors](https://opencollective.com/sonarr/sponsors.svg?width=890)](https://opencollective.com/sonarr/contribute/sponsor-21457/checkout) + +#### Backers + +[![Backers](https://opencollective.com/sonarr/backers.svg?width=890)](https://opencollective.com/sonarr/contribute/backer-21442/checkout) + +#### JetBrains + +Thank you to [JetBrains](http://www.jetbrains.com/) for providing us with free licenses to their great tools + +[TeamCity](http://www.jetbrains.com/teamcity/) + +[ReSharper](http://www.jetbrains.com/resharper/) + +[dotTrace](http://www.jetbrains.com/dottrace/) + +[Rider](http://www.jetbrains.com/rider/) + +### Licenses + +- [GNU GPL v3](http://www.gnu.org/licenses/gpl.html) +- Copyright 2010-2024 diff --git a/SECURITY.md b/SECURITY.md new file mode 100644 index 000000000..a534ff2fb --- /dev/null +++ b/SECURITY.md @@ -0,0 +1,9 @@ +# Security Policy + +## Reporting a Vulnerability + +Please report (suspected) security vulnerabilities on Discord (preferred) to +either markus101 +#2148 or Taloth#7357 or via email: security@sonarr.tv. You will receive a response from +us within 72 hours. If the issue is confirmed, we will release a patch as soon +as possible depending on complexity/severity. diff --git a/build.ps1 b/build.ps1 deleted file mode 100644 index 45b8ce783..000000000 --- a/build.ps1 +++ /dev/null @@ -1 +0,0 @@ -Write-Warning "DEPRECATED -- Please use build.sh instead." \ No newline at end of file diff --git a/build.sh b/build.sh index e45c949e9..ee59d2f61 100755 --- a/build.sh +++ b/build.sh @@ -1,265 +1,455 @@ -#! /bin/bash -msBuild='/c/Program Files (x86)/MSBuild/14.0/Bin' -outputFolder='./_output' -outputFolderMono='./_output_mono' -outputFolderOsx='./_output_osx' -outputFolderOsxApp='./_output_osx_app' -testPackageFolder='./_tests/' -testSearchPattern='*.Test/bin/x86/Release' -sourceFolder='./src' -slnFile=$sourceFolder/NzbDrone.sln -updateFolder=$outputFolder/NzbDrone.Update -updateFolderMono=$outputFolderMono/NzbDrone.Update +#! /usr/bin/env bash +set -e -nuget='tools/nuget/nuget.exe'; -CheckExitCode() +outputFolder='_output' +testPackageFolder='_tests' +artifactsFolder="_artifacts"; +framework="${FRAMEWORK:=net6.0}" + +ProgressStart() { - "$@" - local status=$? - if [ $status -ne 0 ]; then - echo "error with $1" >&2 - exit 1 + echo "::group::$1" + echo "Start '$1'" +} + +ProgressEnd() +{ + echo "Finish '$1'" + echo "::endgroup::" +} + +UpdateVersionNumber() +{ + if [ "$SONARR_VERSION" != "" ]; then + echo "Updating version info to: $SONARR_VERSION" + sed -i'' -e "s/[0-9.*]\+<\/AssemblyVersion>/$SONARR_VERSION<\/AssemblyVersion>/g" src/Directory.Build.props + sed -i'' -e "s/[\$()A-Za-z-]\+<\/AssemblyConfiguration>/${BRANCH}<\/AssemblyConfiguration>/g" src/Directory.Build.props + sed -i'' -e "s/10.0.0.0<\/string>/$SONARR_VERSION<\/string>/g" distribution/macOS/Sonarr.app/Contents/Info.plist fi - return $status } -CleanFolder() +EnableExtraPlatformsInSDK() { - local path=$1 - local keepConfigFiles=$2 - - - find $path -name "*.transform" -exec rm "{}" \; - - if [ $keepConfigFiles != true ] ; then - find $path -name "*.dll.config" -exec rm "{}" \; + BUNDLEDVERSIONS="${SDK_PATH}/Microsoft.NETCoreSdk.BundledVersions.props" + if grep -q freebsd-x64 "$BUNDLEDVERSIONS"; then + echo "Extra platforms already enabled" + else + echo "Enabling extra platform support" + sed -i.ORI 's/osx-x64/osx-x64;freebsd-x64/' "$BUNDLEDVERSIONS" fi - - echo "Removing FluentValidation.Resources files" - find $path -name "FluentValidation.resources.dll" -exec rm "{}" \; - find $path -name "App.config" -exec rm "{}" \; - - echo "Removing .less files" - find $path -name "*.less" -exec rm "{}" \; - - echo "Removing vshost files" - find $path -name "*.vshost.exe" -exec rm "{}" \; - - echo "Removing dylib files" - find $path -name "*.dylib" -exec rm "{}" \; - - echo "Removing Empty folders" - find $path -depth -empty -type d -exec rm -r "{}" \; } - - -AddJsonNet() +EnableExtraPlatforms() { - rm $outputFolder/Newtonsoft.Json.* - cp $sourceFolder/packages/Newtonsoft.Json.*/lib/net35/*.dll $outputFolder - cp $sourceFolder/packages/Newtonsoft.Json.*/lib/net35/*.dll $outputFolder/NzbDrone.Update + if grep -qv freebsd-x64 src/Directory.Build.props; then + sed -i'' -e "s^\(.*\)^\1;freebsd-x64^g" src/Directory.Build.props + fi } -BuildWithMSBuild() +LintUI() { - export PATH=$msBuild:$PATH - CheckExitCode MSBuild.exe $slnFile //t:Clean //m - $nuget restore $slnFile - CheckExitCode MSBuild.exe $slnFile //p:Configuration=Release //p:Platform=x86 //t:Build //m //p:AllowedReferenceRelatedFileExtensions=.pdb -} + ProgressStart 'ESLint' + yarn lint + ProgressEnd 'ESLint' -BuildWithXbuild() -{ - export MONO_IOMAP=case - CheckExitCode xbuild /t:Clean $slnFile - mono $nuget restore $slnFile - CheckExitCode xbuild /p:Configuration=Release /p:Platform=x86 /t:Build /p:AllowedReferenceRelatedFileExtensions=.pdb $slnFile + ProgressStart 'Stylelint' + yarn stylelint + ProgressEnd 'Stylelint' } Build() { - echo "##teamcity[progressStart 'Build']" + ProgressStart 'Build' rm -rf $outputFolder + rm -rf $testPackageFolder - if [ $runtime = "dotnet" ] ; then - BuildWithMSBuild + slnFile=src/Sonarr.sln + + if [ $os = "windows" ]; then + platform=Windows else - BuildWithXbuild + platform=Posix fi - CleanFolder $outputFolder false + dotnet clean $slnFile -c Debug + dotnet clean $slnFile -c Release - AddJsonNet - - echo "Removing Mono.Posix.dll" - rm $outputFolder/Mono.Posix.dll - - echo "##teamcity[progressFinish 'Build']" -} - -RunGulp() -{ - echo "##teamcity[progressStart 'npm install']" - npm-cache install npm || CheckExitCode npm install - echo "##teamcity[progressFinish 'npm install']" - - echo "##teamcity[progressStart 'Running gulp']" - CheckExitCode npm run build - echo "##teamcity[progressFinish 'Running gulp']" -} - -CreateMdbs() -{ - local path=$1 - if [ $runtime = "dotnet" ] ; then - local pdbFiles=( $(find $path -name "*.pdb") ) - for filename in "${pdbFiles[@]}" - do - if [ -e ${filename%.pdb}.dll ] ; then - tools/pdb2mdb/pdb2mdb.exe ${filename%.pdb}.dll - fi - if [ -e ${filename%.pdb}.exe ] ; then - tools/pdb2mdb/pdb2mdb.exe ${filename%.pdb}.exe - fi - done + if [[ -z "$RID" || -z "$FRAMEWORK" ]]; + then + dotnet msbuild -restore $slnFile -p:Configuration=Release -p:Platform=$platform -t:PublishAllRids + else + dotnet msbuild -restore $slnFile -p:Configuration=Release -p:Platform=$platform -p:RuntimeIdentifiers=$RID -t:PublishAllRids fi + + ProgressEnd 'Build' } -PackageMono() +YarnInstall() { - echo "##teamcity[progressStart 'Creating Mono Package']" - rm -rf $outputFolderMono - cp -r $outputFolder $outputFolderMono + ProgressStart 'yarn install' + yarn install --frozen-lockfile --network-timeout 120000 + ProgressEnd 'yarn install' +} - echo "Creating MDBs" - CreateMdbs $outputFolderMono +RunWebpack() +{ + ProgressStart 'Running webpack' + yarn run build --env production + ProgressEnd 'Running webpack' +} - echo "Removing PDBs" - find $outputFolderMono -name "*.pdb" -exec rm "{}" \; +PackageFiles() +{ + local folder="$1" + local framework="$2" + local runtime="$3" + + rm -rf $folder + mkdir -p $folder + cp -r $outputFolder/$framework/$runtime/publish/* $folder + cp -r $outputFolder/Sonarr.Update/$framework/$runtime/publish $folder/Sonarr.Update + + if [ "$FRONTEND" = "YES" ]; + then + cp -r $outputFolder/UI $folder + fi + + echo "Adding LICENSE" + cp LICENSE.md $folder +} + +PackageLinux() +{ + local framework="$1" + local runtime="$2" + + ProgressStart "Creating $runtime Package for $framework" + + local folder=$artifactsFolder/$runtime/$framework/Sonarr + + PackageFiles "$folder" "$framework" "$runtime" echo "Removing Service helpers" - rm -f $outputFolderMono/ServiceUninstall.* - rm -f $outputFolderMono/ServiceInstall.* + rm -f $folder/ServiceUninstall.* + rm -f $folder/ServiceInstall.* - echo "Removing native windows binaries Sqlite, MediaInfo" - rm -f $outputFolderMono/sqlite3.* - rm -f $outputFolderMono/MediaInfo.* + echo "Removing Sonarr.Windows" + rm $folder/Sonarr.Windows.* - echo "Adding NzbDrone.Core.dll.config (for dllmap)" - cp $sourceFolder/NzbDrone.Core/NzbDrone.Core.dll.config $outputFolderMono + echo "Adding Sonarr.Mono to UpdatePackage" + cp $folder/Sonarr.Mono.* $folder/Sonarr.Update + if [ "$framework" = "$framework" ]; then + cp $folder/Mono.Posix.NETStandard.* $folder/Sonarr.Update + cp $folder/libMonoPosixHelper.* $folder/Sonarr.Update + fi - echo "Adding CurlSharp.dll.config (for dllmap)" - cp $sourceFolder/NzbDrone.Common/CurlSharp.dll.config $outputFolderMono - - echo "Renaming NzbDrone.Console.exe to NzbDrone.exe" - rm $outputFolderMono/NzbDrone.exe* - for file in $outputFolderMono/NzbDrone.Console.exe*; do - mv "$file" "${file//.Console/}" - done - - echo "Removing NzbDrone.Windows" - rm $outputFolderMono/NzbDrone.Windows.* - - echo "Adding NzbDrone.Mono to UpdatePackage" - cp $outputFolderMono/NzbDrone.Mono.* $updateFolderMono - - echo "##teamcity[progressFinish 'Creating Mono Package']" + ProgressEnd "Creating $runtime Package for $framework" } -PackageOsx() +PackageMacOS() { - echo "##teamcity[progressStart 'Creating OS X Package']" - rm -rf $outputFolderOsx - cp -r $outputFolderMono $outputFolderOsx + local framework="$1" + local runtime="$2" - echo "Adding sqlite dylibs" - cp $sourceFolder/Libraries/Sqlite/*.dylib $outputFolderOsx + ProgressStart "Creating $runtime Package for $framework" - echo "Adding MediaInfo dylib" - cp $sourceFolder/Libraries/MediaInfo/*.dylib $outputFolderOsx + local folder=$artifactsFolder/$runtime/$framework/Sonarr - echo "Adding Startup script" - cp ./osx/Sonarr $outputFolderOsx + PackageFiles "$folder" "$framework" "$runtime" - echo "##teamcity[progressFinish 'Creating OS X Package']" + echo "Removing Service helpers" + rm -f $folder/ServiceUninstall.* + rm -f $folder/ServiceInstall.* + + echo "Removing Sonarr.Windows" + rm $folder/Sonarr.Windows.* + + echo "Adding Sonarr.Mono to UpdatePackage" + cp $folder/Sonarr.Mono.* $folder/Sonarr.Update + if [ "$framework" = "$framework" ]; then + cp $folder/Mono.Posix.NETStandard.* $folder/Sonarr.Update + cp $folder/libMonoPosixHelper.* $folder/Sonarr.Update + fi + + ProgressEnd "Creating $runtime Package for $framework" } -PackageOsxApp() +PackageMacOSApp() { - echo "##teamcity[progressStart 'Creating OS X App Package']" - rm -rf $outputFolderOsxApp - mkdir $outputFolderOsxApp + local framework="$1" + local runtime="$2" - cp -r ./osx/Sonarr.app $outputFolderOsxApp - cp -r $outputFolderOsx $outputFolderOsxApp/Sonarr.app/Contents/MacOS + ProgressStart "Creating $runtime App Package for $framework" - echo "##teamcity[progressFinish 'Creating OS X App Package']" + local folder=$artifactsFolder/$runtime-app/$framework + + rm -rf $folder + mkdir -p $folder + cp -r distribution/macOS/Sonarr.app $folder + mkdir -p $folder/Sonarr.app/Contents/MacOS + + echo "Copying Binaries" + cp -r $artifactsFolder/$runtime/$framework/Sonarr/* $folder/Sonarr.app/Contents/MacOS + + echo "Removing Update Folder" + rm -r $folder/Sonarr.app/Contents/MacOS/Sonarr.Update + + ProgressEnd "Creating $runtime App Package for $framework" +} + +PackageWindows() +{ + local framework="$1" + local runtime="$2" + + ProgressStart "Creating Windows Package for $framework" + + local folder=$artifactsFolder/$runtime/$framework/Sonarr + + PackageFiles "$folder" "$framework" "$runtime" + cp -r $outputFolder/$framework-windows/$runtime/publish/* $folder + + echo "Removing Sonarr.Mono" + rm -f $folder/Sonarr.Mono.* + rm -f $folder/Mono.Posix.NETStandard.* + rm -f $folder/libMonoPosixHelper.* + + echo "Adding Sonarr.Windows to UpdatePackage" + cp $folder/Sonarr.Windows.* $folder/Sonarr.Update + + ProgressEnd "Creating Windows Package for $framework" +} + +Package() +{ + local framework="$1" + local runtime="$2" + local SPLIT + + IFS='-' read -ra SPLIT <<< "$runtime" + + case "${SPLIT[0]}" in + linux|freebsd*) + PackageLinux "$framework" "$runtime" + ;; + win) + PackageWindows "$framework" "$runtime" + ;; + osx) + PackageMacOS "$framework" "$runtime" + ;; + esac } PackageTests() { - echo "Packaging Tests" - echo "##teamcity[progressStart 'Creating Test Package']" - rm -rf $testPackageFolder - mkdir $testPackageFolder + local framework="$1" + local runtime="$2" - find $sourceFolder -path $testSearchPattern -exec cp -r -u -T "{}" $testPackageFolder \; + ProgressStart "Creating $runtime Test Package for $framework" - if [ $runtime = "dotnet" ] ; then - $nuget install NUnit.ConsoleRunner -Version 3.2.0 -Output $testPackageFolder - else - mono $nuget install NUnit.ConsoleRunner -Version 3.2.0 -Output $testPackageFolder - fi + cp test.sh "$testPackageFolder/$framework/$runtime/publish" - cp $outputFolder/*.dll $testPackageFolder - cp ./*.sh $testPackageFolder + rm -f $testPackageFolder/$framework/$runtime/*.log.config - echo "Creating MDBs for tests" - CreateMdbs $testPackageFolder - - rm -f $testPackageFolder/*.log.config - - CleanFolder $testPackageFolder true - - echo "Adding NzbDrone.Core.dll.config (for dllmap)" - cp $sourceFolder/NzbDrone.Core/NzbDrone.Core.dll.config $testPackageFolder - - echo "Adding CurlSharp.dll.config (for dllmap)" - cp $sourceFolder/NzbDrone.Common/CurlSharp.dll.config $testPackageFolder - - echo "Copying CurlSharp libraries" - cp $sourceFolder/ExternalModules/CurlSharp/libs/i386/* $testPackageFolder - - echo "##teamcity[progressFinish 'Creating Test Package']" + ProgressEnd "Creating $runtime Test Package for $framework" } -CleanupWindowsPackage() +UploadTestArtifacts() { - echo "Removing NzbDrone.Mono" - rm -f $outputFolder/NzbDrone.Mono.* + local framework="$1" - echo "Adding NzbDrone.Windows to UpdatePackage" - cp $outputFolder/NzbDrone.Windows.* $updateFolder + ProgressStart 'Publishing Test Artifacts' + + # Tests + for dir in $testPackageFolder/$framework/* + do + local runtime=$(basename "$dir") + echo "##teamcity[publishArtifacts '$testPackageFolder/$framework/$runtime/publish/** => tests.$runtime.zip']" + done + + ProgressEnd 'Publishing Test Artifacts' +} + +UploadArtifacts() +{ + local framework="$1" + + ProgressStart 'Publishing Artifacts' + + # Releases + for dir in $artifactsFolder/* + do + local runtime=$(basename "$dir") + + echo "##teamcity[publishArtifacts '$artifactsFolder/$runtime/$framework/** => Sonarr.$BRANCH.$SONARR_VERSION.$runtime.zip']" + done + + # Debian Package / Windows installer / macOS app + echo "##teamcity[publishArtifacts 'distribution/** => distribution.zip']" + + ProgressEnd 'Publishing Artifacts' +} + +UploadUIArtifacts() +{ + local framework="$1" + + ProgressStart 'Publishing UI Artifacts' + + # UI folder + echo "##teamcity[publishArtifacts '$outputFolder/UI/** => UI.zip']" + + ProgressEnd 'Publishing UI Artifacts' } # Use mono or .net depending on OS case "$(uname -s)" in CYGWIN*|MINGW32*|MINGW64*|MSYS*) # on windows, use dotnet - runtime="dotnet" + os="windows" ;; *) # otherwise use mono - runtime="mono" + os="posix" ;; esac -Build -RunGulp -PackageMono -PackageOsx -PackageOsxApp -PackageTests -CleanupWindowsPackage +POSITIONAL=() + +if [ $# -eq 0 ]; then + echo "No arguments provided, building everything" + BACKEND=YES + FRONTEND=YES + PACKAGES=YES + LINT=YES + ENABLE_EXTRA_PLATFORMS=NO + ENABLE_EXTRA_PLATFORMS_IN_SDK=NO +fi + +while [[ $# -gt 0 ]] +do +key="$1" + +case $key in + --backend) + BACKEND=YES + shift # past argument + ;; + --enable-bsd|--enable-extra-platforms) + ENABLE_EXTRA_PLATFORMS=YES + shift # past argument + ;; + --enable-extra-platforms-in-sdk) + ENABLE_EXTRA_PLATFORMS_IN_SDK=YES + shift # past argument + ;; + -r|--runtime) + RID="$2" + shift # past argument + shift # past value + ;; + -f|--framework) + FRAMEWORK="$2" + shift # past argument + shift # past value + ;; + --frontend) + FRONTEND=YES + shift # past argument + ;; + --packages) + PACKAGES=YES + shift # past argument + ;; + --lint) + LINT=YES + shift # past argument + ;; + --all) + BACKEND=YES + FRONTEND=YES + PACKAGES=YES + LINT=YES + shift # past argument + ;; + *) # unknown option + POSITIONAL+=("$1") # save it in an array for later + shift # past argument + ;; +esac +done +set -- "${POSITIONAL[@]}" # restore positional parameters + +if [ "$ENABLE_EXTRA_PLATFORMS_IN_SDK" = "YES" ]; +then + EnableExtraPlatformsInSDK +fi + +if [ "$BACKEND" = "YES" ]; +then + UpdateVersionNumber + if [ "$ENABLE_EXTRA_PLATFORMS" = "YES" ]; + then + EnableExtraPlatforms + fi + + Build + + if [[ -z "$RID" || -z "$FRAMEWORK" ]]; + then + PackageTests "$framework" "win-x64" + PackageTests "$framework" "win-x86" + PackageTests "$framework" "linux-x64" + PackageTests "$framework" "linux-musl-x64" + PackageTests "$framework" "osx-x64" + if [ "$ENABLE_EXTRA_PLATFORMS" = "YES" ]; + then + PackageTests "$framework" "freebsd-x64" + fi + else + PackageTests "$FRAMEWORK" "$RID" + fi + + UploadTestArtifacts "$framework" +fi + +if [ "$FRONTEND" = "YES" ]; +then + YarnInstall + + if [ "$LINT" = "YES" ]; + then + LintUI + fi + + RunWebpack + UploadUIArtifacts +fi + +if [ "$PACKAGES" = "YES" ]; +then + UpdateVersionNumber + + if [[ -z "$RID" || -z "$FRAMEWORK" ]]; + then + Package "$framework" "win-x64" + Package "$framework" "win-x86" + Package "$framework" "linux-x64" + Package "$framework" "linux-musl-x64" + Package "$framework" "linux-arm64" + Package "$framework" "linux-musl-arm64" + Package "$framework" "linux-arm" + Package "$framework" "osx-x64" + Package "$framework" "osx-arm64" + if [ "$ENABLE_EXTRA_PLATFORMS" = "YES" ]; + then + Package "$framework" "freebsd-x64" + fi + else + Package "$FRAMEWORK" "$RID" + fi + + UploadArtifacts "$framework" +fi diff --git a/debian/changelog b/debian/changelog deleted file mode 100644 index eb8f841a6..000000000 --- a/debian/changelog +++ /dev/null @@ -1,5 +0,0 @@ -nzbdrone {version} {branch}; urgency=low - - * Automatic Release. - - -- NzbDrone Mon, 26 Aug 2013 00:00:00 -0700 diff --git a/debian/compat b/debian/compat deleted file mode 100644 index 45a4fb75d..000000000 --- a/debian/compat +++ /dev/null @@ -1 +0,0 @@ -8 diff --git a/debian/control b/debian/control deleted file mode 100644 index ba30c02ee..000000000 --- a/debian/control +++ /dev/null @@ -1,12 +0,0 @@ -Section: web -Priority: optional -Maintainer: Sonarr -Source: nzbdrone -Homepage: https://sonarr.tv -Vcs-Git: git@github.com:Sonarr/Sonarr.git -Vcs-Browser: https://github.com/Sonarr/Sonarr - -Package: nzbdrone -Architecture: all -Depends: libmono-cil-dev (>= 3.2), sqlite3 (>= 3.7), mediainfo (>= 0.7.52) -Description: Sonarr is an internet PVR diff --git a/debian/copyright b/debian/copyright deleted file mode 100755 index 466d37fce..000000000 --- a/debian/copyright +++ /dev/null @@ -1,24 +0,0 @@ -Format: http://www.debian.org/doc/packaging-manuals/copyright-format/1.0/ -Upstream-Name: nzbdrone -Source: https://github.com/Sonarr/Sonarr - -Files: * -Copyright: 2010-2016 Sonarr - -License: GPL-3.0+ - - This program is free software: you can redistribute it and/or modify - it under the terms of the GNU General Public License as published by - the Free Software Foundation, either version 3 of the License, or - (at your option) any later version. - . - This package is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. - . - You should have received a copy of the GNU General Public License - along with this program. If not, see . - . - On Debian systems, the complete text of the GNU General - Public License version 3 can be found in "/usr/share/common-licenses/GPL-3". diff --git a/debian/install b/debian/install deleted file mode 100755 index 106b06a9b..000000000 --- a/debian/install +++ /dev/null @@ -1 +0,0 @@ -nzbdrone_bin/* opt/NzbDrone diff --git a/debian/rules b/debian/rules deleted file mode 100755 index b760bee7f..000000000 --- a/debian/rules +++ /dev/null @@ -1,13 +0,0 @@ -#!/usr/bin/make -f -# -*- makefile -*- -# Sample debian/rules that uses debhelper. -# This file was originally written by Joey Hess and Craig Small. -# As a special exception, when this file is copied by dh-make into a -# dh-make output file, you may use that output file without restriction. -# This special exception was added by Craig Small in version 0.37 of dh-make. - -# Uncomment this to turn on verbose mode. -#export DH_VERBOSE=1 - -%: - dh $@ diff --git a/distribution/build-package.sh b/distribution/build-package.sh new file mode 100644 index 000000000..89e92e91b --- /dev/null +++ b/distribution/build-package.sh @@ -0,0 +1,7 @@ +# Note, this script is only used for local dev tests, this is not the script used for building the official sonarr package + +mkdir -p /${PWD}/../_output_debian + +docker build -f docker-build/Dockerfile -t sonarr-packager ./docker-build + +docker run --rm -v /${PWD}/../_output_linux:/data/sonarr_bin:ro -v /${PWD}:/data/build -v /${PWD}/../_output_debian:/data/output sonarr-packager diff --git a/distribution/debian/install.sh b/distribution/debian/install.sh new file mode 100644 index 000000000..803d7cf51 --- /dev/null +++ b/distribution/debian/install.sh @@ -0,0 +1,182 @@ +#!/bin/bash +### Description: Sonarr .NET Debian install +### Originally written for Radarr by: DoctorArr - doctorarr@the-rowlands.co.uk on 2021-10-01 v1.0 +### Updates for servarr suite made by Bakerboy448, DoctorArr, brightghost, aeramor and VP-EN +### Version v1.0.0 2023-12-29 - StevieTV - adapted from servarr script for Sonarr installs +### Version V1.0.1 2024-01-02 - StevieTV - remove UTF8-BOM +### Version V1.0.2 2024-01-03 - markus101 - Get user input from /dev/tty +### Version V1.0.3 2024-01-06 - StevieTV - exit script when it is ran from install directory + +### Boilerplate Warning +#THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +#EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +#MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND +#NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE +#LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION +#OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION +#WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + +scriptversion="1.0.3" +scriptdate="2024-01-06" + +set -euo pipefail + +echo "Running Sonarr Install Script - Version [$scriptversion] as of [$scriptdate]" + +# Am I root?, need root! + +if [ "$EUID" -ne 0 ]; then + echo "Please run as root." + exit +fi + +app="sonarr" +app_port="8989" +app_prereq="curl sqlite3 wget" +app_umask="0002" +branch="main" + +# Constants +### Update these variables as required for your specific instance +installdir="/opt" # {Update me if needed} Install Location +bindir="${installdir}/${app^}" # Full Path to Install Location +datadir="/var/lib/$app/" # {Update me if needed} AppData directory to use +app_bin=${app^} # Binary Name of the app + +# This script should not be ran from installdir, otherwise later in the script the extracted files will be removed before they can be moved to installdir. +if [ "$installdir" == "$(dirname -- "$( readlink -f -- "$0"; )")" ] || [ "$bindir" == "$(dirname -- "$( readlink -f -- "$0"; )")" ]; then + echo "You should not run this script from the intended install directory. The script will exit. Please re-run it from another directory" + exit +fi + +# Prompt User +read -r -p "What user should ${app^} run as? (Default: $app): " app_uid < /dev/tty +app_uid=$(echo "$app_uid" | tr -d ' ') +app_uid=${app_uid:-$app} +# Prompt Group +read -r -p "What group should ${app^} run as? (Default: media): " app_guid < /dev/tty +app_guid=$(echo "$app_guid" | tr -d ' ') +app_guid=${app_guid:-media} + +echo "This will install [${app^}] to [$bindir] and use [$datadir] for the AppData Directory" +echo "${app^} will run as the user [$app_uid] and group [$app_guid]. By continuing, you've confirmed that the selected user and group will have READ and WRITE access to your Media Library and Download Client Completed Download directories" +read -n 1 -r -s -p $'Press enter to continue or ctrl+c to exit...\n' < /dev/tty + +# Create User / Group as needed +if [ "$app_guid" != "$app_uid" ]; then + if ! getent group "$app_guid" >/dev/null; then + groupadd "$app_guid" + fi +fi +if ! getent passwd "$app_uid" >/dev/null; then + adduser --system --no-create-home --ingroup "$app_guid" "$app_uid" + echo "Created and added User [$app_uid] to Group [$app_guid]" +fi +if ! getent group "$app_guid" | grep -qw "$app_uid"; then + echo "User [$app_uid] did not exist in Group [$app_guid]" + usermod -a -G "$app_guid" "$app_uid" + echo "Added User [$app_uid] to Group [$app_guid]" +fi + +# Stop the App if running +if service --status-all | grep -Fq "$app"; then + systemctl stop "$app" + systemctl disable "$app".service + echo "Stopped existing $app" +fi + +# Create Appdata Directory + +# AppData +mkdir -p "$datadir" +chown -R "$app_uid":"$app_guid" "$datadir" +chmod 775 "$datadir" +echo "Directories created" +# Download and install the App + +# prerequisite packages +echo "" +echo "Installing pre-requisite Packages" +# shellcheck disable=SC2086 +apt update && apt install -y $app_prereq +echo "" +ARCH=$(dpkg --print-architecture) +# get arch +dlbase="https://services.sonarr.tv/v1/download/$branch/latest?version=4&os=linux" +case "$ARCH" in +"amd64") DLURL="${dlbase}&arch=x64" ;; +"armhf") DLURL="${dlbase}&arch=arm" ;; +"arm64") DLURL="${dlbase}&arch=arm64" ;; +*) + echo "Arch not supported" + exit 1 + ;; +esac +echo "" +echo "Removing previous tarballs" +# -f to Force so we fail if it doesn't exist +rm -f "${app^}".*.tar.gz +echo "" +echo "Downloading..." +wget --content-disposition "$DLURL" +tar -xvzf "${app^}".*.tar.gz +echo "" +echo "Installation files downloaded and extracted" + +# remove existing installs +echo "Removing existing installation" +rm -rf "$bindir" +echo "Installing..." +mv "${app^}" $installdir +chown "$app_uid":"$app_guid" -R "$bindir" +chmod 775 "$bindir" +rm -rf "${app^}.*.tar.gz" +# Ensure we check for an update in case user installs older version or different branch +touch "$datadir"/update_required +chown "$app_uid":"$app_guid" "$datadir"/update_required +echo "App Installed" +# Configure Autostart + +# Remove any previous app .service +echo "Removing old service file" +rm -rf /etc/systemd/system/"$app".service + +# Create app .service with correct user startup +echo "Creating service file" +cat </dev/null +[Unit] +Description=${app^} Daemon +After=syslog.target network.target +[Service] +User=$app_uid +Group=$app_guid +UMask=$app_umask +Type=simple +ExecStart=$bindir/$app_bin -nobrowser -data=$datadir +TimeoutStopSec=20 +KillMode=process +Restart=on-failure +[Install] +WantedBy=multi-user.target +EOF + +# Start the App +echo "Service file created. Attempting to start the app" +systemctl -q daemon-reload +systemctl enable --now -q "$app" + +# Finish Update/Installation +host=$(hostname -I) +ip_local=$(grep -oP '^\S*' <<<"$host") +echo "" +echo "Install complete" +sleep 10 +STATUS="$(systemctl is-active "$app")" +if [ "${STATUS}" = "active" ]; then + echo "Browse to http://$ip_local:$app_port for the ${app^} GUI" +else + echo "${app^} failed to start" +fi + +# Exit +exit 0 diff --git a/distribution/debian/sonarr.service b/distribution/debian/sonarr.service new file mode 100644 index 000000000..cd106de3d --- /dev/null +++ b/distribution/debian/sonarr.service @@ -0,0 +1,20 @@ +# This file is owned by the sonarr package, DO NOT MODIFY MANUALLY +# Instead use 'dpkg-reconfigure -plow sonarr' to modify User/Group/UMask/-data +# Or use systemd built-in override functionality using 'systemctl edit sonarr' +[Unit] +Description=Sonarr Daemon +After=network.target + +[Service] +User=sonarr +Group=sonarr +UMask=002 + +Type=simple +ExecStart=/opt/Sonarr/Sonarr -nobrowser -data=/var/lib/sonarr +TimeoutStopSec=20 +KillMode=process +Restart=on-failure + +[Install] +WantedBy=multi-user.target diff --git a/distribution/docker-build/Dockerfile b/distribution/docker-build/Dockerfile new file mode 100644 index 000000000..9cb387c3b --- /dev/null +++ b/distribution/docker-build/Dockerfile @@ -0,0 +1,32 @@ +FROM ubuntu:focal AS builder + +ENV DEBIAN_FRONTEND noninteractive +ENV MONO_VERSION 5.18 + +RUN apt-get update && \ + apt-get -y -o Dpkg::Options::="--force-confold" install --no-install-recommends \ + apt-transport-https \ + wget dirmngr gpg gpg-agent \ + # add-apt-repository for PPAs + software-properties-common && \ + rm -rf /var/lib/apt/lists/* + +RUN apt-key adv --keyserver hkp://keyserver.ubuntu.com:80 --recv-keys 3FA7E0328081BFF6A14DA29AA6A19B38D3D831EF && \ + echo "deb http://download.mono-project.com/repo/debian stable-focal main" > /etc/apt/sources.list.d/mono-official-stable.list && \ + apt-get update && apt-get install -y \ + devscripts build-essential tofrodos \ + dh-make dh-systemd \ + cli-common-dev \ + mono-complete \ + sqlite3 libcurl4 mediainfo +RUN apt-get upgrade -y + +RUN apt-cache policy mono-complete +RUN apt-cache policy cli-common-dev + +COPY debian-start.sh /debian-start.sh +RUN fromdos /debian-start.sh + +WORKDIR /data +VOLUME [ "/data/sonarr_bin", "/data/build", "/data/output" ] +CMD /debian-start.sh diff --git a/distribution/docker-build/debian-start.sh b/distribution/docker-build/debian-start.sh new file mode 100644 index 000000000..a1eff0638 --- /dev/null +++ b/distribution/docker-build/debian-start.sh @@ -0,0 +1,18 @@ +echo "Debian Build Dev bootstrap..." + +export TEST_OUTPUT=/data/output + +mkdir ${TEST_OUTPUT} + +mkdir /data/temp + +cp -rf /data/build/debian.sh /data/temp +cp -rf /data/build/debian /data/temp +cp -rf /data/sonarr_bin /data/temp/sonarr_bin + +cd /data/temp + +ls -al . + +fromdos debian.sh +sh debian.sh diff --git a/osx/Sonarr.app/Contents/Info.plist b/distribution/macOS/Sonarr.app/Contents/Info.plist similarity index 95% rename from osx/Sonarr.app/Contents/Info.plist rename to distribution/macOS/Sonarr.app/Contents/Info.plist index eeae50f41..4a6973050 100644 --- a/osx/Sonarr.app/Contents/Info.plist +++ b/distribution/macOS/Sonarr.app/Contents/Info.plist @@ -23,11 +23,11 @@ CFBundlePackageType APPL CFBundleShortVersionString - 2.0 + 4.0 CFBundleSignature xmmd CFBundleVersion - 2.0 + 4.0 NSAppleScriptEnabled YES diff --git a/distribution/macOS/Sonarr.app/Contents/Resources/sonarr.icns b/distribution/macOS/Sonarr.app/Contents/Resources/sonarr.icns new file mode 100644 index 000000000..a3c2e21ad Binary files /dev/null and b/distribution/macOS/Sonarr.app/Contents/Resources/sonarr.icns differ diff --git a/distribution/windows/setup/build.bat b/distribution/windows/setup/build.bat new file mode 100644 index 000000000..6c205089e --- /dev/null +++ b/distribution/windows/setup/build.bat @@ -0,0 +1,7 @@ +@REM SET SONARR_MAJOR_VERSION=4 +@REM SET SONARR_VERSION=4.0.0.5 +@REM SET BRANCH=develop +@REM SET FRAMEWORK=net6.0 +@REM SET RUNTIME=win-x64 + +inno\ISCC.exe sonarr.iss diff --git a/setup/inno/Default.isl b/distribution/windows/setup/inno/Default.isl similarity index 100% rename from setup/inno/Default.isl rename to distribution/windows/setup/inno/Default.isl diff --git a/setup/inno/ISCC.exe b/distribution/windows/setup/inno/ISCC.exe similarity index 100% rename from setup/inno/ISCC.exe rename to distribution/windows/setup/inno/ISCC.exe diff --git a/setup/inno/ISCmplr.dll b/distribution/windows/setup/inno/ISCmplr.dll similarity index 100% rename from setup/inno/ISCmplr.dll rename to distribution/windows/setup/inno/ISCmplr.dll diff --git a/setup/inno/ISPP.dll b/distribution/windows/setup/inno/ISPP.dll similarity index 100% rename from setup/inno/ISPP.dll rename to distribution/windows/setup/inno/ISPP.dll diff --git a/setup/inno/Setup.e32 b/distribution/windows/setup/inno/Setup.e32 similarity index 100% rename from setup/inno/Setup.e32 rename to distribution/windows/setup/inno/Setup.e32 diff --git a/setup/inno/SetupLdr.e32 b/distribution/windows/setup/inno/SetupLdr.e32 similarity index 100% rename from setup/inno/SetupLdr.e32 rename to distribution/windows/setup/inno/SetupLdr.e32 diff --git a/setup/inno/WizModernImage.bmp b/distribution/windows/setup/inno/WizModernImage.bmp similarity index 100% rename from setup/inno/WizModernImage.bmp rename to distribution/windows/setup/inno/WizModernImage.bmp diff --git a/setup/inno/WizModernSmallImage.bmp b/distribution/windows/setup/inno/WizModernSmallImage.bmp similarity index 100% rename from setup/inno/WizModernSmallImage.bmp rename to distribution/windows/setup/inno/WizModernSmallImage.bmp diff --git a/setup/inno/islzma.dll b/distribution/windows/setup/inno/islzma.dll similarity index 100% rename from setup/inno/islzma.dll rename to distribution/windows/setup/inno/islzma.dll diff --git a/distribution/windows/setup/sonarr.iss b/distribution/windows/setup/sonarr.iss new file mode 100644 index 000000000..8401bdea9 --- /dev/null +++ b/distribution/windows/setup/sonarr.iss @@ -0,0 +1,86 @@ +; Script generated by the Inno Setup Script Wizard. +; SEE THE DOCUMENTATION FOR DETAILS ON CREATING INNO SETUP SCRIPT FILES! + +#define AppName "Sonarr" +#define AppPublisher "Team Sonarr" +#define AppURL "https://sonarr.tv/" +#define ForumsURL "https://forums.sonarr.tv/" +#define AppExeName "Sonarr.exe" +#define BuildNumber "4.0" +#define BuildNumber GetEnv('SONARR_VERSION') +#define MajorVersion GetEnv('SONARR_MAJOR_VERSION') +#define BranchName GetEnv('BRANCH') +#define Framework GetEnv('FRAMEWORK') +#define Runtime GetEnv('RUNTIME') + +[Setup] +; NOTE: The value of AppId uniquely identifies this appl ication. +; Do not use the same AppId value in installers for other applications. +; (To generate a new GUID, click Tools | Generate GUID inside the IDE.) +AppId={{56C1065D-3523-4025-B76D-6F73F67F7F71} +AppName={#AppName} +AppVersion={#MajorVersion} +AppPublisher={#AppPublisher} +AppPublisherURL={#AppURL} +AppSupportURL={#ForumsURL} +AppUpdatesURL={#AppURL} +UsePreviousAppDir=no +DefaultDirName={commonappdata}\Sonarr\bin +DisableDirPage=yes +DefaultGroupName={#AppName} +DisableProgramGroupPage=yes +OutputBaseFilename=Sonarr.{#BranchName}.{#BuildNumber}.{#Runtime}-installer +SolidCompression=yes +AppCopyright=Creative Commons 3.0 License +AllowUNCPath=False +UninstallDisplayIcon={app}\Sonarr.exe +DisableReadyPage=True +CompressionThreads=2 +Compression=lzma2/normal +AppContact={#ForumsURL} +VersionInfoVersion={#MajorVersion} +SetupLogging=yes +OutputDir="..\..\..\_artifacts" +AppverName={#AppName} + +[Languages] +Name: "english"; MessagesFile: "compiler:Default.isl" + +[Tasks] +Name: "desktopIcon"; Description: "{cm:CreateDesktopIcon}" +Name: "windowsService"; Description: "Install Windows Service (Starts when the computer starts as the LocalService user, you will need to change the user to access network shares)"; GroupDescription: "Start automatically"; Flags: exclusive unchecked +Name: "startupShortcut"; Description: "Create shortcut in Startup folder (Starts when you log into Windows)"; GroupDescription: "Start automatically"; Flags: exclusive +Name: "none"; Description: "Do not start automatically"; GroupDescription: "Start automatically"; Flags: exclusive unchecked + +[Files] +Source: "..\..\..\_output\{#Runtime}\{#Framework}\Sonarr\Sonarr.exe"; DestDir: "{app}"; Flags: ignoreversion +Source: "..\..\..\_output\{#Runtime}\{#Framework}\Sonarr\*"; Excludes: "Sonarr.Update"; DestDir: "{app}"; Flags: ignoreversion recursesubdirs createallsubdirs +; NOTE: Don't use "Flags: ignoreversion" on any shared system files + +[Icons] +Name: "{group}\{#AppName}"; Filename: "{app}\{#AppExeName}"; Parameters: "/icon" +Name: "{commondesktop}\{#AppName}"; Filename: "{app}\{#AppExeName}"; Parameters: "/icon"; Tasks: desktopIcon +Name: "{userstartup}\{#AppName}"; Filename: "{app}\Sonarr.exe"; WorkingDir: "{app}"; Tasks: startupShortcut + +[InstallDelete] +Name: "{commonappdata}\NzbDrone\bin"; Type: filesandordirs +Name: "{app}"; Type: filesandordirs + +[Run] +Filename: "{app}\Sonarr.Console.exe"; StatusMsg: "Removing previous Windows Service"; Parameters: "/u /exitimmediately"; Flags: runhidden waituntilterminated; +Filename: "{app}\Sonarr.Console.exe"; Description: "Enable Access from Other Devices"; StatusMsg: "Enabling Remote access"; Parameters: "/registerurl /exitimmediately"; Flags: postinstall runascurrentuser runhidden waituntilterminated; Tasks: startupShortcut none; +Filename: "{app}\Sonarr.Console.exe"; StatusMsg: "Installing Windows Service"; Parameters: "/i /exitimmediately"; Flags: runhidden waituntilterminated; Tasks: windowsService +Filename: "{app}\Sonarr.exe"; Description: "Open Sonarr Web UI"; Flags: postinstall skipifsilent nowait; Tasks: windowsService; +Filename: "{app}\Sonarr.exe"; Description: "Start Sonarr"; Flags: postinstall skipifsilent nowait; Tasks: startupShortcut none; + +[UninstallRun] +Filename: "{app}\Sonarr.Console.exe"; Parameters: "/u"; Flags: runhidden waituntilterminated skipifdoesntexist + +[Code] +function PrepareToInstall(var NeedsRestart: Boolean): String; +var + ResultCode: Integer; +begin + Exec('net', 'stop nzbdrone', '', 0, ewWaitUntilTerminated, ResultCode) + Exec('sc', 'delete nzbdrone', '', 0, ewWaitUntilTerminated, ResultCode) +end; diff --git a/docker/tests/mono/complete/Dockerfile b/docker/tests/mono/complete/Dockerfile new file mode 100644 index 000000000..272aed8ca --- /dev/null +++ b/docker/tests/mono/complete/Dockerfile @@ -0,0 +1,25 @@ +FROM ubuntu:xenial + +ENV DEBIAN_FRONTEND noninteractive +ARG MONO_VERSION=5.20 +ARG MONO_URL=stable-xenial/snapshots/$MONO_VERSION + +RUN apt-key adv --keyserver hkp://keyserver.ubuntu.com:80 --recv-keys 3FA7E0328081BFF6A14DA29AA6A19B38D3D831EF && \ + echo "deb http://download.mono-project.com/repo/debian $MONO_URL main" > /etc/apt/sources.list.d/mono-official-stable.list && \ + apt-get update && apt-get install -y \ + tofrodos tzdata \ + mono-complete \ + sqlite3 mediainfo \ + && rm -rf /var/lib/apt/lists/* + +COPY startup.sh /startup.sh +RUN fromdos /startup.sh + +WORKDIR /data/ +VOLUME ["/data/_tests_linux", "/data/_output_linux", "/data/_tests_results"] + +RUN groupadd sonarrtst -g 4020 && useradd sonarrtst -u 4021 -g 4020 -m -s /bin/bash +USER sonarrtst + +CMD bash /startup.sh + diff --git a/docker/tests/mono/sonarr/Dockerfile b/docker/tests/mono/sonarr/Dockerfile new file mode 100644 index 000000000..f2ec42a9e --- /dev/null +++ b/docker/tests/mono/sonarr/Dockerfile @@ -0,0 +1,32 @@ +FROM ubuntu:xenial + +ENV DEBIAN_FRONTEND noninteractive +ARG MONO_VERSION=5.20 +ARG MONO_URL=stable-xenial/snapshots/$MONO_VERSION + +RUN apt-key adv --keyserver hkp://keyserver.ubuntu.com:80 --recv-keys 3FA7E0328081BFF6A14DA29AA6A19B38D3D831EF && \ + echo "deb http://download.mono-project.com/repo/debian $MONO_URL main" > /etc/apt/sources.list.d/mono-official-stable.list && \ + apt-key adv --keyserver hkp://keyserver.ubuntu.com:80 --recv-keys 2009837CBFFD68F45BC180471F4F90DE2A9B4BF8 && \ + echo "deb http://apt.sonarr.tv/ubuntu xenial main" > /etc/apt/sources.list.d/sonarr.list && \ + apt-get update && apt-get install -y \ + tofrodos tzdata \ + sonarr \ + sqlite3 mediainfo \ + && rm -rf /var/lib/apt/lists/* + +RUN apt-get update && apt-get install -y \ + libmono-system-runtime4.0-cil \ + libmono-system-net-http4.0-cil \ + && rm -rf /var/lib/apt/lists/* + +COPY startup.sh /startup.sh +RUN fromdos /startup.sh + +WORKDIR /data/ +VOLUME ["/data/_tests_linux", "/data/_output_linux", "/data/_tests_results"] + +RUN groupadd sonarrtst -g 4020 && useradd sonarrtst -u 4021 -g 4020 -m -s /bin/bash +USER sonarrtst + +CMD bash /startup.sh + diff --git a/docker/tests/mono/startup.sh b/docker/tests/mono/startup.sh new file mode 100644 index 000000000..30b5c43f1 --- /dev/null +++ b/docker/tests/mono/startup.sh @@ -0,0 +1,15 @@ +echo "Preparing Test..." +mkdir -p /data/test +cp -r /data/_tests_linux/* /data/test/ +cp -r /data/_output_linux /data/test/bin + +cd /data/test + +runTest() +{ + bash test.sh Linux $1 + cp TestResult.xml /data/_tests_results/TestResult_$1.xml +} + +runTest Integration +runTest Unit \ No newline at end of file diff --git a/docker/tests/run-all.sh b/docker/tests/run-all.sh new file mode 100644 index 000000000..21301e40f --- /dev/null +++ b/docker/tests/run-all.sh @@ -0,0 +1,121 @@ + +opt_parallel= +opt_version= +opt_mode=both +while getopts 'pv:m:r?h' c +do + case $c in + p) opt_parallel=1 ;; + v) opt_version=$OPTARG ;; + m) opt_mode=$OPTARG ;; + r) opt_report=1 ;; + ?|h) printf "Usage: %s [-p] [-v mono-ver] [-m sonarr|complete]\n" $0 + printf " -p run parallel\n" + printf " -v run specified mono version\n" + printf " -m run only mono-'complete' or 'sonarr' package variants\n" + printf " -r only report\n" + exit 2 + esac +done +# NOTE: +# each container has a 1gb tmpfs mounted since it greatly speeds up the normally intensive db operations +# make sure that the docker host has enough memory to handle about ~300 MB per container, so 2-3 GB total +# excess goes to the swap and will slow down the entire system + +MONO_VERSIONS="" + +# Future versions +MONO_VERSIONS="$MONO_VERSIONS 6.10=preview-xenial" + +# Semi-Supported versions +MONO_VERSIONS="$MONO_VERSIONS 6.8 6.6 6.4 6.0" + +# Supported versions +MONO_VERSIONS="$MONO_VERSIONS 5.20 5.18" + +# Legacy unsupported versions (but appear to work) +MONO_VERSIONS="$MONO_VERSIONS 5.16 5.14 5.12" + +# Legacy unsupported versions +MONO_VERSIONS="$MONO_VERSIONS 5.10 5.8 5.4 5.0" +#MONO_VERSIONS="$MONO_VERSIONS 4.8=stable-wheezy/snapshots/4.8" + +if [ "$opt_version" != "" ]; then + MONO_VERSIONS="$opt_version" +fi + +mkdir -p ${PWD}/../../_tests_results + +prepOne() { + local MONO_VERSION_PAIR=$1 + + MONO_VERSION_SPLIT=(${MONO_VERSION_PAIR//=/ }) + MONO_VERSION=${MONO_VERSION_SPLIT[0]} + MONO_URL=${MONO_VERSION_SPLIT[1]:-"stable-xenial/snapshots/$MONO_VERSION"} + + echo "Building Test Docker for mono $MONO_VERSION" + + if [ "$opt_mode" != "sonarr" ]; then + docker build -t sonarr-test-$MONO_VERSION --build-arg MONO_VERSION=$MONO_VERSION --build-arg MONO_URL=$MONO_URL --file mono/complete/Dockerfile mono + fi + + if [ "$opt_mode" != "complete" ] && [ "$MONO_VERSION" != "5.0" ]; then + docker build -t sonarr-test-$MONO_VERSION-sonarr --build-arg MONO_VERSION=$MONO_VERSION --build-arg MONO_URL=$MONO_URL --file mono/sonarr/Dockerfile mono + fi +} + +runOne() { + local MONO_VERSION_PAIR=$1 + + MONO_VERSION_SPLIT=(${MONO_VERSION_PAIR//=/ }) + MONO_VERSION=${MONO_VERSION_SPLIT[0]} + + echo "Running Test Docker for mono $MONO_VERSION" + + if [ "$opt_mode" != "sonarr" ]; then + dockerArgs="--rm" + dockerArgs="$dockerArgs -v /${PWD}/../../_tests_linux:/data/_tests_linux:ro" + dockerArgs="$dockerArgs -v /${PWD}/../../_output_linux:/data/_output_linux:ro" + dockerArgs="$dockerArgs -v /${PWD}/../../_tests_results/mono-$MONO_VERSION:/data/_tests_results" + dockerArgs="$dockerArgs --mount type=tmpfs,destination=//data/test,tmpfs-size=1g" + docker run $dockerArgs sonarr-test-$MONO_VERSION + fi + + if [ "$opt_mode" != "complete" ] && [ "$MONO_VERSION" != "5.0" ]; then + dockerArgs="--rm" + dockerArgs="$dockerArgs -v /${PWD}/../../_tests_linux:/data/_tests_linux:ro" + dockerArgs="$dockerArgs -v /${PWD}/../../_output_linux:/data/_output_linux:ro" + dockerArgs="$dockerArgs -v /${PWD}/../../_tests_results/mono-$MONO_VERSION-sonarr:/data/_tests_results" + dockerArgs="$dockerArgs --mount type=tmpfs,destination=//data/test,tmpfs-size=1g" + docker run $dockerArgs sonarr-test-$MONO_VERSION-sonarr + fi + + echo "Finished Test Docker for mono $MONO_VERSION" +} + +if [ "$opt_report" != "1" ]; then + + if [ "$opt_parallel" == "1" ]; then + for MONO_VERSION_PAIR in $MONO_VERSIONS; do + prepOne "$MONO_VERSION_PAIR" + done + fi + + for MONO_VERSION_PAIR in $MONO_VERSIONS; do + if [ "$opt_parallel" == "1" ]; then + runOne "$MONO_VERSION_PAIR" & + else + prepOne "$MONO_VERSION_PAIR" + runOne "$MONO_VERSION_PAIR" + fi + done + + if [ "$opt_parallel" == "1" ]; then + echo "Waiting for all runs to finish" + wait + echo "Finished all runs" + fi + +fi + +grep " dirent.isDirectory()) + .map((dirent) => dirent.name) + .join('|'); + +module.exports = { + root: true, + + parser: '@babel/eslint-parser', + + env: { + browser: true, + commonjs: true, + node: true, + es6: true + }, + + globals: { + expect: false, + chai: false, + sinon: false, + JSX: true + }, + + parserOptions: { + ecmaVersion: 6, + sourceType: 'module', + babelOptions: { + configFile: `${frontendFolder}/babel.config.js` + }, + ecmaFeatures: { + modules: true, + impliedStrict: true + } + }, + + plugins: [ + 'filenames', + 'react', + 'react-hooks', + 'simple-import-sort', + 'import', + '@typescript-eslint', + 'prettier' + ], + + settings: { + react: { + version: 'detect' + } + }, + + rules: { + 'filenames/match-exported': ['error'], + + // ECMAScript 6 + + 'arrow-body-style': [0], + 'arrow-parens': ['error', 'always'], + 'arrow-spacing': ['error', { before: true, after: true }], + 'constructor-super': 'error', + 'generator-star-spacing': 'off', + 'no-class-assign': 'error', + 'no-confusing-arrow': 'error', + 'no-const-assign': 'error', + 'no-dupe-class-members': 'error', + 'no-duplicate-imports': 'error', + 'no-new-symbol': 'error', + 'no-this-before-super': 'error', + 'no-useless-escape': 'error', + 'no-useless-computed-key': 'error', + 'no-useless-constructor': 'error', + 'no-var': 'warn', + 'object-shorthand': ['error', 'properties'], + 'prefer-arrow-callback': 'error', + 'prefer-const': 'warn', + 'prefer-reflect': 'off', + 'prefer-rest-params': 'off', + 'prefer-spread': 'warn', + 'prefer-template': 'error', + 'require-yield': 'off', + 'template-curly-spacing': ['error', 'never'], + 'yield-star-spacing': 'off', + + // Possible Errors + + 'comma-dangle': 'error', + 'no-cond-assign': 'error', + 'no-console': 'off', + 'no-constant-condition': 'warn', + 'no-control-regex': 'error', + 'no-debugger': 'off', + 'no-dupe-args': 'error', + 'no-dupe-keys': 'error', + 'no-duplicate-case': 'error', + 'no-empty': 'warn', + 'no-empty-character-class': 'error', + 'no-ex-assign': 'error', + 'no-extra-boolean-cast': 'error', + 'no-extra-parens': ['error', 'functions'], + 'no-extra-semi': 'error', + 'no-func-assign': 'error', + 'no-inner-declarations': 'error', + 'no-invalid-regexp': 'error', + 'no-irregular-whitespace': 'error', + 'no-negated-in-lhs': 'error', + 'no-obj-calls': 'error', + 'no-regex-spaces': 'error', + 'no-sparse-arrays': 'error', + 'no-unexpected-multiline': 'error', + 'no-unreachable': 'warn', + 'no-unsafe-finally': 'error', + 'use-isnan': 'error', + 'valid-jsdoc': 'off', + 'valid-typeof': 'error', + + // Best Practices + + 'accessor-pairs': 'off', + 'array-callback-return': 'warn', + 'block-scoped-var': 'warn', + 'consistent-return': 'off', + curly: 'error', + 'default-case': 'error', + 'dot-location': ['error', 'property'], + 'dot-notation': 'error', + eqeqeq: ['error', 'smart'], + 'guard-for-in': 'error', + 'no-alert': 'warn', + 'no-caller': 'error', + 'no-case-declarations': 'error', + 'no-div-regex': 'error', + 'no-else-return': 'error', + 'no-empty-function': ['error', { allow: ['arrowFunctions'] }], + 'no-empty-pattern': 'error', + 'no-eval': 'error', + 'no-extend-native': 'error', + 'no-extra-bind': 'error', + 'no-fallthrough': 'error', + 'no-floating-decimal': 'error', + 'no-implicit-coercion': ['error', { + boolean: false, + number: true, + string: true, + allow: [/* "!!", "~", "*", "+" */] + }], + 'no-implicit-globals': 'error', + 'no-implied-eval': 'error', + 'no-invalid-this': 'off', + 'no-iterator': 'error', + 'no-labels': 'error', + 'no-lone-blocks': 'error', + 'no-loop-func': 'error', + 'no-magic-numbers': ['off', { ignoreArrayIndexes: true, ignore: [0, 1] }], + 'no-multi-spaces': 'error', + 'no-multi-str': 'error', + 'no-native-reassign': ['error', { exceptions: ['console'] }], + 'no-new': 'off', + 'no-new-func': 'error', + 'no-new-wrappers': 'error', + 'no-octal': 'error', + 'no-octal-escape': 'error', + 'no-param-reassign': 'off', + 'no-process-env': 'off', + 'no-proto': 'error', + 'no-redeclare': 'error', + 'no-return-assign': 'warn', + 'no-script-url': 'error', + 'no-self-assign': 'error', + 'no-self-compare': 'error', + 'no-sequences': 'error', + 'no-throw-literal': 'error', + 'no-unmodified-loop-condition': 'error', + 'no-unused-expressions': 'error', + 'no-unused-labels': 'error', + 'no-useless-call': 'error', + 'no-useless-concat': 'error', + 'no-void': 'error', + 'no-warning-comments': 'off', + 'no-with': 'error', + radix: ['error', 'as-needed'], + 'vars-on-top': 'off', + 'wrap-iife': ['error', 'inside'], + yoda: 'error', + + // Strict Mode + + strict: ['error', 'never'], + + // Variables + + 'init-declarations': ['error', 'always'], + 'no-catch-shadow': 'error', + 'no-delete-var': 'error', + 'no-label-var': 'error', + 'no-restricted-globals': 'off', + 'no-shadow': 'error', + 'no-shadow-restricted-names': 'error', + 'no-undef': 'error', + 'no-undef-init': 'off', + 'no-undefined': 'off', + 'no-unused-vars': ['error', { args: 'none', ignoreRestSiblings: true }], + + // Node.js and CommonJS + + 'callback-return': 'warn', + 'global-require': 'error', + 'handle-callback-err': 'warn', + 'no-mixed-requires': 'error', + 'no-new-require': 'error', + 'no-path-concat': 'error', + 'no-process-exit': 'error', + + // Stylistic Issues + + 'array-bracket-spacing': ['error', 'never'], + 'block-spacing': ['error', 'always'], + 'brace-style': ['error', '1tbs', { allowSingleLine: false }], + camelcase: 'off', + 'comma-spacing': ['error', { before: false, after: true }], + 'comma-style': ['error', 'last'], + 'computed-property-spacing': ['error', 'never'], + 'consistent-this': ['error', 'self'], + 'eol-last': 'error', + 'func-names': 'off', + 'func-style': ['error', 'declaration', { allowArrowFunctions: true }], + indent: ['error', 2, { SwitchCase: 1 }], + 'key-spacing': ['error', { beforeColon: false, afterColon: true }], + 'keyword-spacing': ['error', { before: true, after: true }], + 'lines-around-comment': ['error', { beforeBlockComment: true, afterBlockComment: false }], + 'max-depth': ['error', { maximum: 5 }], + 'max-nested-callbacks': ['error', 4], + 'max-statements': 'off', + 'max-statements-per-line': ['error', { max: 1 }], + 'new-cap': ['error', { capIsNewExceptions: ['$.Deferred', 'DragDropContext', 'DragLayer', 'DragSource', 'DropTarget'] }], + 'new-parens': 'error', + 'newline-after-var': 'off', + 'newline-before-return': 'off', + 'newline-per-chained-call': 'off', + 'no-array-constructor': 'error', + 'no-bitwise': 'error', + 'no-continue': 'error', + 'no-inline-comments': 'off', + 'no-lonely-if': 'warn', + 'no-mixed-spaces-and-tabs': 'error', + 'no-multiple-empty-lines': ['error', { max: 1 }], + 'no-negated-condition': 'warn', + 'no-nested-ternary': 'error', + 'no-new-object': 'error', + 'no-plusplus': 'off', + 'no-restricted-syntax': 'off', + 'no-spaced-func': 'error', + 'no-ternary': 'off', + 'no-trailing-spaces': 'error', + 'no-underscore-dangle': ['error', { allowAfterThis: true }], + 'no-unneeded-ternary': 'error', + 'no-whitespace-before-property': 'error', + 'object-curly-spacing': ['error', 'always'], + 'one-var': ['error', 'never'], + 'one-var-declaration-per-line': ['error', 'always'], + 'operator-assignment': ['off', 'never'], + 'operator-linebreak': ['error', 'after'], + 'quote-props': ['error', 'as-needed'], + quotes: ['error', 'single'], + 'require-jsdoc': 'off', + semi: 'error', + 'semi-spacing': ['error', { before: false, after: true }], + 'sort-vars': 'off', + 'space-before-blocks': ['error', 'always'], + 'space-before-function-paren': ['error', 'never'], + 'space-in-parens': 'off', + 'space-infix-ops': 'off', + 'space-unary-ops': 'off', + 'spaced-comment': 'error', + 'wrap-regex': 'error', + + // ImportSort + + 'simple-import-sort/imports': 'error', + 'import/newline-after-import': 'error', + + // React + + 'react/jsx-boolean-value': [2, 'always'], + 'react/jsx-uses-vars': 2, + 'react/jsx-closing-bracket-location': 2, + 'react/jsx-tag-spacing': ['error'], + 'react/jsx-curly-spacing': [2, 'never'], + 'react/jsx-equals-spacing': [2, 'never'], + 'react/jsx-indent-props': [2, 2], + 'react/jsx-indent': [2, 2, { indentLogicalExpressions: true }], + 'react/jsx-key': 2, + 'react/jsx-no-bind': [2, { allowArrowFunctions: true }], + 'react/jsx-no-duplicate-props': [2, { ignoreCase: true }], + 'react/jsx-max-props-per-line': [2, { maximum: 2 }], + 'react/jsx-handler-names': [2, { eventHandlerPrefix: '(on|dispatch)', eventHandlerPropPrefix: 'on' }], + 'react/jsx-no-undef': 2, + 'react/jsx-pascal-case': 2, + 'react/jsx-uses-react': 2, + // Explicitly disabled in case we want to enable them again + 'react/no-did-mount-set-state': 0, + 'react/no-did-update-set-state': 0, + 'react/no-direct-mutation-state': 2, + 'react/no-multi-comp': [2, { ignoreStateless: true }], + 'react/no-unknown-property': 2, + 'react/prefer-es6-class': 2, + 'react/prop-types': 2, + 'react/react-in-jsx-scope': 2, + 'react/self-closing-comp': 2, + 'react/sort-comp': 2, + 'react/jsx-wrap-multilines': 2, + 'react-hooks/rules-of-hooks': 'error', + 'react-hooks/exhaustive-deps': 'error' + }, + overrides: [ + { + files: [ + '*.js' + ], + rules: { + 'simple-import-sort/imports': [ + 'error', + { + groups: [ + // Packages + // Absolute Paths + // Relative Paths + // Css + ['^@?\\w', `^(${dirs})(/.*|$)`, '^\\.', '^\\..*css$'] + ] + } + ] + } + }, + { + files: [ + '*.ts', + '*.tsx' + ], + + parser: '@typescript-eslint/parser', + parserOptions: { + project: './tsconfig.json' + }, + + extends: [ + 'prettier' + ], + + rules: Object.assign(typescriptEslintRecommended.rules, { + '@typescript-eslint/no-unused-vars': [ + 'error', + { + args: 'after-used', + argsIgnorePattern: '^_', + caughtErrorsIgnorePattern: '^_', + destructuredArrayIgnorePattern: '^_', + varsIgnorePattern: '^_', + ignoreRestSiblings: true + + } + ], + '@typescript-eslint/explicit-function-return-type': 'off', + 'no-shadow': 'off', + 'prettier/prettier': 'error', + 'simple-import-sort/imports': [ + 'error', + { + groups: [ + // Packages + // Absolute Paths + // Relative Paths + // Css + ['^@?\\w', `^(${dirs})(/.*|$)`, '^\\.', '^\\..*css$'] + ] + } + ], + + // React Hooks + 'react-hooks/rules-of-hooks': 'error', + 'react-hooks/exhaustive-deps': 'error', + + // React + 'react/function-component-definition': 'error', + 'react/hook-use-state': 'error', + 'react/jsx-boolean-value': ['error', 'always'], + 'react/jsx-curly-brace-presence': [ + 'error', + { props: 'never', children: 'never' } + ], + 'react/jsx-fragments': 'error', + 'react/jsx-handler-names': [ + 'error', + { + eventHandlerPrefix: 'on', + eventHandlerPropPrefix: 'on' + } + ], + 'react/jsx-no-bind': ['error', { ignoreRefs: true }], + 'react/jsx-no-useless-fragment': ['error', { allowExpressions: true }], + 'react/jsx-pascal-case': ['error', { allowAllCaps: true }], + 'react/jsx-sort-props': [ + 'error', + { + callbacksLast: true, + noSortAlphabetically: true, + reservedFirst: true + } + ], + 'react/prop-types': 'off', + 'react/self-closing-comp': 'error' + }) + }, + { + files: [ + '*.css.d.ts' + ], + rules: { + 'filenames/match-exported': 'off', + 'init-declarations': 'off', + 'prettier/prettier': 'off' + } + } + ] +}; diff --git a/frontend/.prettierignore b/frontend/.prettierignore new file mode 100644 index 000000000..3e6367c54 --- /dev/null +++ b/frontend/.prettierignore @@ -0,0 +1,10 @@ +# Ignore everything recursively +* + +# But not the .ts files +!*.ts* + +*css.d.ts + +# Check subdirectories too +!*/ diff --git a/frontend/.prettierrc.json b/frontend/.prettierrc.json new file mode 100644 index 000000000..2f91ee691 --- /dev/null +++ b/frontend/.prettierrc.json @@ -0,0 +1,6 @@ +{ + "arrowParens": "always", + "endOfLine": "auto", + "singleQuote": true, + "trailingComma": "es5" +} diff --git a/frontend/.stylelintrc b/frontend/.stylelintrc new file mode 100644 index 000000000..f19357a4c --- /dev/null +++ b/frontend/.stylelintrc @@ -0,0 +1,326 @@ +{ + "plugins": [ + "stylelint-order" + ], + "ignoreFiles": [ + "frontend/src/Styles/scaffolding.css", + "**/*.js" + ], + "rules": { + "at-rule-empty-line-before": [ + "always", + { + "except": [ + "inside-block" + ] + } + ], + "at-rule-no-unknown": [ + true, + { + "ignoreAtRules": [ + "/^add\\-mixin$/", + "/^define\\-mixin$/" + ] + } + ], + "at-rule-no-vendor-prefix": true, + "block-no-empty": true, + "color-hex-length": "short", + "color-named": "never", + "color-no-invalid-hex": true, + "comment-whitespace-inside": "always", + "declaration-block-no-duplicate-properties": [ + true, + { + "ignoreProperties": [ + "composes" + ] + } + ], + "declaration-block-no-redundant-longhand-properties": true, + "declaration-block-no-shorthand-property-overrides": true, + "declaration-block-single-line-max-declarations": 1, + "font-family-name-quotes": "always-unless-keyword", + "function-calc-no-unspaced-operator": true, + "function-linear-gradient-no-nonstandard-direction": true, + "function-name-case": "lower", + "function-url-quotes": "always", + "function-url-scheme-disallowed-list": [ + "data" + ], + "keyframe-declaration-no-important": true, + "length-zero-no-unit": true, + "max-nesting-depth": 2, + "media-feature-name-no-vendor-prefix": true, + "no-empty-source": true, + "no-invalid-double-slash-comments": true, + "order/order": [ + "custom-properties", + "dollar-variables", + { + "hasBlock": false, + "name": "add-mixin", + "type": "at-rule" + }, + "declarations", + "rules", + "at-rules" + ], + "order/properties-order": [ + { + "emptyLineBefore": "always", + "properties": [ + "composes" + ] + }, + { + "emptyLineBefore": "always", + "properties": [ + "position", + "top", + "right", + "bottom", + "left", + "inset", + "z-index", + "display", + "visibility", + "align-content", + "align-items", + "align-self", + "justify-content", + "flex", + "flex-direction", + "flex-order", + "flex-pack", + "flex-align", + "flex-grow", + "flex-shrink", + "flex-basis", + "flex-wrap", + "flex-flow", + "float", + "clear", + "overflow", + "overflow-x", + "overflow-y", + "-webkit-overflow-scrolling", + "clip", + "box-sizing", + "margin", + "margin-top", + "margin-right", + "margin-bottom", + "margin-left", + "padding", + "padding-top", + "padding-right", + "padding-bottom", + "padding-left", + "min-width", + "min-height", + "max-width", + "max-height", + "width", + "height", + "outline", + "outline-width", + "outline-style", + "outline-color", + "outline-offset", + "border", + "border-spacing", + "border-collapse", + "border-width", + "border-style", + "border-color", + "border-top", + "border-top-width", + "border-top-style", + "border-top-color", + "border-right", + "border-right-width", + "border-right-style", + "border-right-color", + "border-bottom", + "border-bottom-width", + "border-bottom-style", + "border-bottom-color", + "border-left", + "border-left-width", + "border-left-style", + "border-left-color", + "border-radius", + "border-top-left-radius", + "border-top-right-radius", + "border-bottom-right-radius", + "border-bottom-left-radius", + "border-image", + "border-image-source", + "border-image-slice", + "border-image-width", + "border-image-outset", + "border-image-repeat", + "border-top-image", + "border-right-image", + "border-bottom-image", + "border-left-image", + "border-corner-image", + "border-top-left-image", + "border-top-right-image", + "border-bottom-right-image", + "border-bottom-left-image", + "background", + "background-color", + "background-image", + "background-attachment", + "background-position", + "background-position-x", + "background-position-y", + "background-clip", + "background-origin", + "background-size", + "background-repeat", + "box-decoration-break", + "box-shadow", + "color", + "table-layout", + "caption-side", + "empty-cells", + "list-style", + "list-style-position", + "list-style-type", + "list-style-image", + "quotes", + "content", + "counter-increment", + "counter-reset", + "-ms-writing-mode", + "vertical-align", + "text-align", + "text-align-last", + "text-decoration", + "text-emphasis", + "text-emphasis-position", + "text-emphasis-style", + "text-emphasis-color", + "text-indent", + "text-justify", + "text-outline", + "text-transform", + "text-wrap", + "text-overflow", + "text-overflow-ellipsis", + "text-overflow-mode", + "text-shadow", + "white-space", + "word-spacing", + "word-wrap", + "word-break", + "tab-size", + "hyphens", + "letter-spacing", + "font", + "font-weight", + "font-style", + "font-variant", + "font-size-adjust", + "font-stretch", + "font-size", + "font-family", + "font-smoothing", + "-moz-osx-font-smoothing", + "-webkit-font-smoothing", + "src", + "line-height", + "opacity", + "filter", + "resize", + "cursor", + "appearance", + "nav-index", + "nav-up", + "nav-right", + "nav-down", + "nav-left", + "transition", + "transition-delay", + "transition-timing-function", + "transition-duration", + "transition-property", + "transform", + "transform-origin", + "transform-style", + "backface-visibility", + "animation", + "animation-name", + "animation-duration", + "animation-play-state", + "animation-timing-function", + "animation-delay", + "animation-iteration-count", + "animation-direction", + "animation-fill-mode", + "pointer-events", + "user-select", + "touch-action", + "-webkit-tap-highlight-color", + "unicode-bidi", + "direction", + "columns", + "column-span", + "column-width", + "column-count", + "column-fill", + "column-gap", + "column-rule", + "column-rule-width", + "column-rule-style", + "column-rule-color", + "break-before", + "break-inside", + "break-after", + "page-break-before", + "page-break-inside", + "page-break-after", + "orphans", + "widows", + "zoom", + "max-zoom", + "min-zoom", + "user-zoom", + "orientation" + ] + } + ], + "property-no-vendor-prefix": true, + "rule-empty-line-before": [ + "always", + { + "except": [ + "first-nested" + ], + "ignore": [ + "after-comment" + ] + } + ], + "selector-attribute-quotes": "never", + "selector-class-pattern": "^[A-Za-z0-9]+$", + "selector-max-attribute": 0, + "selector-max-class": 3, + "selector-max-compound-selectors": 3, + "selector-max-id": 0, + "selector-max-universal": 0, + "selector-pseudo-element-colon-notation": "double", + "selector-pseudo-element-no-unknown": true, + "selector-type-case": "lower", + "selector-type-no-unknown": true, + "shorthand-property-no-redundant-values": true, + "string-no-newline": true, + "time-min-milliseconds": 100, + "unit-no-unknown": true, + "value-no-vendor-prefix": true + } +} \ No newline at end of file diff --git a/frontend/.tern-project b/frontend/.tern-project new file mode 100644 index 000000000..aa9d76407 --- /dev/null +++ b/frontend/.tern-project @@ -0,0 +1,7 @@ +{ + "ecmaVersion": 6, + "libs": [ + "browser", + "jquery" + ] +} diff --git a/frontend/.vscode/extensions.json b/frontend/.vscode/extensions.json new file mode 100644 index 000000000..0e005a3cd --- /dev/null +++ b/frontend/.vscode/extensions.json @@ -0,0 +1,7 @@ +{ + "recommendations": [ + "stylelint.vscode-stylelint", + "dbaeumer.vscode-eslint", + "esbenp.prettier-vscode" + ] +} \ No newline at end of file diff --git a/frontend/.vscode/settings.json b/frontend/.vscode/settings.json new file mode 100644 index 000000000..8da95337f --- /dev/null +++ b/frontend/.vscode/settings.json @@ -0,0 +1,23 @@ +// Place your settings in this file to overwrite default and user settings. +{ + "files.insertFinalNewline": true, + + "files.exclude": { + "**/node_modules": true, + "**/*.d.css": true + }, + + "editor.formatOnSave": false, + "editor.codeActionsOnSave": { + "source.fixAll": "explicit" + }, + + "typescript.preferences.quoteStyle": "single", + + "eslint.validate": [ + "javascript", + "javascriptreact", + "typescript", + "typescriptreact" + ], +} diff --git a/frontend/babel.config.js b/frontend/babel.config.js new file mode 100644 index 000000000..ade9f24a2 --- /dev/null +++ b/frontend/babel.config.js @@ -0,0 +1,39 @@ +const loose = true; + +module.exports = { + plugins: [ + '@babel/plugin-transform-logical-assignment-operators', + + // Stage 1 + '@babel/plugin-proposal-export-default-from', + ['@babel/plugin-transform-optional-chaining', { loose }], + ['@babel/plugin-transform-nullish-coalescing-operator', { loose }], + + // Stage 2 + '@babel/plugin-transform-export-namespace-from', + + // Stage 3 + ['@babel/plugin-transform-class-properties', { loose }], + '@babel/plugin-syntax-dynamic-import' + ], + env: { + development: { + presets: [ + ['@babel/preset-react', { development: true }], + '@babel/preset-typescript' + ], + plugins: [ + 'babel-plugin-inline-classnames' + ] + }, + production: { + presets: [ + '@babel/preset-react', + '@babel/preset-typescript' + ], + plugins: [ + 'babel-plugin-transform-react-remove-prop-types' + ] + } + } +}; diff --git a/frontend/build/webpack.config.js b/frontend/build/webpack.config.js new file mode 100644 index 000000000..0d0364950 --- /dev/null +++ b/frontend/build/webpack.config.js @@ -0,0 +1,290 @@ +/* eslint-disable @typescript-eslint/no-var-requires */ +const path = require('path'); +const webpack = require('webpack'); +const FileManagerPlugin = require('filemanager-webpack-plugin'); +const HtmlWebpackPlugin = require('html-webpack-plugin'); +const LiveReloadPlugin = require('webpack-livereload-plugin'); +const MiniCssExtractPlugin = require('mini-css-extract-plugin'); +const TerserPlugin = require('terser-webpack-plugin'); +const ForkTsCheckerWebpackPlugin = require('fork-ts-checker-webpack-plugin'); + +module.exports = (env) => { + const uiFolder = 'UI'; + const frontendFolder = path.join(__dirname, '..'); + const srcFolder = path.join(frontendFolder, 'src'); + const isProduction = !!env.production; + const isProfiling = isProduction && !!env.profile; + const inlineWebWorkers = 'no-fallback'; + + const distFolder = path.resolve(frontendFolder, '..', '_output', uiFolder); + + console.log('Source Folder:', srcFolder); + console.log('Output Folder:', distFolder); + console.log('isProduction:', isProduction); + console.log('isProfiling:', isProfiling); + + const config = { + mode: isProduction ? 'production' : 'development', + devtool: isProduction ? 'source-map' : 'eval-source-map', + target: 'web', + + stats: { + children: false + }, + + watchOptions: { + ignored: /node_modules/ + }, + + entry: { + index: 'index.ts' + }, + + resolve: { + extensions: [ + '.ts', + '.tsx', + '.js' + ], + modules: [ + srcFolder, + path.join(srcFolder, 'Shims'), + 'node_modules' + ], + alias: { + jquery: 'jquery/dist/jquery.min' + }, + fallback: { + buffer: false, + http: false, + https: false, + url: false, + util: false, + net: false + } + }, + + output: { + path: distFolder, + publicPath: '/', + filename: isProduction ? '[name]-[contenthash].js' : '[name].js', + sourceMapFilename: '[file].map' + }, + + optimization: { + moduleIds: 'deterministic', + chunkIds: isProduction ? 'deterministic' : 'named' + }, + + performance: { + hints: false + }, + + experiments: { + topLevelAwait: true + }, + + plugins: [ + new webpack.DefinePlugin({ + __DEV__: !isProduction, + 'process.env.NODE_ENV': isProduction ? JSON.stringify('production') : JSON.stringify('development') + }), + + new MiniCssExtractPlugin({ + filename: 'Content/styles.css', + chunkFilename: isProduction ? 'Content/[id]-[chunkhash].css' : 'Content/[id].css' + }), + + new HtmlWebpackPlugin({ + template: 'frontend/src/index.ejs', + filename: 'index.html', + publicPath: '/', + inject: false + }), + + new FileManagerPlugin({ + events: { + onEnd: { + copy: [ + // HTML + { + source: 'frontend/src/*.html', + destination: distFolder + }, + + // Fonts + { + source: 'frontend/src/Content/Fonts/*.*', + destination: path.join(distFolder, 'Content/Fonts') + }, + + // Icon Images + { + source: 'frontend/src/Content/Images/Icons/*.*', + destination: path.join(distFolder, 'Content/Images/Icons') + }, + + // Images + { + source: 'frontend/src/Content/Images/*.*', + destination: path.join(distFolder, 'Content/Images') + }, + + // Robots + { + source: 'frontend/src/Content/robots.txt', + destination: path.join(distFolder, 'Content/robots.txt') + }, + + // manifest.json and browserconfig.xml + { + source: 'frontend/src/Content/*.(json|xml)', + destination: path.join(distFolder, 'Content') + } + ] + } + } + }), + + new ForkTsCheckerWebpackPlugin(), + + new LiveReloadPlugin() + ], + + resolveLoader: { + modules: [ + 'node_modules', + 'frontend/build/webpack/' + ] + }, + + module: { + rules: [ + { + test: /\.worker\.js$/, + use: { + loader: 'worker-loader', + options: { + filename: '[name].js', + inline: inlineWebWorkers + } + } + }, + { + test: [/\.jsx?$/, /\.tsx?$/], + exclude: /(node_modules|JsLibraries)/, + use: [ + { + loader: 'babel-loader', + options: { + configFile: `${frontendFolder}/babel.config.js`, + envName: isProduction ? 'production' : 'development', + presets: [ + [ + '@babel/preset-env', + { + modules: false, + loose: true, + debug: false, + useBuiltIns: 'entry', + corejs: '3.39' + } + ] + ] + } + } + ] + }, + + // CSS Modules + { + test: /\.css$/, + exclude: /(node_modules|globals.css)/, + use: [ + { loader: MiniCssExtractPlugin.loader }, + { loader: 'css-modules-typescript-loader' }, + { + loader: 'css-loader', + options: { + importLoaders: 1, + modules: { + localIdentName: isProduction ? '[name]/[local]/[hash:base64:5]' : '[name]/[local]' + } + } + }, + { + loader: 'postcss-loader', + options: { + postcssOptions: { + config: 'frontend/postcss.config.js' + } + } + } + ] + }, + + // Global styles + { + test: /\.css$/, + include: /(node_modules|globals.css)/, + use: [ + 'style-loader', + { + loader: 'css-loader' + } + ] + }, + + // Fonts + { + test: /\.woff(2)?(\?v=[0-9]\.[0-9]\.[0-9])?$/, + use: [ + { + loader: 'url-loader', + options: { + limit: 10240, + mimetype: 'application/font-woff', + emitFile: false, + name: 'Content/Fonts/[name].[ext]' + } + } + ] + }, + + { + test: /\.(ttf|eot|eot?#iefix|svg)(\?v=[0-9]\.[0-9]\.[0-9])?$/, + use: [ + { + loader: 'file-loader', + options: { + emitFile: false, + name: 'Content/Fonts/[name].[ext]' + } + } + ] + } + ] + } + }; + + if (isProfiling) { + config.resolve.alias['react-dom$'] = 'react-dom/profiling'; + config.resolve.alias['scheduler/tracing'] = 'scheduler/tracing-profiling'; + + config.optimization = { + minimize: true, + minimizer: [ + new TerserPlugin({ + terserOptions: { + sourceMap: true, // Must be set to true if using source-maps in production + mangle: false, + keep_classnames: true, + keep_fnames: true + } + }) + ] + }; + } + + return config; +}; diff --git a/frontend/build/webpack/css-variables-loader.js b/frontend/build/webpack/css-variables-loader.js new file mode 100644 index 000000000..717d7d323 --- /dev/null +++ b/frontend/build/webpack/css-variables-loader.js @@ -0,0 +1,12 @@ +// eslint-disable-next-line filenames/match-exported +const loaderUtils = require('loader-utils'); + +module.exports = function cssVariablesLoader(source) { + const options = loaderUtils.getOptions(this); + + options.cssVarsFiles.forEach((cssVarsFile) => { + this.addDependency(cssVarsFile); + }); + + return source; +}; diff --git a/frontend/postcss.config.js b/frontend/postcss.config.js new file mode 100644 index 000000000..89db00f8c --- /dev/null +++ b/frontend/postcss.config.js @@ -0,0 +1,32 @@ +const reload = require('require-nocache')(module); + +const cssVarsFiles = [ + './src/Styles/Variables/dimensions', + './src/Styles/Variables/fonts', + './src/Styles/Variables/animations', + './src/Styles/Variables/zIndexes' +].map(require.resolve); + +const mixinsFiles = [ + 'frontend/src/Styles/Mixins/cover.css', + 'frontend/src/Styles/Mixins/linkOverlay.css', + 'frontend/src/Styles/Mixins/scroller.css', + 'frontend/src/Styles/Mixins/truncate.css' +]; + +module.exports = { + plugins: [ + 'autoprefixer', + ['postcss-mixins', { + mixinsFiles + }], + ['postcss-simple-vars', { + variables: () => + cssVarsFiles.reduce((acc, vars) => { + return Object.assign(acc, reload(vars)); + }, {}) + }], + 'postcss-color-function', + 'postcss-nested' + ] +}; diff --git a/frontend/src/Activity/Blocklist/Blocklist.tsx b/frontend/src/Activity/Blocklist/Blocklist.tsx new file mode 100644 index 000000000..4163bc9ca --- /dev/null +++ b/frontend/src/Activity/Blocklist/Blocklist.tsx @@ -0,0 +1,329 @@ +import React, { useCallback, useEffect, useMemo, useState } from 'react'; +import { useDispatch, useSelector } from 'react-redux'; +import { SelectProvider } from 'App/SelectContext'; +import AppState from 'App/State/AppState'; +import * as commandNames from 'Commands/commandNames'; +import Alert from 'Components/Alert'; +import LoadingIndicator from 'Components/Loading/LoadingIndicator'; +import FilterMenu from 'Components/Menu/FilterMenu'; +import ConfirmModal from 'Components/Modal/ConfirmModal'; +import PageContent from 'Components/Page/PageContent'; +import PageContentBody from 'Components/Page/PageContentBody'; +import PageToolbar from 'Components/Page/Toolbar/PageToolbar'; +import PageToolbarButton from 'Components/Page/Toolbar/PageToolbarButton'; +import PageToolbarSection from 'Components/Page/Toolbar/PageToolbarSection'; +import Table from 'Components/Table/Table'; +import TableBody from 'Components/Table/TableBody'; +import TableOptionsModalWrapper from 'Components/Table/TableOptions/TableOptionsModalWrapper'; +import TablePager from 'Components/Table/TablePager'; +import usePaging from 'Components/Table/usePaging'; +import useCurrentPage from 'Helpers/Hooks/useCurrentPage'; +import usePrevious from 'Helpers/Hooks/usePrevious'; +import useSelectState from 'Helpers/Hooks/useSelectState'; +import { align, icons, kinds } from 'Helpers/Props'; +import { + clearBlocklist, + fetchBlocklist, + gotoBlocklistPage, + removeBlocklistItems, + setBlocklistFilter, + setBlocklistSort, + setBlocklistTableOption, +} from 'Store/Actions/blocklistActions'; +import { executeCommand } from 'Store/Actions/commandActions'; +import { createCustomFiltersSelector } from 'Store/Selectors/createClientSideCollectionSelector'; +import createCommandExecutingSelector from 'Store/Selectors/createCommandExecutingSelector'; +import { CheckInputChanged } from 'typings/inputs'; +import { SelectStateInputProps } from 'typings/props'; +import { TableOptionsChangePayload } from 'typings/Table'; +import { + registerPagePopulator, + unregisterPagePopulator, +} from 'Utilities/pagePopulator'; +import translate from 'Utilities/String/translate'; +import getSelectedIds from 'Utilities/Table/getSelectedIds'; +import BlocklistFilterModal from './BlocklistFilterModal'; +import BlocklistRow from './BlocklistRow'; + +function Blocklist() { + const requestCurrentPage = useCurrentPage(); + + const { + isFetching, + isPopulated, + error, + items, + columns, + selectedFilterKey, + filters, + sortKey, + sortDirection, + page, + pageSize, + totalPages, + totalRecords, + isRemoving, + } = useSelector((state: AppState) => state.blocklist); + + const customFilters = useSelector(createCustomFiltersSelector('blocklist')); + const isClearingBlocklistExecuting = useSelector( + createCommandExecutingSelector(commandNames.CLEAR_BLOCKLIST) + ); + const dispatch = useDispatch(); + + const [isConfirmRemoveModalOpen, setIsConfirmRemoveModalOpen] = + useState(false); + const [isConfirmClearModalOpen, setIsConfirmClearModalOpen] = useState(false); + + const [selectState, setSelectState] = useSelectState(); + const { allSelected, allUnselected, selectedState } = selectState; + + const selectedIds = useMemo(() => { + return getSelectedIds(selectedState); + }, [selectedState]); + + const wasClearingBlocklistExecuting = usePrevious( + isClearingBlocklistExecuting + ); + + const handleSelectAllChange = useCallback( + ({ value }: CheckInputChanged) => { + setSelectState({ type: value ? 'selectAll' : 'unselectAll', items }); + }, + [items, setSelectState] + ); + + const handleSelectedChange = useCallback( + ({ id, value, shiftKey = false }: SelectStateInputProps) => { + setSelectState({ + type: 'toggleSelected', + items, + id, + isSelected: value, + shiftKey, + }); + }, + [items, setSelectState] + ); + + const handleRemoveSelectedPress = useCallback(() => { + setIsConfirmRemoveModalOpen(true); + }, [setIsConfirmRemoveModalOpen]); + + const handleRemoveSelectedConfirmed = useCallback(() => { + dispatch(removeBlocklistItems({ ids: selectedIds })); + setIsConfirmRemoveModalOpen(false); + }, [selectedIds, setIsConfirmRemoveModalOpen, dispatch]); + + const handleConfirmRemoveModalClose = useCallback(() => { + setIsConfirmRemoveModalOpen(false); + }, [setIsConfirmRemoveModalOpen]); + + const handleClearBlocklistPress = useCallback(() => { + setIsConfirmClearModalOpen(true); + }, [setIsConfirmClearModalOpen]); + + const handleClearBlocklistConfirmed = useCallback(() => { + dispatch(executeCommand({ name: commandNames.CLEAR_BLOCKLIST })); + setIsConfirmClearModalOpen(false); + }, [setIsConfirmClearModalOpen, dispatch]); + + const handleConfirmClearModalClose = useCallback(() => { + setIsConfirmClearModalOpen(false); + }, [setIsConfirmClearModalOpen]); + + const { + handleFirstPagePress, + handlePreviousPagePress, + handleNextPagePress, + handleLastPagePress, + handlePageSelect, + } = usePaging({ + page, + totalPages, + gotoPage: gotoBlocklistPage, + }); + + const handleFilterSelect = useCallback( + (selectedFilterKey: string) => { + dispatch(setBlocklistFilter({ selectedFilterKey })); + }, + [dispatch] + ); + + const handleSortPress = useCallback( + (sortKey: string) => { + dispatch(setBlocklistSort({ sortKey })); + }, + [dispatch] + ); + + const handleTableOptionChange = useCallback( + (payload: TableOptionsChangePayload) => { + dispatch(setBlocklistTableOption(payload)); + + if (payload.pageSize) { + dispatch(gotoBlocklistPage({ page: 1 })); + } + }, + [dispatch] + ); + + useEffect(() => { + if (requestCurrentPage) { + dispatch(fetchBlocklist()); + } else { + dispatch(gotoBlocklistPage({ page: 1 })); + } + + return () => { + dispatch(clearBlocklist()); + }; + }, [requestCurrentPage, dispatch]); + + useEffect(() => { + const repopulate = () => { + dispatch(fetchBlocklist()); + }; + + registerPagePopulator(repopulate); + + return () => { + unregisterPagePopulator(repopulate); + }; + }, [dispatch]); + + useEffect(() => { + if (wasClearingBlocklistExecuting && !isClearingBlocklistExecuting) { + dispatch(gotoBlocklistPage({ page: 1 })); + } + }, [isClearingBlocklistExecuting, wasClearingBlocklistExecuting, dispatch]); + + return ( + + + + + + + + + + + + + + + + + + + + {isFetching && !isPopulated ? : null} + + {!isFetching && !!error ? ( + {translate('BlocklistLoadError')} + ) : null} + + {isPopulated && !error && !items.length ? ( + + {selectedFilterKey === 'all' + ? translate('NoBlocklistItems') + : translate('BlocklistFilterHasNoItems')} + + ) : null} + + {isPopulated && !error && !!items.length ? ( +
+ + + {items.map((item) => { + return ( + + ); + })} + +
+ +
+ ) : null} +
+ + + + +
+
+ ); +} + +export default Blocklist; diff --git a/frontend/src/Activity/Blocklist/BlocklistDetailsModal.tsx b/frontend/src/Activity/Blocklist/BlocklistDetailsModal.tsx new file mode 100644 index 000000000..ec026ae92 --- /dev/null +++ b/frontend/src/Activity/Blocklist/BlocklistDetailsModal.tsx @@ -0,0 +1,64 @@ +import React from 'react'; +import DescriptionList from 'Components/DescriptionList/DescriptionList'; +import DescriptionListItem from 'Components/DescriptionList/DescriptionListItem'; +import Button from 'Components/Link/Button'; +import Modal from 'Components/Modal/Modal'; +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 DownloadProtocol from 'DownloadClient/DownloadProtocol'; +import translate from 'Utilities/String/translate'; + +interface BlocklistDetailsModalProps { + isOpen: boolean; + sourceTitle: string; + protocol: DownloadProtocol; + indexer?: string; + message?: string; + onModalClose: () => void; +} + +function BlocklistDetailsModal(props: BlocklistDetailsModalProps) { + const { isOpen, sourceTitle, protocol, indexer, message, onModalClose } = + props; + + return ( + + + Details + + + + + + + + {message ? ( + + ) : null} + + {message ? ( + + ) : null} + + + + + + + + + ); +} + +export default BlocklistDetailsModal; diff --git a/frontend/src/Activity/Blocklist/BlocklistFilterModal.tsx b/frontend/src/Activity/Blocklist/BlocklistFilterModal.tsx new file mode 100644 index 000000000..ea80458f1 --- /dev/null +++ b/frontend/src/Activity/Blocklist/BlocklistFilterModal.tsx @@ -0,0 +1,54 @@ +import React, { useCallback } from 'react'; +import { useDispatch, useSelector } from 'react-redux'; +import { createSelector } from 'reselect'; +import AppState from 'App/State/AppState'; +import FilterModal from 'Components/Filter/FilterModal'; +import { setBlocklistFilter } from 'Store/Actions/blocklistActions'; + +function createBlocklistSelector() { + return createSelector( + (state: AppState) => state.blocklist.items, + (blocklistItems) => { + return blocklistItems; + } + ); +} + +function createFilterBuilderPropsSelector() { + return createSelector( + (state: AppState) => state.blocklist.filterBuilderProps, + (filterBuilderProps) => { + return filterBuilderProps; + } + ); +} + +interface BlocklistFilterModalProps { + isOpen: boolean; +} + +export default function BlocklistFilterModal(props: BlocklistFilterModalProps) { + const sectionItems = useSelector(createBlocklistSelector()); + const filterBuilderProps = useSelector(createFilterBuilderPropsSelector()); + const customFilterType = 'blocklist'; + + const dispatch = useDispatch(); + + const dispatchSetFilter = useCallback( + (payload: unknown) => { + dispatch(setBlocklistFilter(payload)); + }, + [dispatch] + ); + + return ( + + ); +} diff --git a/frontend/src/Activity/Blocklist/BlocklistRow.css b/frontend/src/Activity/Blocklist/BlocklistRow.css new file mode 100644 index 000000000..aa008a6ce --- /dev/null +++ b/frontend/src/Activity/Blocklist/BlocklistRow.css @@ -0,0 +1,18 @@ +.languages, +.quality { + composes: cell from '~Components/Table/Cells/TableRowCell.css'; + + width: 100px; +} + +.indexer { + composes: cell from '~Components/Table/Cells/TableRowCell.css'; + + width: 80px; +} + +.actions { + composes: cell from '~Components/Table/Cells/TableRowCell.css'; + + width: 70px; +} diff --git a/frontend/src/Activity/Blocklist/BlocklistRow.css.d.ts b/frontend/src/Activity/Blocklist/BlocklistRow.css.d.ts new file mode 100644 index 000000000..cc16b7e9e --- /dev/null +++ b/frontend/src/Activity/Blocklist/BlocklistRow.css.d.ts @@ -0,0 +1,10 @@ +// This file is automatically generated. +// Please do not change this file! +interface CssExports { + 'actions': string; + 'indexer': string; + 'languages': string; + 'quality': string; +} +export const cssExports: CssExports; +export default cssExports; diff --git a/frontend/src/Activity/Blocklist/BlocklistRow.tsx b/frontend/src/Activity/Blocklist/BlocklistRow.tsx new file mode 100644 index 000000000..c7410320d --- /dev/null +++ b/frontend/src/Activity/Blocklist/BlocklistRow.tsx @@ -0,0 +1,163 @@ +import React, { useCallback, useState } from 'react'; +import { useDispatch } from 'react-redux'; +import IconButton from 'Components/Link/IconButton'; +import RelativeDateCell from 'Components/Table/Cells/RelativeDateCell'; +import TableRowCell from 'Components/Table/Cells/TableRowCell'; +import TableSelectCell from 'Components/Table/Cells/TableSelectCell'; +import Column from 'Components/Table/Column'; +import TableRow from 'Components/Table/TableRow'; +import EpisodeFormats from 'Episode/EpisodeFormats'; +import EpisodeLanguages from 'Episode/EpisodeLanguages'; +import EpisodeQuality from 'Episode/EpisodeQuality'; +import { icons, kinds } from 'Helpers/Props'; +import SeriesTitleLink from 'Series/SeriesTitleLink'; +import useSeries from 'Series/useSeries'; +import { removeBlocklistItem } from 'Store/Actions/blocklistActions'; +import Blocklist from 'typings/Blocklist'; +import { SelectStateInputProps } from 'typings/props'; +import translate from 'Utilities/String/translate'; +import BlocklistDetailsModal from './BlocklistDetailsModal'; +import styles from './BlocklistRow.css'; + +interface BlocklistRowProps extends Blocklist { + isSelected: boolean; + columns: Column[]; + onSelectedChange: (options: SelectStateInputProps) => void; +} + +function BlocklistRow(props: BlocklistRowProps) { + const { + id, + seriesId, + sourceTitle, + languages, + quality, + customFormats, + date, + protocol, + indexer, + message, + isSelected, + columns, + onSelectedChange, + } = props; + + const series = useSeries(seriesId); + const dispatch = useDispatch(); + const [isDetailsModalOpen, setIsDetailsModalOpen] = useState(false); + + const handleDetailsPress = useCallback(() => { + setIsDetailsModalOpen(true); + }, [setIsDetailsModalOpen]); + + const handleDetailsModalClose = useCallback(() => { + setIsDetailsModalOpen(false); + }, [setIsDetailsModalOpen]); + + const handleRemovePress = useCallback(() => { + dispatch(removeBlocklistItem({ id })); + }, [id, dispatch]); + + if (!series) { + return null; + } + + return ( + + + + {columns.map((column) => { + const { name, isVisible } = column; + + if (!isVisible) { + return null; + } + + if (name === 'series.sortTitle') { + return ( + + + + ); + } + + if (name === 'sourceTitle') { + return {sourceTitle}; + } + + if (name === 'languages') { + return ( + + + + ); + } + + if (name === 'quality') { + return ( + + + + ); + } + + if (name === 'customFormats') { + return ( + + + + ); + } + + if (name === 'date') { + // eslint-disable-next-line @typescript-eslint/ban-ts-comment + // @ts-ignore ts(2739) + return ; + } + + if (name === 'indexer') { + return ( + + {indexer} + + ); + } + + if (name === 'actions') { + return ( + + + + + + ); + } + + return null; + })} + + + + ); +} + +export default BlocklistRow; diff --git a/frontend/src/Activity/History/Details/HistoryDetails.css b/frontend/src/Activity/History/Details/HistoryDetails.css new file mode 100644 index 000000000..383f08afd --- /dev/null +++ b/frontend/src/Activity/History/Details/HistoryDetails.css @@ -0,0 +1,5 @@ +.description { + composes: description from '~Components/DescriptionList/DescriptionListItemDescription.css'; + + overflow-wrap: break-word; +} diff --git a/frontend/src/Activity/History/Details/HistoryDetails.css.d.ts b/frontend/src/Activity/History/Details/HistoryDetails.css.d.ts new file mode 100644 index 000000000..ff7055b0f --- /dev/null +++ b/frontend/src/Activity/History/Details/HistoryDetails.css.d.ts @@ -0,0 +1,7 @@ +// This file is automatically generated. +// Please do not change this file! +interface CssExports { + 'description': string; +} +export const cssExports: CssExports; +export default cssExports; diff --git a/frontend/src/Activity/History/Details/HistoryDetails.tsx b/frontend/src/Activity/History/Details/HistoryDetails.tsx new file mode 100644 index 000000000..f460ec433 --- /dev/null +++ b/frontend/src/Activity/History/Details/HistoryDetails.tsx @@ -0,0 +1,321 @@ +import React from 'react'; +import { useSelector } from 'react-redux'; +import DescriptionList from 'Components/DescriptionList/DescriptionList'; +import DescriptionListItem from 'Components/DescriptionList/DescriptionListItem'; +import DescriptionListItemDescription from 'Components/DescriptionList/DescriptionListItemDescription'; +import DescriptionListItemTitle from 'Components/DescriptionList/DescriptionListItemTitle'; +import Link from 'Components/Link/Link'; +import createUISettingsSelector from 'Store/Selectors/createUISettingsSelector'; +import { + DownloadFailedHistory, + DownloadFolderImportedHistory, + DownloadIgnoredHistory, + EpisodeFileDeletedHistory, + EpisodeFileRenamedHistory, + GrabbedHistoryData, + HistoryData, + HistoryEventType, +} from 'typings/History'; +import formatDateTime from 'Utilities/Date/formatDateTime'; +import formatAge from 'Utilities/Number/formatAge'; +import formatCustomFormatScore from 'Utilities/Number/formatCustomFormatScore'; +import translate from 'Utilities/String/translate'; +import styles from './HistoryDetails.css'; + +interface HistoryDetailsProps { + eventType: HistoryEventType; + sourceTitle: string; + data: HistoryData; + downloadId?: string; +} + +function HistoryDetails(props: HistoryDetailsProps) { + const { eventType, sourceTitle, data, downloadId } = props; + + const { shortDateFormat, timeFormat } = useSelector( + createUISettingsSelector() + ); + + if (eventType === 'grabbed') { + const { + indexer, + releaseGroup, + seriesMatchType, + releaseSource, + customFormatScore, + nzbInfoUrl, + downloadClient, + downloadClientName, + age, + ageHours, + ageMinutes, + publishedDate, + } = data as GrabbedHistoryData; + + const downloadClientNameInfo = downloadClientName ?? downloadClient; + + let releaseSourceMessage = ''; + + switch (releaseSource) { + case 'Unknown': + releaseSourceMessage = translate('Unknown'); + break; + case 'Rss': + releaseSourceMessage = translate('Rss'); + break; + case 'Search': + releaseSourceMessage = translate('Search'); + break; + case 'UserInvokedSearch': + releaseSourceMessage = translate('UserInvokedSearch'); + break; + case 'InteractiveSearch': + releaseSourceMessage = translate('InteractiveSearch'); + break; + case 'ReleasePush': + releaseSourceMessage = translate('ReleasePush'); + break; + default: + releaseSourceMessage = ''; + } + + return ( + + + + {indexer ? ( + + ) : null} + + {releaseGroup ? ( + + ) : null} + + {customFormatScore && customFormatScore !== '0' ? ( + + ) : null} + + {seriesMatchType ? ( + + ) : null} + + {releaseSource ? ( + + ) : null} + + {nzbInfoUrl ? ( + + + {translate('InfoUrl')} + + + + {nzbInfoUrl} + + + ) : null} + + {downloadClientNameInfo ? ( + + ) : null} + + {downloadId ? ( + + ) : null} + + {age || ageHours || ageMinutes ? ( + + ) : null} + + {publishedDate ? ( + + ) : null} + + ); + } + + if (eventType === 'downloadFailed') { + const { message } = data as DownloadFailedHistory; + + return ( + + + + {downloadId ? ( + + ) : null} + + {message ? ( + + ) : null} + + ); + } + + if (eventType === 'downloadFolderImported') { + const { customFormatScore, droppedPath, importedPath } = + data as DownloadFolderImportedHistory; + + return ( + + + + {droppedPath ? ( + + ) : null} + + {importedPath ? ( + + ) : null} + + {customFormatScore && customFormatScore !== '0' ? ( + + ) : null} + + ); + } + + if (eventType === 'episodeFileDeleted') { + const { reason, customFormatScore } = data as EpisodeFileDeletedHistory; + + let reasonMessage = ''; + + switch (reason) { + case 'Manual': + reasonMessage = translate('DeletedReasonManual'); + break; + case 'MissingFromDisk': + reasonMessage = translate('DeletedReasonEpisodeMissingFromDisk'); + break; + case 'Upgrade': + reasonMessage = translate('DeletedReasonUpgrade'); + break; + default: + reasonMessage = ''; + } + + return ( + + + + + + {customFormatScore && customFormatScore !== '0' ? ( + + ) : null} + + ); + } + + if (eventType === 'episodeFileRenamed') { + const { sourcePath, sourceRelativePath, path, relativePath } = + data as EpisodeFileRenamedHistory; + + return ( + + + + + + + + + + ); + } + + if (eventType === 'downloadIgnored') { + const { message } = data as DownloadIgnoredHistory; + + return ( + + + + {downloadId ? ( + + ) : null} + + {message ? ( + + ) : null} + + ); + } + + return ( + + + + ); +} + +export default HistoryDetails; diff --git a/frontend/src/Activity/History/Details/HistoryDetailsModal.css b/frontend/src/Activity/History/Details/HistoryDetailsModal.css new file mode 100644 index 000000000..271d422ff --- /dev/null +++ b/frontend/src/Activity/History/Details/HistoryDetailsModal.css @@ -0,0 +1,5 @@ +.markAsFailedButton { + composes: button from '~Components/Link/Button.css'; + + margin-right: auto; +} diff --git a/frontend/src/Activity/History/Details/HistoryDetailsModal.css.d.ts b/frontend/src/Activity/History/Details/HistoryDetailsModal.css.d.ts new file mode 100644 index 000000000..a8cc499e2 --- /dev/null +++ b/frontend/src/Activity/History/Details/HistoryDetailsModal.css.d.ts @@ -0,0 +1,7 @@ +// This file is automatically generated. +// Please do not change this file! +interface CssExports { + 'markAsFailedButton': string; +} +export const cssExports: CssExports; +export default cssExports; diff --git a/frontend/src/Activity/History/Details/HistoryDetailsModal.tsx b/frontend/src/Activity/History/Details/HistoryDetailsModal.tsx new file mode 100644 index 000000000..8134a9736 --- /dev/null +++ b/frontend/src/Activity/History/Details/HistoryDetailsModal.tsx @@ -0,0 +1,90 @@ +import React from 'react'; +import Button from 'Components/Link/Button'; +import SpinnerButton from 'Components/Link/SpinnerButton'; +import Modal from 'Components/Modal/Modal'; +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 { HistoryData, HistoryEventType } from 'typings/History'; +import translate from 'Utilities/String/translate'; +import HistoryDetails from './HistoryDetails'; +import styles from './HistoryDetailsModal.css'; + +function getHeaderTitle(eventType: HistoryEventType) { + switch (eventType) { + case 'grabbed': + return translate('Grabbed'); + case 'downloadFailed': + return translate('DownloadFailed'); + case 'downloadFolderImported': + return translate('EpisodeImported'); + case 'episodeFileDeleted': + return translate('EpisodeFileDeleted'); + case 'episodeFileRenamed': + return translate('EpisodeFileRenamed'); + case 'downloadIgnored': + return translate('DownloadIgnored'); + default: + return translate('Unknown'); + } +} + +interface HistoryDetailsModalProps { + isOpen: boolean; + eventType: HistoryEventType; + sourceTitle: string; + data: HistoryData; + downloadId?: string; + isMarkingAsFailed: boolean; + onMarkAsFailedPress: () => void; + onModalClose: () => void; +} + +function HistoryDetailsModal(props: HistoryDetailsModalProps) { + const { + isOpen, + eventType, + sourceTitle, + data, + downloadId, + isMarkingAsFailed = false, + onMarkAsFailedPress, + onModalClose, + } = props; + + return ( + + + {getHeaderTitle(eventType)} + + + + + + + {eventType === 'grabbed' && ( + + {translate('MarkAsFailed')} + + )} + + + + + + ); +} + +export default HistoryDetailsModal; diff --git a/frontend/src/Activity/History/History.tsx b/frontend/src/Activity/History/History.tsx new file mode 100644 index 000000000..9f00a1ab3 --- /dev/null +++ b/frontend/src/Activity/History/History.tsx @@ -0,0 +1,231 @@ +import React, { useCallback, useEffect } from 'react'; +import { useDispatch, useSelector } from 'react-redux'; +import AppState from 'App/State/AppState'; +import Alert from 'Components/Alert'; +import LoadingIndicator from 'Components/Loading/LoadingIndicator'; +import FilterMenu from 'Components/Menu/FilterMenu'; +import PageContent from 'Components/Page/PageContent'; +import PageContentBody from 'Components/Page/PageContentBody'; +import PageToolbar from 'Components/Page/Toolbar/PageToolbar'; +import PageToolbarButton from 'Components/Page/Toolbar/PageToolbarButton'; +import PageToolbarSection from 'Components/Page/Toolbar/PageToolbarSection'; +import Table from 'Components/Table/Table'; +import TableBody from 'Components/Table/TableBody'; +import TableOptionsModalWrapper from 'Components/Table/TableOptions/TableOptionsModalWrapper'; +import TablePager from 'Components/Table/TablePager'; +import usePaging from 'Components/Table/usePaging'; +import createEpisodesFetchingSelector from 'Episode/createEpisodesFetchingSelector'; +import useCurrentPage from 'Helpers/Hooks/useCurrentPage'; +import { align, icons, kinds } from 'Helpers/Props'; +import { clearEpisodes, fetchEpisodes } from 'Store/Actions/episodeActions'; +import { clearEpisodeFiles } from 'Store/Actions/episodeFileActions'; +import { + clearHistory, + fetchHistory, + gotoHistoryPage, + setHistoryFilter, + setHistorySort, + setHistoryTableOption, +} from 'Store/Actions/historyActions'; +import { createCustomFiltersSelector } from 'Store/Selectors/createClientSideCollectionSelector'; +import HistoryItem from 'typings/History'; +import { TableOptionsChangePayload } from 'typings/Table'; +import selectUniqueIds from 'Utilities/Object/selectUniqueIds'; +import { + registerPagePopulator, + unregisterPagePopulator, +} from 'Utilities/pagePopulator'; +import translate from 'Utilities/String/translate'; +import HistoryFilterModal from './HistoryFilterModal'; +import HistoryRow from './HistoryRow'; + +function History() { + const requestCurrentPage = useCurrentPage(); + + const { + isFetching, + isPopulated, + error, + items, + columns, + selectedFilterKey, + filters, + sortKey, + sortDirection, + page, + pageSize, + totalPages, + totalRecords, + } = useSelector((state: AppState) => state.history); + + const { isEpisodesFetching, isEpisodesPopulated, episodesError } = + useSelector(createEpisodesFetchingSelector()); + const customFilters = useSelector(createCustomFiltersSelector('history')); + const dispatch = useDispatch(); + + const isFetchingAny = isFetching || isEpisodesFetching; + const isAllPopulated = isPopulated && (isEpisodesPopulated || !items.length); + const hasError = error || episodesError; + + const { + handleFirstPagePress, + handlePreviousPagePress, + handleNextPagePress, + handleLastPagePress, + handlePageSelect, + } = usePaging({ + page, + totalPages, + gotoPage: gotoHistoryPage, + }); + + const handleFilterSelect = useCallback( + (selectedFilterKey: string) => { + dispatch(setHistoryFilter({ selectedFilterKey })); + }, + [dispatch] + ); + + const handleSortPress = useCallback( + (sortKey: string) => { + dispatch(setHistorySort({ sortKey })); + }, + [dispatch] + ); + + const handleTableOptionChange = useCallback( + (payload: TableOptionsChangePayload) => { + dispatch(setHistoryTableOption(payload)); + + if (payload.pageSize) { + dispatch(gotoHistoryPage({ page: 1 })); + } + }, + [dispatch] + ); + + useEffect(() => { + if (requestCurrentPage) { + dispatch(fetchHistory()); + } else { + dispatch(gotoHistoryPage({ page: 1 })); + } + + return () => { + dispatch(clearHistory()); + dispatch(clearEpisodes()); + dispatch(clearEpisodeFiles()); + }; + }, [requestCurrentPage, dispatch]); + + useEffect(() => { + const episodeIds = selectUniqueIds(items, 'episodeId'); + + if (episodeIds.length) { + dispatch(fetchEpisodes({ episodeIds })); + } else { + dispatch(clearEpisodes()); + } + }, [items, dispatch]); + + useEffect(() => { + const repopulate = () => { + dispatch(fetchHistory()); + }; + + registerPagePopulator(repopulate); + + return () => { + unregisterPagePopulator(repopulate); + }; + }, [dispatch]); + + return ( + + + + + + + + + + + + + + + + + {isFetchingAny && !isAllPopulated ? : null} + + {!isFetchingAny && hasError ? ( + {translate('HistoryLoadError')} + ) : null} + + { + // If history isPopulated and it's empty show no history found and don't + // wait for the episodes to populate because they are never coming. + + isPopulated && !hasError && !items.length ? ( + {translate('NoHistoryFound')} + ) : null + } + + {isAllPopulated && !hasError && items.length ? ( +
+ + + {items.map((item) => { + return ( + + ); + })} + +
+ + +
+ ) : null} +
+
+ ); +} + +export default History; diff --git a/frontend/src/Activity/History/HistoryEventTypeCell.css b/frontend/src/Activity/History/HistoryEventTypeCell.css new file mode 100644 index 000000000..63d79e18c --- /dev/null +++ b/frontend/src/Activity/History/HistoryEventTypeCell.css @@ -0,0 +1,6 @@ +.cell { + composes: cell from '~Components/Table/Cells/TableRowCell.css'; + + width: 35px; + text-align: center; +} diff --git a/frontend/src/Activity/History/HistoryEventTypeCell.css.d.ts b/frontend/src/Activity/History/HistoryEventTypeCell.css.d.ts new file mode 100644 index 000000000..c748f6f97 --- /dev/null +++ b/frontend/src/Activity/History/HistoryEventTypeCell.css.d.ts @@ -0,0 +1,7 @@ +// This file is automatically generated. +// Please do not change this file! +interface CssExports { + 'cell': string; +} +export const cssExports: CssExports; +export default cssExports; diff --git a/frontend/src/Activity/History/HistoryEventTypeCell.tsx b/frontend/src/Activity/History/HistoryEventTypeCell.tsx new file mode 100644 index 000000000..adedf08c0 --- /dev/null +++ b/frontend/src/Activity/History/HistoryEventTypeCell.tsx @@ -0,0 +1,89 @@ +import React from 'react'; +import Icon from 'Components/Icon'; +import TableRowCell from 'Components/Table/Cells/TableRowCell'; +import { icons, kinds } from 'Helpers/Props'; +import { + EpisodeFileDeletedHistory, + GrabbedHistoryData, + HistoryData, + HistoryEventType, +} from 'typings/History'; +import translate from 'Utilities/String/translate'; +import styles from './HistoryEventTypeCell.css'; + +function getIconName(eventType: HistoryEventType, data: HistoryData) { + switch (eventType) { + case 'grabbed': + return icons.DOWNLOADING; + case 'seriesFolderImported': + return icons.DRIVE; + case 'downloadFolderImported': + return icons.DOWNLOADED; + case 'downloadFailed': + return icons.DOWNLOADING; + case 'episodeFileDeleted': + return (data as EpisodeFileDeletedHistory).reason === 'MissingFromDisk' + ? icons.FILE_MISSING + : icons.DELETE; + case 'episodeFileRenamed': + return icons.ORGANIZE; + case 'downloadIgnored': + return icons.IGNORE; + default: + return icons.UNKNOWN; + } +} + +function getIconKind(eventType: HistoryEventType) { + switch (eventType) { + case 'downloadFailed': + return kinds.DANGER; + default: + return kinds.DEFAULT; + } +} + +function getTooltip(eventType: HistoryEventType, data: HistoryData) { + switch (eventType) { + case 'grabbed': + return translate('EpisodeGrabbedTooltip', { + indexer: (data as GrabbedHistoryData).indexer, + downloadClient: (data as GrabbedHistoryData).downloadClient, + }); + case 'seriesFolderImported': + return translate('SeriesFolderImportedTooltip'); + case 'downloadFolderImported': + return translate('EpisodeImportedTooltip'); + case 'downloadFailed': + return translate('DownloadFailedEpisodeTooltip'); + case 'episodeFileDeleted': + return (data as EpisodeFileDeletedHistory).reason === 'MissingFromDisk' + ? translate('EpisodeFileMissingTooltip') + : translate('EpisodeFileDeletedTooltip'); + case 'episodeFileRenamed': + return translate('EpisodeFileRenamedTooltip'); + case 'downloadIgnored': + return translate('DownloadIgnoredEpisodeTooltip'); + default: + return translate('UnknownEventTooltip'); + } +} + +interface HistoryEventTypeCellProps { + eventType: HistoryEventType; + data: HistoryData; +} + +function HistoryEventTypeCell({ eventType, data }: HistoryEventTypeCellProps) { + const iconName = getIconName(eventType, data); + const iconKind = getIconKind(eventType); + const tooltip = getTooltip(eventType, data); + + return ( + + + + ); +} + +export default HistoryEventTypeCell; diff --git a/frontend/src/Activity/History/HistoryFilterModal.tsx b/frontend/src/Activity/History/HistoryFilterModal.tsx new file mode 100644 index 000000000..f4ad2e57c --- /dev/null +++ b/frontend/src/Activity/History/HistoryFilterModal.tsx @@ -0,0 +1,54 @@ +import React, { useCallback } from 'react'; +import { useDispatch, useSelector } from 'react-redux'; +import { createSelector } from 'reselect'; +import AppState from 'App/State/AppState'; +import FilterModal from 'Components/Filter/FilterModal'; +import { setHistoryFilter } from 'Store/Actions/historyActions'; + +function createHistorySelector() { + return createSelector( + (state: AppState) => state.history.items, + (queueItems) => { + return queueItems; + } + ); +} + +function createFilterBuilderPropsSelector() { + return createSelector( + (state: AppState) => state.history.filterBuilderProps, + (filterBuilderProps) => { + return filterBuilderProps; + } + ); +} + +interface HistoryFilterModalProps { + isOpen: boolean; +} + +export default function HistoryFilterModal(props: HistoryFilterModalProps) { + const sectionItems = useSelector(createHistorySelector()); + const filterBuilderProps = useSelector(createFilterBuilderPropsSelector()); + const customFilterType = 'history'; + + const dispatch = useDispatch(); + + const dispatchSetFilter = useCallback( + (payload: unknown) => { + dispatch(setHistoryFilter(payload)); + }, + [dispatch] + ); + + return ( + + ); +} diff --git a/frontend/src/Activity/History/HistoryRow.css b/frontend/src/Activity/History/HistoryRow.css new file mode 100644 index 000000000..039804b63 --- /dev/null +++ b/frontend/src/Activity/History/HistoryRow.css @@ -0,0 +1,29 @@ +.downloadClient { + composes: cell from '~Components/Table/Cells/TableRowCell.css'; + + width: 120px; +} + +.indexer { + composes: cell from '~Components/Table/Cells/TableRowCell.css'; + + width: 80px; +} + +.customFormatScore { + composes: cell from '~Components/Table/Cells/TableRowCell.css'; + + width: 55px; +} + +.releaseGroup { + composes: cell from '~Components/Table/Cells/TableRowCell.css'; + + width: 110px; +} + +.details { + composes: cell from '~Components/Table/Cells/TableRowCell.css'; + + width: 30px; +} diff --git a/frontend/src/Activity/History/HistoryRow.css.d.ts b/frontend/src/Activity/History/HistoryRow.css.d.ts new file mode 100644 index 000000000..e1f54bc96 --- /dev/null +++ b/frontend/src/Activity/History/HistoryRow.css.d.ts @@ -0,0 +1,11 @@ +// This file is automatically generated. +// Please do not change this file! +interface CssExports { + 'customFormatScore': string; + 'details': string; + 'downloadClient': string; + 'indexer': string; + 'releaseGroup': string; +} +export const cssExports: CssExports; +export default cssExports; diff --git a/frontend/src/Activity/History/HistoryRow.tsx b/frontend/src/Activity/History/HistoryRow.tsx new file mode 100644 index 000000000..d1ba279dc --- /dev/null +++ b/frontend/src/Activity/History/HistoryRow.tsx @@ -0,0 +1,270 @@ +import React, { useCallback, useEffect, useState } from 'react'; +import { useDispatch } from 'react-redux'; +import IconButton from 'Components/Link/IconButton'; +import RelativeDateCell from 'Components/Table/Cells/RelativeDateCell'; +import TableRowCell from 'Components/Table/Cells/TableRowCell'; +import Column from 'Components/Table/Column'; +import TableRow from 'Components/Table/TableRow'; +import Tooltip from 'Components/Tooltip/Tooltip'; +import episodeEntities from 'Episode/episodeEntities'; +import EpisodeFormats from 'Episode/EpisodeFormats'; +import EpisodeLanguages from 'Episode/EpisodeLanguages'; +import EpisodeQuality from 'Episode/EpisodeQuality'; +import EpisodeTitleLink from 'Episode/EpisodeTitleLink'; +import SeasonEpisodeNumber from 'Episode/SeasonEpisodeNumber'; +import useEpisode from 'Episode/useEpisode'; +import usePrevious from 'Helpers/Hooks/usePrevious'; +import { icons, tooltipPositions } from 'Helpers/Props'; +import Language from 'Language/Language'; +import { QualityModel } from 'Quality/Quality'; +import SeriesTitleLink from 'Series/SeriesTitleLink'; +import useSeries from 'Series/useSeries'; +import { fetchHistory, markAsFailed } from 'Store/Actions/historyActions'; +import CustomFormat from 'typings/CustomFormat'; +import { HistoryData, HistoryEventType } from 'typings/History'; +import formatCustomFormatScore from 'Utilities/Number/formatCustomFormatScore'; +import HistoryDetailsModal from './Details/HistoryDetailsModal'; +import HistoryEventTypeCell from './HistoryEventTypeCell'; +import styles from './HistoryRow.css'; + +interface HistoryRowProps { + id: number; + episodeId: number; + seriesId: number; + languages: Language[]; + quality: QualityModel; + customFormats?: CustomFormat[]; + customFormatScore: number; + qualityCutoffNotMet: boolean; + eventType: HistoryEventType; + sourceTitle: string; + date: string; + data: HistoryData; + downloadId?: string; + isMarkingAsFailed?: boolean; + markAsFailedError?: object; + columns: Column[]; +} + +function HistoryRow(props: HistoryRowProps) { + const { + id, + episodeId, + seriesId, + languages, + quality, + customFormats = [], + customFormatScore, + qualityCutoffNotMet, + eventType, + sourceTitle, + date, + data, + downloadId, + isMarkingAsFailed = false, + markAsFailedError, + columns, + } = props; + + const wasMarkingAsFailed = usePrevious(isMarkingAsFailed); + const dispatch = useDispatch(); + const series = useSeries(seriesId); + const episode = useEpisode(episodeId, 'episodes'); + + const [isDetailsModalOpen, setIsDetailsModalOpen] = useState(false); + + const handleDetailsPress = useCallback(() => { + setIsDetailsModalOpen(true); + }, [setIsDetailsModalOpen]); + + const handleDetailsModalClose = useCallback(() => { + setIsDetailsModalOpen(false); + }, [setIsDetailsModalOpen]); + + const handleMarkAsFailedPress = useCallback(() => { + dispatch(markAsFailed({ id })); + }, [id, dispatch]); + + useEffect(() => { + if (wasMarkingAsFailed && !isMarkingAsFailed && !markAsFailedError) { + setIsDetailsModalOpen(false); + dispatch(fetchHistory()); + } + }, [ + wasMarkingAsFailed, + isMarkingAsFailed, + markAsFailedError, + setIsDetailsModalOpen, + dispatch, + ]); + + if (!series || !episode) { + return null; + } + + return ( + + {columns.map((column) => { + const { name, isVisible } = column; + + if (!isVisible) { + return null; + } + + if (name === 'eventType') { + return ( + + ); + } + + if (name === 'series.sortTitle') { + return ( + + + + ); + } + + if (name === 'episode') { + return ( + + + + ); + } + + if (name === 'episodes.title') { + return ( + + + + ); + } + + if (name === 'languages') { + return ( + + + + ); + } + + if (name === 'quality') { + return ( + + + + ); + } + + if (name === 'customFormats') { + return ( + + + + ); + } + + if (name === 'date') { + return ; + } + + if (name === 'downloadClient') { + const downloadClientName = + 'downloadClientName' in data ? data.downloadClientName : null; + const downloadClient = + 'downloadClient' in data ? data.downloadClient : null; + + return ( + + {downloadClientName ?? downloadClient ?? ''} + + ); + } + + if (name === 'indexer') { + return ( + + {'indexer' in data ? data.indexer : ''} + + ); + } + + if (name === 'customFormatScore') { + return ( + + } + position={tooltipPositions.BOTTOM} + /> + + ); + } + + if (name === 'releaseGroup') { + return ( + + {'releaseGroup' in data ? data.releaseGroup : ''} + + ); + } + + if (name === 'sourceTitle') { + return {sourceTitle}; + } + + if (name === 'details') { + return ( + + + + ); + } + + return null; + })} + + + + ); +} + +export default HistoryRow; diff --git a/frontend/src/Activity/Queue/ProtocolLabel.css b/frontend/src/Activity/Queue/ProtocolLabel.css new file mode 100644 index 000000000..c94e383b1 --- /dev/null +++ b/frontend/src/Activity/Queue/ProtocolLabel.css @@ -0,0 +1,17 @@ +.torrent { + composes: label from '~Components/Label.css'; + + border-color: var(--torrentColor); + background-color: var(--torrentColor); +} + +.usenet { + composes: label from '~Components/Label.css'; + + border-color: var(--usenetColor); + background-color: var(--usenetColor); +} + +.unknown { + composes: label from '~Components/Label.css'; +} diff --git a/frontend/src/Activity/Queue/ProtocolLabel.css.d.ts b/frontend/src/Activity/Queue/ProtocolLabel.css.d.ts new file mode 100644 index 000000000..ba0cb260d --- /dev/null +++ b/frontend/src/Activity/Queue/ProtocolLabel.css.d.ts @@ -0,0 +1,9 @@ +// This file is automatically generated. +// Please do not change this file! +interface CssExports { + 'torrent': string; + 'unknown': string; + 'usenet': string; +} +export const cssExports: CssExports; +export default cssExports; diff --git a/frontend/src/Activity/Queue/ProtocolLabel.tsx b/frontend/src/Activity/Queue/ProtocolLabel.tsx new file mode 100644 index 000000000..c1824452a --- /dev/null +++ b/frontend/src/Activity/Queue/ProtocolLabel.tsx @@ -0,0 +1,16 @@ +import React from 'react'; +import Label from 'Components/Label'; +import DownloadProtocol from 'DownloadClient/DownloadProtocol'; +import styles from './ProtocolLabel.css'; + +interface ProtocolLabelProps { + protocol: DownloadProtocol; +} + +function ProtocolLabel({ protocol }: ProtocolLabelProps) { + const protocolName = protocol === 'usenet' ? 'nzb' : protocol; + + return ; +} + +export default ProtocolLabel; diff --git a/frontend/src/Activity/Queue/Queue.tsx b/frontend/src/Activity/Queue/Queue.tsx new file mode 100644 index 000000000..bd063e69a --- /dev/null +++ b/frontend/src/Activity/Queue/Queue.tsx @@ -0,0 +1,415 @@ +import React, { + ReactElement, + useCallback, + useEffect, + useMemo, + useRef, + useState, +} from 'react'; +import { useDispatch, useSelector } from 'react-redux'; +import AppState from 'App/State/AppState'; +import * as commandNames from 'Commands/commandNames'; +import Alert from 'Components/Alert'; +import LoadingIndicator from 'Components/Loading/LoadingIndicator'; +import FilterMenu from 'Components/Menu/FilterMenu'; +import PageContent from 'Components/Page/PageContent'; +import PageContentBody from 'Components/Page/PageContentBody'; +import PageToolbar from 'Components/Page/Toolbar/PageToolbar'; +import PageToolbarButton from 'Components/Page/Toolbar/PageToolbarButton'; +import PageToolbarSection from 'Components/Page/Toolbar/PageToolbarSection'; +import PageToolbarSeparator from 'Components/Page/Toolbar/PageToolbarSeparator'; +import Table from 'Components/Table/Table'; +import TableBody from 'Components/Table/TableBody'; +import TableOptionsModalWrapper from 'Components/Table/TableOptions/TableOptionsModalWrapper'; +import TablePager from 'Components/Table/TablePager'; +import usePaging from 'Components/Table/usePaging'; +import createEpisodesFetchingSelector from 'Episode/createEpisodesFetchingSelector'; +import useCurrentPage from 'Helpers/Hooks/useCurrentPage'; +import useSelectState from 'Helpers/Hooks/useSelectState'; +import { align, icons, kinds } from 'Helpers/Props'; +import { executeCommand } from 'Store/Actions/commandActions'; +import { clearEpisodes, fetchEpisodes } from 'Store/Actions/episodeActions'; +import { + clearQueue, + fetchQueue, + gotoQueuePage, + grabQueueItems, + removeQueueItems, + setQueueFilter, + setQueueSort, + setQueueTableOption, +} from 'Store/Actions/queueActions'; +import { createCustomFiltersSelector } from 'Store/Selectors/createClientSideCollectionSelector'; +import createCommandExecutingSelector from 'Store/Selectors/createCommandExecutingSelector'; +import { CheckInputChanged } from 'typings/inputs'; +import { SelectStateInputProps } from 'typings/props'; +import QueueItem from 'typings/Queue'; +import { TableOptionsChangePayload } from 'typings/Table'; +import selectUniqueIds from 'Utilities/Object/selectUniqueIds'; +import { + registerPagePopulator, + unregisterPagePopulator, +} from 'Utilities/pagePopulator'; +import translate from 'Utilities/String/translate'; +import getSelectedIds from 'Utilities/Table/getSelectedIds'; +import QueueFilterModal from './QueueFilterModal'; +import QueueOptions from './QueueOptions'; +import QueueRow from './QueueRow'; +import RemoveQueueItemModal, { RemovePressProps } from './RemoveQueueItemModal'; +import createQueueStatusSelector from './Status/createQueueStatusSelector'; + +function Queue() { + const requestCurrentPage = useCurrentPage(); + const dispatch = useDispatch(); + + const { + isFetching, + isPopulated, + error, + items, + columns, + selectedFilterKey, + filters, + sortKey, + sortDirection, + page, + pageSize, + totalPages, + totalRecords, + isGrabbing, + isRemoving, + } = useSelector((state: AppState) => state.queue.paged); + + const { count } = useSelector(createQueueStatusSelector()); + const { isEpisodesFetching, isEpisodesPopulated, episodesError } = + useSelector(createEpisodesFetchingSelector()); + const customFilters = useSelector(createCustomFiltersSelector('queue')); + + const isRefreshMonitoredDownloadsExecuting = useSelector( + createCommandExecutingSelector(commandNames.REFRESH_MONITORED_DOWNLOADS) + ); + + const shouldBlockRefresh = useRef(false); + const currentQueue = useRef(null); + + const [selectState, setSelectState] = useSelectState(); + const { allSelected, allUnselected, selectedState } = selectState; + + const selectedIds = useMemo(() => { + return getSelectedIds(selectedState); + }, [selectedState]); + + const isPendingSelected = useMemo(() => { + return items.some((item) => { + return selectedIds.indexOf(item.id) > -1 && item.status === 'delay'; + }); + }, [items, selectedIds]); + + const [isConfirmRemoveModalOpen, setIsConfirmRemoveModalOpen] = + useState(false); + + const isRefreshing = + isFetching || isEpisodesFetching || isRefreshMonitoredDownloadsExecuting; + const isAllPopulated = + isPopulated && + (isEpisodesPopulated || !items.length || items.every((e) => !e.episodeId)); + const hasError = error || episodesError; + const selectedCount = selectedIds.length; + const disableSelectedActions = selectedCount === 0; + + const handleSelectAllChange = useCallback( + ({ value }: CheckInputChanged) => { + setSelectState({ type: value ? 'selectAll' : 'unselectAll', items }); + }, + [items, setSelectState] + ); + + const handleSelectedChange = useCallback( + ({ id, value, shiftKey = false }: SelectStateInputProps) => { + setSelectState({ + type: 'toggleSelected', + items, + id, + isSelected: value, + shiftKey, + }); + }, + [items, setSelectState] + ); + + const handleRefreshPress = useCallback(() => { + dispatch( + executeCommand({ + name: commandNames.REFRESH_MONITORED_DOWNLOADS, + }) + ); + }, [dispatch]); + + const handleQueueRowModalOpenOrClose = useCallback((isOpen: boolean) => { + shouldBlockRefresh.current = isOpen; + }, []); + + const handleGrabSelectedPress = useCallback(() => { + dispatch(grabQueueItems({ ids: selectedIds })); + }, [selectedIds, dispatch]); + + const handleRemoveSelectedPress = useCallback(() => { + shouldBlockRefresh.current = true; + setIsConfirmRemoveModalOpen(true); + }, [setIsConfirmRemoveModalOpen]); + + const handleRemoveSelectedConfirmed = useCallback( + (payload: RemovePressProps) => { + shouldBlockRefresh.current = false; + dispatch(removeQueueItems({ ids: selectedIds, ...payload })); + setIsConfirmRemoveModalOpen(false); + }, + [selectedIds, setIsConfirmRemoveModalOpen, dispatch] + ); + + const handleConfirmRemoveModalClose = useCallback(() => { + shouldBlockRefresh.current = false; + setIsConfirmRemoveModalOpen(false); + }, [setIsConfirmRemoveModalOpen]); + + const { + handleFirstPagePress, + handlePreviousPagePress, + handleNextPagePress, + handleLastPagePress, + handlePageSelect, + } = usePaging({ + page, + totalPages, + gotoPage: gotoQueuePage, + }); + + const handleFilterSelect = useCallback( + (selectedFilterKey: string) => { + dispatch(setQueueFilter({ selectedFilterKey })); + }, + [dispatch] + ); + + const handleSortPress = useCallback( + (sortKey: string) => { + dispatch(setQueueSort({ sortKey })); + }, + [dispatch] + ); + + const handleTableOptionChange = useCallback( + (payload: TableOptionsChangePayload) => { + dispatch(setQueueTableOption(payload)); + + if (payload.pageSize) { + dispatch(gotoQueuePage({ page: 1 })); + } + }, + [dispatch] + ); + + useEffect(() => { + if (requestCurrentPage) { + dispatch(fetchQueue()); + } else { + dispatch(gotoQueuePage({ page: 1 })); + } + + return () => { + dispatch(clearQueue()); + }; + }, [requestCurrentPage, dispatch]); + + useEffect(() => { + const episodeIds = selectUniqueIds( + items, + 'episodeId' + ); + + if (episodeIds.length) { + dispatch(fetchEpisodes({ episodeIds })); + } else { + dispatch(clearEpisodes()); + } + }, [items, dispatch]); + + useEffect(() => { + const repopulate = () => { + dispatch(fetchQueue()); + }; + + registerPagePopulator(repopulate); + + return () => { + unregisterPagePopulator(repopulate); + }; + }, [dispatch]); + + if (!shouldBlockRefresh.current) { + currentQueue.current = ( + + {isRefreshing && !isAllPopulated ? : null} + + {!isRefreshing && hasError ? ( + {translate('QueueLoadError')} + ) : null} + + {isAllPopulated && !hasError && !items.length ? ( + + {selectedFilterKey !== 'all' && count > 0 + ? translate('QueueFilterHasNoItems') + : translate('QueueIsEmpty')} + + ) : null} + + {isAllPopulated && !hasError && !!items.length ? ( +
+ + + {items.map((item) => { + return ( + + ); + })} + +
+ + +
+ ) : null} +
+ ); + } + + return ( + + + + + + + + + + + + + + + + + + + + + + {currentQueue.current} + + { + const item = items.find((i) => i.id === id); + + return !!(item && item.downloadClientHasPostImportCategory); + }) + } + canIgnore={ + isConfirmRemoveModalOpen && + selectedIds.every((id) => { + const item = items.find((i) => i.id === id); + + return !!(item && item.seriesId && item.episodeId); + }) + } + isPending={ + isConfirmRemoveModalOpen && + selectedIds.every((id) => { + const item = items.find((i) => i.id === id); + + if (!item) { + return false; + } + + return ( + item.status === 'delay' || + item.status === 'downloadClientUnavailable' + ); + }) + } + onRemovePress={handleRemoveSelectedConfirmed} + onModalClose={handleConfirmRemoveModalClose} + /> + + ); +} + +export default Queue; diff --git a/frontend/src/Activity/Queue/QueueDetails.css b/frontend/src/Activity/Queue/QueueDetails.css new file mode 100644 index 000000000..b7caba649 --- /dev/null +++ b/frontend/src/Activity/Queue/QueueDetails.css @@ -0,0 +1,5 @@ +.progressBarContainer { + display: flex; + justify-content: center; + width: 100%; +} diff --git a/frontend/src/Activity/Queue/QueueDetails.css.d.ts b/frontend/src/Activity/Queue/QueueDetails.css.d.ts new file mode 100644 index 000000000..4f2287015 --- /dev/null +++ b/frontend/src/Activity/Queue/QueueDetails.css.d.ts @@ -0,0 +1,7 @@ +// This file is automatically generated. +// Please do not change this file! +interface CssExports { + 'progressBarContainer': string; +} +export const cssExports: CssExports; +export default cssExports; diff --git a/frontend/src/Activity/Queue/QueueDetails.tsx b/frontend/src/Activity/Queue/QueueDetails.tsx new file mode 100644 index 000000000..be70ceead --- /dev/null +++ b/frontend/src/Activity/Queue/QueueDetails.tsx @@ -0,0 +1,82 @@ +import React from 'react'; +import Icon from 'Components/Icon'; +import Popover from 'Components/Tooltip/Popover'; +import { icons, tooltipPositions } from 'Helpers/Props'; +import { + QueueTrackedDownloadState, + QueueTrackedDownloadStatus, + StatusMessage, +} from 'typings/Queue'; +import translate from 'Utilities/String/translate'; +import QueueStatus from './QueueStatus'; +import styles from './QueueDetails.css'; + +interface QueueDetailsProps { + title: string; + size: number; + sizeleft: number; + estimatedCompletionTime?: string; + status: string; + trackedDownloadState?: QueueTrackedDownloadState; + trackedDownloadStatus?: QueueTrackedDownloadStatus; + statusMessages?: StatusMessage[]; + errorMessage?: string; + progressBar: React.ReactNode; +} + +function QueueDetails(props: QueueDetailsProps) { + const { + title, + size, + sizeleft, + status, + trackedDownloadState = 'downloading', + trackedDownloadStatus = 'ok', + statusMessages, + errorMessage, + progressBar, + } = props; + + const progress = 100 - (sizeleft / size) * 100; + const isDownloading = status === 'downloading'; + const isPaused = status === 'paused'; + const hasWarning = trackedDownloadStatus === 'warning'; + const hasError = trackedDownloadStatus === 'error'; + + if ((isDownloading || isPaused) && !hasWarning && !hasError) { + const state = isPaused ? translate('Paused') : translate('Downloading'); + + if (progress < 5) { + return ( + + ); + } + + return ( + {title}} + position={tooltipPositions.LEFT} + /> + ); + } + + return ( + + ); +} + +export default QueueDetails; diff --git a/frontend/src/Activity/Queue/QueueFilterModal.tsx b/frontend/src/Activity/Queue/QueueFilterModal.tsx new file mode 100644 index 000000000..3fce6c166 --- /dev/null +++ b/frontend/src/Activity/Queue/QueueFilterModal.tsx @@ -0,0 +1,54 @@ +import React, { useCallback } from 'react'; +import { useDispatch, useSelector } from 'react-redux'; +import { createSelector } from 'reselect'; +import AppState from 'App/State/AppState'; +import FilterModal from 'Components/Filter/FilterModal'; +import { setQueueFilter } from 'Store/Actions/queueActions'; + +function createQueueSelector() { + return createSelector( + (state: AppState) => state.queue.paged.items, + (queueItems) => { + return queueItems; + } + ); +} + +function createFilterBuilderPropsSelector() { + return createSelector( + (state: AppState) => state.queue.paged.filterBuilderProps, + (filterBuilderProps) => { + return filterBuilderProps; + } + ); +} + +interface QueueFilterModalProps { + isOpen: boolean; +} + +export default function QueueFilterModal(props: QueueFilterModalProps) { + const sectionItems = useSelector(createQueueSelector()); + const filterBuilderProps = useSelector(createFilterBuilderPropsSelector()); + const customFilterType = 'queue'; + + const dispatch = useDispatch(); + + const dispatchSetFilter = useCallback( + (payload: unknown) => { + dispatch(setQueueFilter(payload)); + }, + [dispatch] + ); + + return ( + + ); +} diff --git a/frontend/src/Activity/Queue/QueueOptions.tsx b/frontend/src/Activity/Queue/QueueOptions.tsx new file mode 100644 index 000000000..17a6ac1fe --- /dev/null +++ b/frontend/src/Activity/Queue/QueueOptions.tsx @@ -0,0 +1,48 @@ +import React, { useCallback } from 'react'; +import { useDispatch, useSelector } from 'react-redux'; +import AppState from 'App/State/AppState'; +import FormGroup from 'Components/Form/FormGroup'; +import FormInputGroup from 'Components/Form/FormInputGroup'; +import FormLabel from 'Components/Form/FormLabel'; +import { inputTypes } from 'Helpers/Props'; +import { gotoQueuePage, setQueueOption } from 'Store/Actions/queueActions'; +import { CheckInputChanged } from 'typings/inputs'; +import translate from 'Utilities/String/translate'; + +function QueueOptions() { + const dispatch = useDispatch(); + const { includeUnknownSeriesItems } = useSelector( + (state: AppState) => state.queue.options + ); + + const handleOptionChange = useCallback( + ({ name, value }: CheckInputChanged) => { + dispatch( + setQueueOption({ + [name]: value, + }) + ); + + if (name === 'includeUnknownSeriesItems') { + dispatch(gotoQueuePage({ page: 1 })); + } + }, + [dispatch] + ); + + return ( + + {translate('ShowUnknownSeriesItems')} + + + + ); +} + +export default QueueOptions; diff --git a/frontend/src/Activity/Queue/QueueRow.css b/frontend/src/Activity/Queue/QueueRow.css new file mode 100644 index 000000000..459cdad8e --- /dev/null +++ b/frontend/src/Activity/Queue/QueueRow.css @@ -0,0 +1,30 @@ +.quality { + composes: cell from '~Components/Table/Cells/TableRowCell.css'; + + width: 150px; +} + +.protocol { + composes: cell from '~Components/Table/Cells/TableRowCell.css'; + + width: 100px; +} + +.progress { + composes: cell from '~Components/Table/Cells/TableRowCell.css'; + + width: 150px; +} + +.customFormatScore { + composes: cell from '~Components/Table/Cells/TableRowCell.css'; + + width: 55px; +} + +.actions { + composes: cell from '~Components/Table/Cells/TableRowCell.css'; + + width: 70px; + text-align: right; +} diff --git a/frontend/src/Activity/Queue/QueueRow.css.d.ts b/frontend/src/Activity/Queue/QueueRow.css.d.ts new file mode 100644 index 000000000..13d67ea3a --- /dev/null +++ b/frontend/src/Activity/Queue/QueueRow.css.d.ts @@ -0,0 +1,11 @@ +// This file is automatically generated. +// Please do not change this file! +interface CssExports { + 'actions': string; + 'customFormatScore': string; + 'progress': string; + 'protocol': string; + 'quality': string; +} +export const cssExports: CssExports; +export default cssExports; diff --git a/frontend/src/Activity/Queue/QueueRow.tsx b/frontend/src/Activity/Queue/QueueRow.tsx new file mode 100644 index 000000000..25f5cb410 --- /dev/null +++ b/frontend/src/Activity/Queue/QueueRow.tsx @@ -0,0 +1,411 @@ +import React, { useCallback, useState } from 'react'; +import { useDispatch, useSelector } from 'react-redux'; +import ProtocolLabel from 'Activity/Queue/ProtocolLabel'; +import { Error } from 'App/State/AppSectionState'; +import IconButton from 'Components/Link/IconButton'; +import SpinnerIconButton from 'Components/Link/SpinnerIconButton'; +import ProgressBar from 'Components/ProgressBar'; +import RelativeDateCell from 'Components/Table/Cells/RelativeDateCell'; +import TableRowCell from 'Components/Table/Cells/TableRowCell'; +import TableSelectCell from 'Components/Table/Cells/TableSelectCell'; +import Column from 'Components/Table/Column'; +import TableRow from 'Components/Table/TableRow'; +import Tooltip from 'Components/Tooltip/Tooltip'; +import DownloadProtocol from 'DownloadClient/DownloadProtocol'; +import EpisodeFormats from 'Episode/EpisodeFormats'; +import EpisodeLanguages from 'Episode/EpisodeLanguages'; +import EpisodeQuality from 'Episode/EpisodeQuality'; +import EpisodeTitleLink from 'Episode/EpisodeTitleLink'; +import SeasonEpisodeNumber from 'Episode/SeasonEpisodeNumber'; +import useEpisode from 'Episode/useEpisode'; +import { icons, kinds, tooltipPositions } from 'Helpers/Props'; +import InteractiveImportModal from 'InteractiveImport/InteractiveImportModal'; +import Language from 'Language/Language'; +import { QualityModel } from 'Quality/Quality'; +import SeriesTitleLink from 'Series/SeriesTitleLink'; +import useSeries from 'Series/useSeries'; +import { grabQueueItem, removeQueueItem } from 'Store/Actions/queueActions'; +import createUISettingsSelector from 'Store/Selectors/createUISettingsSelector'; +import CustomFormat from 'typings/CustomFormat'; +import { SelectStateInputProps } from 'typings/props'; +import { + QueueTrackedDownloadState, + QueueTrackedDownloadStatus, + StatusMessage, +} from 'typings/Queue'; +import formatBytes from 'Utilities/Number/formatBytes'; +import formatCustomFormatScore from 'Utilities/Number/formatCustomFormatScore'; +import translate from 'Utilities/String/translate'; +import QueueStatusCell from './QueueStatusCell'; +import RemoveQueueItemModal, { RemovePressProps } from './RemoveQueueItemModal'; +import TimeleftCell from './TimeleftCell'; +import styles from './QueueRow.css'; + +interface QueueRowProps { + id: number; + seriesId?: number; + episodeId?: number; + downloadId?: string; + title: string; + status: string; + trackedDownloadStatus?: QueueTrackedDownloadStatus; + trackedDownloadState?: QueueTrackedDownloadState; + statusMessages?: StatusMessage[]; + errorMessage?: string; + languages: Language[]; + quality: QualityModel; + customFormats?: CustomFormat[]; + customFormatScore: number; + protocol: DownloadProtocol; + indexer?: string; + outputPath?: string; + downloadClient?: string; + downloadClientHasPostImportCategory?: boolean; + estimatedCompletionTime?: string; + added?: string; + timeleft?: string; + size: number; + sizeleft: number; + isGrabbing?: boolean; + grabError?: Error; + isRemoving?: boolean; + isSelected?: boolean; + columns: Column[]; + onSelectedChange: (options: SelectStateInputProps) => void; + onQueueRowModalOpenOrClose: (isOpen: boolean) => void; +} + +function QueueRow(props: QueueRowProps) { + const { + id, + seriesId, + episodeId, + downloadId, + title, + status, + trackedDownloadStatus, + trackedDownloadState, + statusMessages, + errorMessage, + languages, + quality, + customFormats = [], + customFormatScore, + protocol, + indexer, + outputPath, + downloadClient, + downloadClientHasPostImportCategory, + estimatedCompletionTime, + added, + timeleft, + size, + sizeleft, + isGrabbing = false, + grabError, + isRemoving = false, + isSelected, + columns, + onSelectedChange, + onQueueRowModalOpenOrClose, + } = props; + + const dispatch = useDispatch(); + const series = useSeries(seriesId); + const episode = useEpisode(episodeId, 'episodes'); + const { showRelativeDates, shortDateFormat, timeFormat } = useSelector( + createUISettingsSelector() + ); + + const [isRemoveQueueItemModalOpen, setIsRemoveQueueItemModalOpen] = + useState(false); + + const [isInteractiveImportModalOpen, setIsInteractiveImportModalOpen] = + useState(false); + + const handleGrabPress = useCallback(() => { + dispatch(grabQueueItem({ id })); + }, [id, dispatch]); + + const handleInteractiveImportPress = useCallback(() => { + onQueueRowModalOpenOrClose(true); + setIsInteractiveImportModalOpen(true); + }, [setIsInteractiveImportModalOpen, onQueueRowModalOpenOrClose]); + + const handleInteractiveImportModalClose = useCallback(() => { + onQueueRowModalOpenOrClose(false); + setIsInteractiveImportModalOpen(false); + }, [setIsInteractiveImportModalOpen, onQueueRowModalOpenOrClose]); + + const handleRemoveQueueItemPress = useCallback(() => { + onQueueRowModalOpenOrClose(true); + setIsRemoveQueueItemModalOpen(true); + }, [setIsRemoveQueueItemModalOpen, onQueueRowModalOpenOrClose]); + + const handleRemoveQueueItemModalConfirmed = useCallback( + (payload: RemovePressProps) => { + onQueueRowModalOpenOrClose(false); + dispatch(removeQueueItem({ id, ...payload })); + setIsRemoveQueueItemModalOpen(false); + }, + [id, setIsRemoveQueueItemModalOpen, onQueueRowModalOpenOrClose, dispatch] + ); + + const handleRemoveQueueItemModalClose = useCallback(() => { + onQueueRowModalOpenOrClose(false); + setIsRemoveQueueItemModalOpen(false); + }, [setIsRemoveQueueItemModalOpen, onQueueRowModalOpenOrClose]); + + const progress = 100 - (sizeleft / size) * 100; + const showInteractiveImport = + status === 'completed' && trackedDownloadStatus === 'warning'; + const isPending = + status === 'delay' || status === 'downloadClientUnavailable'; + + return ( + + + + {columns.map((column) => { + const { name, isVisible } = column; + + if (!isVisible) { + return null; + } + + if (name === 'status') { + return ( + + ); + } + + if (name === 'series.sortTitle') { + return ( + + {series ? ( + + ) : ( + title + )} + + ); + } + + if (name === 'episode') { + return ( + + {episode ? ( + + ) : ( + '-' + )} + + ); + } + + if (name === 'episodes.title') { + return ( + + {series && episode ? ( + + ) : ( + '-' + )} + + ); + } + + if (name === 'episodes.airDateUtc') { + if (episode) { + return ; + } + + return -; + } + + if (name === 'languages') { + return ( + + + + ); + } + + if (name === 'quality') { + return ( + + {quality ? : null} + + ); + } + + if (name === 'customFormats') { + return ( + + + + ); + } + + if (name === 'customFormatScore') { + return ( + + } + position={tooltipPositions.BOTTOM} + /> + + ); + } + + if (name === 'protocol') { + return ( + + + + ); + } + + if (name === 'indexer') { + return {indexer}; + } + + if (name === 'downloadClient') { + return {downloadClient}; + } + + if (name === 'title') { + return {title}; + } + + if (name === 'size') { + return {formatBytes(size)}; + } + + if (name === 'outputPath') { + return {outputPath}; + } + + if (name === 'estimatedCompletionTime') { + return ( + + ); + } + + if (name === 'progress') { + return ( + + {!!progress && ( + + )} + + ); + } + + if (name === 'added') { + return ; + } + + if (name === 'actions') { + return ( + + {showInteractiveImport ? ( + + ) : null} + + {isPending ? ( + + ) : null} + + + + ); + } + + return null; + })} + + + + + + ); +} + +export default QueueRow; diff --git a/frontend/src/Activity/Queue/QueueStatus.css b/frontend/src/Activity/Queue/QueueStatus.css new file mode 100644 index 000000000..566231656 --- /dev/null +++ b/frontend/src/Activity/Queue/QueueStatus.css @@ -0,0 +1,3 @@ +.noMessages { + margin-bottom: 10px; +} diff --git a/frontend/src/Activity/Queue/QueueStatus.css.d.ts b/frontend/src/Activity/Queue/QueueStatus.css.d.ts new file mode 100644 index 000000000..0911f2376 --- /dev/null +++ b/frontend/src/Activity/Queue/QueueStatus.css.d.ts @@ -0,0 +1,7 @@ +// This file is automatically generated. +// Please do not change this file! +interface CssExports { + 'noMessages': string; +} +export const cssExports: CssExports; +export default cssExports; diff --git a/frontend/src/Activity/Queue/QueueStatus.tsx b/frontend/src/Activity/Queue/QueueStatus.tsx new file mode 100644 index 000000000..31a28f35c --- /dev/null +++ b/frontend/src/Activity/Queue/QueueStatus.tsx @@ -0,0 +1,158 @@ +import React from 'react'; +import Icon, { IconProps } from 'Components/Icon'; +import Popover from 'Components/Tooltip/Popover'; +import { icons, kinds } from 'Helpers/Props'; +import { TooltipPosition } from 'Helpers/Props/tooltipPositions'; +import { + QueueTrackedDownloadState, + QueueTrackedDownloadStatus, + StatusMessage, +} from 'typings/Queue'; +import translate from 'Utilities/String/translate'; +import styles from './QueueStatus.css'; + +function getDetailedPopoverBody(statusMessages: StatusMessage[]) { + return ( +
+ {statusMessages.map(({ title, messages }) => { + return ( +
+ {title} +
    + {messages.map((message) => { + return
  • {message}
  • ; + })} +
+
+ ); + })} +
+ ); +} + +interface QueueStatusProps { + sourceTitle: string; + status: string; + trackedDownloadStatus?: QueueTrackedDownloadStatus; + trackedDownloadState?: QueueTrackedDownloadState; + statusMessages?: StatusMessage[]; + errorMessage?: string; + position: TooltipPosition; + canFlip?: boolean; +} + +function QueueStatus(props: QueueStatusProps) { + const { + sourceTitle, + status, + trackedDownloadStatus = 'ok', + trackedDownloadState = 'downloading', + statusMessages = [], + errorMessage, + position, + canFlip = false, + } = props; + + const hasWarning = trackedDownloadStatus === 'warning'; + const hasError = trackedDownloadStatus === 'error'; + + // status === 'downloading' + let iconName = icons.DOWNLOADING; + let iconKind: IconProps['kind'] = kinds.DEFAULT; + let title = translate('Downloading'); + + if (status === 'paused') { + iconName = icons.PAUSED; + title = translate('Paused'); + } + + if (status === 'queued') { + iconName = icons.QUEUED; + title = translate('Queued'); + } + + if (status === 'completed') { + iconName = icons.DOWNLOADED; + title = translate('Downloaded'); + + if (trackedDownloadState === 'importBlocked') { + title += ` - ${translate('UnableToImportAutomatically')}`; + iconKind = kinds.WARNING; + } + + if (trackedDownloadState === 'importPending') { + title += ` - ${translate('WaitingToImport')}`; + iconKind = kinds.PURPLE; + } + + if (trackedDownloadState === 'importing') { + title += ` - ${translate('Importing')}`; + iconKind = kinds.PURPLE; + } + + if (trackedDownloadState === 'failedPending') { + title += ` - ${translate('WaitingToProcess')}`; + iconKind = kinds.DANGER; + } + } + + if (hasWarning) { + iconKind = kinds.WARNING; + } + + if (status === 'delay') { + iconName = icons.PENDING; + title = translate('Pending'); + } + + if (status === 'downloadClientUnavailable') { + iconName = icons.PENDING; + iconKind = kinds.WARNING; + title = translate('PendingDownloadClientUnavailable'); + } + + if (status === 'failed') { + iconName = icons.DOWNLOADING; + iconKind = kinds.DANGER; + title = translate('DownloadFailed'); + } + + if (status === 'warning') { + iconName = icons.DOWNLOADING; + iconKind = kinds.WARNING; + const warningMessage = + errorMessage || translate('CheckDownloadClientForDetails'); + title = translate('DownloadWarning', { warningMessage }); + } + + if (hasError) { + if (status === 'completed') { + iconName = icons.DOWNLOAD; + iconKind = kinds.DANGER; + title = translate('ImportFailed', { sourceTitle }); + } else { + iconName = icons.DOWNLOADING; + iconKind = kinds.DANGER; + title = translate('DownloadFailed'); + } + } + + return ( + } + title={title} + body={ + hasWarning || hasError + ? getDetailedPopoverBody(statusMessages) + : sourceTitle + } + position={position} + canFlip={canFlip} + /> + ); +} + +export default QueueStatus; diff --git a/frontend/src/Activity/Queue/QueueStatusCell.css b/frontend/src/Activity/Queue/QueueStatusCell.css new file mode 100644 index 000000000..538d5a15d --- /dev/null +++ b/frontend/src/Activity/Queue/QueueStatusCell.css @@ -0,0 +1,9 @@ +.status { + composes: cell from '~Components/Table/Cells/TableRowCell.css'; + + width: 30px; +} + +.noMessages { + margin-bottom: 10px; +} diff --git a/frontend/src/Activity/Queue/QueueStatusCell.css.d.ts b/frontend/src/Activity/Queue/QueueStatusCell.css.d.ts new file mode 100644 index 000000000..aefdc03b9 --- /dev/null +++ b/frontend/src/Activity/Queue/QueueStatusCell.css.d.ts @@ -0,0 +1,8 @@ +// This file is automatically generated. +// Please do not change this file! +interface CssExports { + 'noMessages': string; + 'status': string; +} +export const cssExports: CssExports; +export default cssExports; diff --git a/frontend/src/Activity/Queue/QueueStatusCell.tsx b/frontend/src/Activity/Queue/QueueStatusCell.tsx new file mode 100644 index 000000000..634e33164 --- /dev/null +++ b/frontend/src/Activity/Queue/QueueStatusCell.tsx @@ -0,0 +1,45 @@ +import React from 'react'; +import TableRowCell from 'Components/Table/Cells/TableRowCell'; +import { + QueueTrackedDownloadState, + QueueTrackedDownloadStatus, + StatusMessage, +} from 'typings/Queue'; +import QueueStatus from './QueueStatus'; +import styles from './QueueStatusCell.css'; + +interface QueueStatusCellProps { + sourceTitle: string; + status: string; + trackedDownloadStatus?: QueueTrackedDownloadStatus; + trackedDownloadState?: QueueTrackedDownloadState; + statusMessages?: StatusMessage[]; + errorMessage?: string; +} + +function QueueStatusCell(props: QueueStatusCellProps) { + const { + sourceTitle, + status, + trackedDownloadStatus = 'ok', + trackedDownloadState = 'downloading', + statusMessages, + errorMessage, + } = props; + + return ( + + + + ); +} + +export default QueueStatusCell; diff --git a/frontend/src/Activity/Queue/RemoveQueueItemModal.css b/frontend/src/Activity/Queue/RemoveQueueItemModal.css new file mode 100644 index 000000000..c9ef59ec1 --- /dev/null +++ b/frontend/src/Activity/Queue/RemoveQueueItemModal.css @@ -0,0 +1,3 @@ +.message { + margin-bottom: 30px; +} diff --git a/frontend/src/Activity/Queue/RemoveQueueItemModal.css.d.ts b/frontend/src/Activity/Queue/RemoveQueueItemModal.css.d.ts new file mode 100644 index 000000000..65c237dff --- /dev/null +++ b/frontend/src/Activity/Queue/RemoveQueueItemModal.css.d.ts @@ -0,0 +1,7 @@ +// This file is automatically generated. +// Please do not change this file! +interface CssExports { + 'message': string; +} +export const cssExports: CssExports; +export default cssExports; diff --git a/frontend/src/Activity/Queue/RemoveQueueItemModal.tsx b/frontend/src/Activity/Queue/RemoveQueueItemModal.tsx new file mode 100644 index 000000000..461fa57ad --- /dev/null +++ b/frontend/src/Activity/Queue/RemoveQueueItemModal.tsx @@ -0,0 +1,231 @@ +import React, { useCallback, useMemo, useState } from 'react'; +import FormGroup from 'Components/Form/FormGroup'; +import FormInputGroup from 'Components/Form/FormInputGroup'; +import FormLabel from 'Components/Form/FormLabel'; +import Button from 'Components/Link/Button'; +import Modal from 'Components/Modal/Modal'; +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 { inputTypes, kinds, sizes } from 'Helpers/Props'; +import translate from 'Utilities/String/translate'; +import styles from './RemoveQueueItemModal.css'; + +export interface RemovePressProps { + remove: boolean; + changeCategory: boolean; + blocklist: boolean; + skipRedownload: boolean; +} + +interface RemoveQueueItemModalProps { + isOpen: boolean; + sourceTitle?: string; + canChangeCategory: boolean; + canIgnore: boolean; + isPending: boolean; + selectedCount?: number; + onRemovePress(props: RemovePressProps): void; + onModalClose: () => void; +} + +type RemovalMethod = 'removeFromClient' | 'changeCategory' | 'ignore'; +type BlocklistMethod = + | 'doNotBlocklist' + | 'blocklistAndSearch' + | 'blocklistOnly'; + +function RemoveQueueItemModal(props: RemoveQueueItemModalProps) { + const { + isOpen, + sourceTitle = '', + canIgnore, + canChangeCategory, + isPending, + selectedCount, + onRemovePress, + onModalClose, + } = props; + + const multipleSelected = selectedCount && selectedCount > 1; + + const [removalMethod, setRemovalMethod] = + useState('removeFromClient'); + const [blocklistMethod, setBlocklistMethod] = + useState('doNotBlocklist'); + + const { title, message } = useMemo(() => { + if (!selectedCount) { + return { + title: translate('RemoveQueueItem', { sourceTitle }), + message: translate('RemoveQueueItemConfirmation', { sourceTitle }), + }; + } + + if (selectedCount === 1) { + return { + title: translate('RemoveSelectedItem'), + message: translate('RemoveSelectedItemQueueMessageText'), + }; + } + + return { + title: translate('RemoveSelectedItems'), + message: translate('RemoveSelectedItemsQueueMessageText', { + selectedCount, + }), + }; + }, [sourceTitle, selectedCount]); + + const removalMethodOptions = useMemo(() => { + return [ + { + key: 'removeFromClient', + value: translate('RemoveFromDownloadClient'), + hint: multipleSelected + ? translate('RemoveMultipleFromDownloadClientHint') + : translate('RemoveFromDownloadClientHint'), + }, + { + key: 'changeCategory', + value: translate('ChangeCategory'), + isDisabled: !canChangeCategory, + hint: multipleSelected + ? translate('ChangeCategoryMultipleHint') + : translate('ChangeCategoryHint'), + }, + { + key: 'ignore', + value: multipleSelected + ? translate('IgnoreDownloads') + : translate('IgnoreDownload'), + isDisabled: !canIgnore, + hint: multipleSelected + ? translate('IgnoreDownloadsHint') + : translate('IgnoreDownloadHint'), + }, + ]; + }, [canChangeCategory, canIgnore, multipleSelected]); + + const blocklistMethodOptions = useMemo(() => { + return [ + { + key: 'doNotBlocklist', + value: translate('DoNotBlocklist'), + hint: translate('DoNotBlocklistHint'), + }, + { + key: 'blocklistAndSearch', + value: translate('BlocklistAndSearch'), + isDisabled: isPending, + hint: multipleSelected + ? translate('BlocklistAndSearchMultipleHint') + : translate('BlocklistAndSearchHint'), + }, + { + key: 'blocklistOnly', + value: translate('BlocklistOnly'), + hint: multipleSelected + ? translate('BlocklistMultipleOnlyHint') + : translate('BlocklistOnlyHint'), + }, + ]; + }, [isPending, multipleSelected]); + + const handleRemovalMethodChange = useCallback( + ({ value }: { value: RemovalMethod }) => { + setRemovalMethod(value); + }, + [setRemovalMethod] + ); + + const handleBlocklistMethodChange = useCallback( + ({ value }: { value: BlocklistMethod }) => { + setBlocklistMethod(value); + }, + [setBlocklistMethod] + ); + + const handleConfirmRemove = useCallback(() => { + onRemovePress({ + remove: removalMethod === 'removeFromClient', + changeCategory: removalMethod === 'changeCategory', + blocklist: blocklistMethod !== 'doNotBlocklist', + skipRedownload: blocklistMethod === 'blocklistOnly', + }); + + setRemovalMethod('removeFromClient'); + setBlocklistMethod('doNotBlocklist'); + }, [ + removalMethod, + blocklistMethod, + setRemovalMethod, + setBlocklistMethod, + onRemovePress, + ]); + + const handleModalClose = useCallback(() => { + setRemovalMethod('removeFromClient'); + setBlocklistMethod('doNotBlocklist'); + + onModalClose(); + }, [setRemovalMethod, setBlocklistMethod, onModalClose]); + + return ( + + + {title} + + +
{message}
+ + {isPending ? null : ( + + {translate('RemoveQueueItemRemovalMethod')} + + + + )} + + + + {multipleSelected + ? translate('BlocklistReleases') + : translate('BlocklistRelease')} + + + + +
+ + + + + + +
+
+ ); +} + +export default RemoveQueueItemModal; diff --git a/frontend/src/Activity/Queue/Status/QueueStatus.tsx b/frontend/src/Activity/Queue/Status/QueueStatus.tsx new file mode 100644 index 000000000..894434e07 --- /dev/null +++ b/frontend/src/Activity/Queue/Status/QueueStatus.tsx @@ -0,0 +1,37 @@ +import React, { useEffect } from 'react'; +import { useDispatch, useSelector } from 'react-redux'; +import AppState from 'App/State/AppState'; +import PageSidebarStatus from 'Components/Page/Sidebar/PageSidebarStatus'; +import usePrevious from 'Helpers/Hooks/usePrevious'; +import { fetchQueueStatus } from 'Store/Actions/queueActions'; +import createQueueStatusSelector from './createQueueStatusSelector'; + +function QueueStatus() { + const dispatch = useDispatch(); + const { isConnected, isReconnecting } = useSelector( + (state: AppState) => state.app + ); + const { isPopulated, count, errors, warnings } = useSelector( + createQueueStatusSelector() + ); + + const wasReconnecting = usePrevious(isReconnecting); + + useEffect(() => { + if (!isPopulated) { + dispatch(fetchQueueStatus()); + } + }, [isPopulated, dispatch]); + + useEffect(() => { + if (isConnected && wasReconnecting) { + dispatch(fetchQueueStatus()); + } + }, [isConnected, wasReconnecting, dispatch]); + + return ( + + ); +} + +export default QueueStatus; diff --git a/frontend/src/Activity/Queue/Status/createQueueStatusSelector.ts b/frontend/src/Activity/Queue/Status/createQueueStatusSelector.ts new file mode 100644 index 000000000..4fd37b28c --- /dev/null +++ b/frontend/src/Activity/Queue/Status/createQueueStatusSelector.ts @@ -0,0 +1,32 @@ +import { createSelector } from 'reselect'; +import AppState from 'App/State/AppState'; + +function createQueueStatusSelector() { + return createSelector( + (state: AppState) => state.queue.status.isPopulated, + (state: AppState) => state.queue.status.item, + (state: AppState) => state.queue.options.includeUnknownSeriesItems, + (isPopulated, status, includeUnknownSeriesItems) => { + const { + errors, + warnings, + unknownErrors, + unknownWarnings, + count, + totalCount, + } = status; + + return { + ...status, + isPopulated, + count: includeUnknownSeriesItems ? totalCount : count, + errors: includeUnknownSeriesItems ? errors || unknownErrors : errors, + warnings: includeUnknownSeriesItems + ? warnings || unknownWarnings + : warnings, + }; + } + ); +} + +export default createQueueStatusSelector; diff --git a/frontend/src/Activity/Queue/TimeleftCell.css b/frontend/src/Activity/Queue/TimeleftCell.css new file mode 100644 index 000000000..cc6001a22 --- /dev/null +++ b/frontend/src/Activity/Queue/TimeleftCell.css @@ -0,0 +1,5 @@ +.timeleft { + composes: cell from '~Components/Table/Cells/TableRowCell.css'; + + width: 100px; +} diff --git a/frontend/src/Activity/Queue/TimeleftCell.css.d.ts b/frontend/src/Activity/Queue/TimeleftCell.css.d.ts new file mode 100644 index 000000000..f5c9402d1 --- /dev/null +++ b/frontend/src/Activity/Queue/TimeleftCell.css.d.ts @@ -0,0 +1,7 @@ +// This file is automatically generated. +// Please do not change this file! +interface CssExports { + 'timeleft': string; +} +export const cssExports: CssExports; +export default cssExports; diff --git a/frontend/src/Activity/Queue/TimeleftCell.tsx b/frontend/src/Activity/Queue/TimeleftCell.tsx new file mode 100644 index 000000000..917a6ad0d --- /dev/null +++ b/frontend/src/Activity/Queue/TimeleftCell.tsx @@ -0,0 +1,97 @@ +import React from 'react'; +import Icon from 'Components/Icon'; +import TableRowCell from 'Components/Table/Cells/TableRowCell'; +import Tooltip from 'Components/Tooltip/Tooltip'; +import { icons, kinds, tooltipPositions } from 'Helpers/Props'; +import formatTime from 'Utilities/Date/formatTime'; +import formatTimeSpan from 'Utilities/Date/formatTimeSpan'; +import getRelativeDate from 'Utilities/Date/getRelativeDate'; +import formatBytes from 'Utilities/Number/formatBytes'; +import translate from 'Utilities/String/translate'; +import styles from './TimeleftCell.css'; + +interface TimeleftCellProps { + estimatedCompletionTime?: string; + timeleft?: string; + status: string; + size: number; + sizeleft: number; + showRelativeDates: boolean; + shortDateFormat: string; + timeFormat: string; +} + +function TimeleftCell(props: TimeleftCellProps) { + const { + estimatedCompletionTime, + timeleft, + status, + size, + sizeleft, + showRelativeDates, + shortDateFormat, + timeFormat, + } = props; + + if (status === 'delay') { + const date = getRelativeDate({ + date: estimatedCompletionTime, + shortDateFormat, + showRelativeDates, + }); + const time = formatTime(estimatedCompletionTime, timeFormat, { + includeMinuteZero: true, + }); + + return ( + + } + tooltip={translate('DelayingDownloadUntil', { date, time })} + kind={kinds.INVERSE} + position={tooltipPositions.TOP} + /> + + ); + } + + if (status === 'downloadClientUnavailable') { + const date = getRelativeDate({ + date: estimatedCompletionTime, + shortDateFormat, + showRelativeDates, + }); + const time = formatTime(estimatedCompletionTime, timeFormat, { + includeMinuteZero: true, + }); + + return ( + + } + tooltip={translate('RetryingDownloadOn', { date, time })} + kind={kinds.INVERSE} + position={tooltipPositions.TOP} + /> + + ); + } + + if (!timeleft || status === 'completed' || status === 'failed') { + return -; + } + + const totalSize = formatBytes(size); + const remainingSize = formatBytes(sizeleft); + + return ( + + {formatTimeSpan(timeleft)} + + ); +} + +export default TimeleftCell; diff --git a/frontend/src/AddSeries/AddNewSeries/AddNewSeries.css b/frontend/src/AddSeries/AddNewSeries/AddNewSeries.css new file mode 100644 index 000000000..d41571320 --- /dev/null +++ b/frontend/src/AddSeries/AddNewSeries/AddNewSeries.css @@ -0,0 +1,60 @@ +.searchContainer { + display: flex; + margin-bottom: 10px; +} + +.searchIconContainer { + width: 58px; + height: 46px; + border: 1px solid var(--inputBorderColor); + border-right: none; + border-radius: 4px; + border-top-right-radius: 0; + border-bottom-right-radius: 0; + background-color: var(--searchIconContainerBackgroundColor); + text-align: center; + line-height: 46px; +} + +.searchInput { + composes: input from '~Components/Form/TextInput.css'; + + height: 46px; + border-radius: 0; + font-size: 18px; +} + +.clearLookupButton { + border: 1px solid var(--inputBorderColor); + border-left: none; + border-top-right-radius: 4px; + border-bottom-right-radius: 4px; + box-shadow: inset 0 1px 1px rgba(0, 0, 0, 0.075); +} + +.message { + margin-top: 30px; + text-align: center; + font-weight: 300; + font-size: $largeFontSize; +} + +.helpText { + margin-bottom: 10px; + font-size: 24px; +} + +.noSeriesText { + margin-top: 80px; + margin-bottom: 20px; +} + +.noResults { + margin-bottom: 10px; + font-weight: 300; + font-size: 30px; +} + +.searchResults { + margin-top: 30px; +} diff --git a/frontend/src/AddSeries/AddNewSeries/AddNewSeries.css.d.ts b/frontend/src/AddSeries/AddNewSeries/AddNewSeries.css.d.ts new file mode 100644 index 000000000..176938a16 --- /dev/null +++ b/frontend/src/AddSeries/AddNewSeries/AddNewSeries.css.d.ts @@ -0,0 +1,15 @@ +// This file is automatically generated. +// Please do not change this file! +interface CssExports { + 'clearLookupButton': string; + 'helpText': string; + 'message': string; + 'noResults': string; + 'noSeriesText': string; + 'searchContainer': string; + 'searchIconContainer': string; + 'searchInput': string; + 'searchResults': string; +} +export const cssExports: CssExports; +export default cssExports; diff --git a/frontend/src/AddSeries/AddNewSeries/AddNewSeries.js b/frontend/src/AddSeries/AddNewSeries/AddNewSeries.js new file mode 100644 index 000000000..18cbffddb --- /dev/null +++ b/frontend/src/AddSeries/AddNewSeries/AddNewSeries.js @@ -0,0 +1,215 @@ +import PropTypes from 'prop-types'; +import React, { Component } from 'react'; +import Alert from 'Components/Alert'; +import TextInput from 'Components/Form/TextInput'; +import Icon from 'Components/Icon'; +import Button from 'Components/Link/Button'; +import Link from 'Components/Link/Link'; +import LoadingIndicator from 'Components/Loading/LoadingIndicator'; +import PageContent from 'Components/Page/PageContent'; +import PageContentBody from 'Components/Page/PageContentBody'; +import { icons, kinds } from 'Helpers/Props'; +import getErrorMessage from 'Utilities/Object/getErrorMessage'; +import translate from 'Utilities/String/translate'; +import AddNewSeriesSearchResultConnector from './AddNewSeriesSearchResultConnector'; +import styles from './AddNewSeries.css'; + +class AddNewSeries extends Component { + + // + // Lifecycle + + constructor(props, context) { + super(props, context); + + this.state = { + term: props.term || '', + isFetching: false + }; + } + + componentDidMount() { + const term = this.state.term; + + if (term) { + this.props.onSeriesLookupChange(term); + } + } + + componentDidUpdate(prevProps) { + const { + term, + isFetching + } = this.props; + + if (term && term !== prevProps.term) { + this.setState({ + term, + isFetching: true + }); + this.props.onSeriesLookupChange(term); + } else if (isFetching !== prevProps.isFetching) { + this.setState({ + isFetching + }); + } + } + + // + // Listeners + + onSearchInputChange = ({ value }) => { + const hasValue = !!value.trim(); + + this.setState({ term: value, isFetching: hasValue }, () => { + if (hasValue) { + this.props.onSeriesLookupChange(value); + } else { + this.props.onClearSeriesLookup(); + } + }); + }; + + onClearSeriesLookupPress = () => { + this.setState({ term: '' }); + this.props.onClearSeriesLookup(); + }; + + // + // Render + + render() { + const { + error, + items, + hasExistingSeries + } = this.props; + + const term = this.state.term; + const isFetching = this.state.isFetching; + + return ( + + +
+
+ +
+ + + + +
+ + { + isFetching && + + } + + { + !isFetching && !!error ? +
+
+ {translate('AddNewSeriesError')} +
+ + {getErrorMessage(error)} +
: null + } + + { + !isFetching && !error && !!items.length && +
+ { + items.map((item) => { + return ( + + ); + }) + } +
+ } + + { + !isFetching && !error && !items.length && !!term && +
+
{translate('CouldNotFindResults', { term })}
+
{translate('SearchByTvdbId')}
+
+ + {translate('WhyCantIFindMyShow')} + +
+
+ } + + { + term ? + null : +
+
+ {translate('AddNewSeriesHelpText')} +
+
{translate('SearchByTvdbId')}
+
+ } + + { + !term && !hasExistingSeries ? +
+
+ {translate('NoSeriesHaveBeenAdded')} +
+
+ +
+
: + null + } + +
+ + + ); + } +} + +AddNewSeries.propTypes = { + term: PropTypes.string, + isFetching: PropTypes.bool.isRequired, + error: PropTypes.object, + isAdding: PropTypes.bool.isRequired, + addError: PropTypes.object, + items: PropTypes.arrayOf(PropTypes.object).isRequired, + hasExistingSeries: PropTypes.bool.isRequired, + onSeriesLookupChange: PropTypes.func.isRequired, + onClearSeriesLookup: PropTypes.func.isRequired +}; + +export default AddNewSeries; diff --git a/frontend/src/AddSeries/AddNewSeries/AddNewSeriesConnector.js b/frontend/src/AddSeries/AddNewSeries/AddNewSeriesConnector.js new file mode 100644 index 000000000..a80a94fca --- /dev/null +++ b/frontend/src/AddSeries/AddNewSeries/AddNewSeriesConnector.js @@ -0,0 +1,104 @@ +import PropTypes from 'prop-types'; +import React, { Component } from 'react'; +import { connect } from 'react-redux'; +import { createSelector } from 'reselect'; +import { clearAddSeries, lookupSeries } from 'Store/Actions/addSeriesActions'; +import { fetchRootFolders } from 'Store/Actions/rootFolderActions'; +import parseUrl from 'Utilities/String/parseUrl'; +import AddNewSeries from './AddNewSeries'; + +function createMapStateToProps() { + return createSelector( + (state) => state.addSeries, + (state) => state.series.items.length, + (state) => state.router.location, + (addSeries, existingSeriesCount, location) => { + const { params } = parseUrl(location.search); + + return { + ...addSeries, + term: params.term, + hasExistingSeries: existingSeriesCount > 0 + }; + } + ); +} + +const mapDispatchToProps = { + lookupSeries, + clearAddSeries, + fetchRootFolders +}; + +class AddNewSeriesConnector extends Component { + + // + // Lifecycle + + constructor(props, context) { + super(props, context); + + this._seriesLookupTimeout = null; + } + + componentDidMount() { + this.props.fetchRootFolders(); + } + + componentWillUnmount() { + if (this._seriesLookupTimeout) { + clearTimeout(this._seriesLookupTimeout); + } + + this.props.clearAddSeries(); + } + + // + // Listeners + + onSeriesLookupChange = (term) => { + if (this._seriesLookupTimeout) { + clearTimeout(this._seriesLookupTimeout); + } + + if (term.trim() === '') { + this.props.clearAddSeries(); + } else { + this._seriesLookupTimeout = setTimeout(() => { + this.props.lookupSeries({ term }); + }, 300); + } + }; + + onClearSeriesLookup = () => { + this.props.clearAddSeries(); + }; + + // + // Render + + render() { + const { + term, + ...otherProps + } = this.props; + + return ( + + ); + } +} + +AddNewSeriesConnector.propTypes = { + term: PropTypes.string, + lookupSeries: PropTypes.func.isRequired, + clearAddSeries: PropTypes.func.isRequired, + fetchRootFolders: PropTypes.func.isRequired +}; + +export default connect(createMapStateToProps, mapDispatchToProps)(AddNewSeriesConnector); diff --git a/frontend/src/AddSeries/AddNewSeries/AddNewSeriesModal.js b/frontend/src/AddSeries/AddNewSeries/AddNewSeriesModal.js new file mode 100644 index 000000000..cb603e7a6 --- /dev/null +++ b/frontend/src/AddSeries/AddNewSeries/AddNewSeriesModal.js @@ -0,0 +1,31 @@ +import PropTypes from 'prop-types'; +import React from 'react'; +import Modal from 'Components/Modal/Modal'; +import AddNewSeriesModalContentConnector from './AddNewSeriesModalContentConnector'; + +function AddNewSeriesModal(props) { + const { + isOpen, + onModalClose, + ...otherProps + } = props; + + return ( + + + + ); +} + +AddNewSeriesModal.propTypes = { + isOpen: PropTypes.bool.isRequired, + onModalClose: PropTypes.func.isRequired +}; + +export default AddNewSeriesModal; diff --git a/frontend/src/AddSeries/AddNewSeries/AddNewSeriesModalContent.css b/frontend/src/AddSeries/AddNewSeries/AddNewSeriesModalContent.css new file mode 100644 index 000000000..5da3d9b96 --- /dev/null +++ b/frontend/src/AddSeries/AddNewSeries/AddNewSeriesModalContent.css @@ -0,0 +1,69 @@ +.container { + display: flex; +} + +.year { + margin-left: 5px; + color: var(--disabledColor); +} + +.poster { + flex: 0 0 170px; + margin-right: 20px; + height: 250px; +} + +.info { + flex-grow: 1; +} + +.overview { + margin-bottom: 30px; +} + +.labelIcon { + margin-left: 8px; +} + +.searchLabelContainer { + display: flex; + justify-content: flex-end; + margin-top: 2px; +} + +.searchLabel { + margin-right: 8px; + font-weight: normal; +} + +.searchInputContainer { + composes: container from '~Components/Form/CheckInput.css'; + + flex: 0 1 0; +} + +.searchInput { + composes: input from '~Components/Form/CheckInput.css'; + + margin-top: 0; +} + +.modalFooter { + composes: modalFooter from '~Components/Modal/ModalFooter.css'; +} + +.addButton { + @add-mixin truncate; + composes: button from '~Components/Link/SpinnerButton.css'; +} + +@media only screen and (max-width: $breakpointSmall) { + .modalFooter { + display: block; + text-align: center; + } + + .addButton { + margin-top: 10px; + } +} diff --git a/frontend/src/AddSeries/AddNewSeries/AddNewSeriesModalContent.css.d.ts b/frontend/src/AddSeries/AddNewSeries/AddNewSeriesModalContent.css.d.ts new file mode 100644 index 000000000..554ff6ff3 --- /dev/null +++ b/frontend/src/AddSeries/AddNewSeries/AddNewSeriesModalContent.css.d.ts @@ -0,0 +1,18 @@ +// This file is automatically generated. +// Please do not change this file! +interface CssExports { + 'addButton': string; + 'container': string; + 'info': string; + 'labelIcon': string; + 'modalFooter': string; + 'overview': string; + 'poster': string; + 'searchInput': string; + 'searchInputContainer': string; + 'searchLabel': string; + 'searchLabelContainer': string; + 'year': string; +} +export const cssExports: CssExports; +export default cssExports; diff --git a/frontend/src/AddSeries/AddNewSeries/AddNewSeriesModalContent.js b/frontend/src/AddSeries/AddNewSeries/AddNewSeriesModalContent.js new file mode 100644 index 000000000..285c00ecb --- /dev/null +++ b/frontend/src/AddSeries/AddNewSeries/AddNewSeriesModalContent.js @@ -0,0 +1,300 @@ +import PropTypes from 'prop-types'; +import React, { Component } from 'react'; +import SeriesMonitoringOptionsPopoverContent from 'AddSeries/SeriesMonitoringOptionsPopoverContent'; +import SeriesTypePopoverContent from 'AddSeries/SeriesTypePopoverContent'; +import CheckInput from 'Components/Form/CheckInput'; +import Form from 'Components/Form/Form'; +import FormGroup from 'Components/Form/FormGroup'; +import FormInputGroup from 'Components/Form/FormInputGroup'; +import FormLabel from 'Components/Form/FormLabel'; +import Icon from 'Components/Icon'; +import SpinnerButton from 'Components/Link/SpinnerButton'; +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 Popover from 'Components/Tooltip/Popover'; +import { icons, inputTypes, kinds, tooltipPositions } from 'Helpers/Props'; +import SeriesPoster from 'Series/SeriesPoster'; +import * as seriesTypes from 'Utilities/Series/seriesTypes'; +import translate from 'Utilities/String/translate'; +import styles from './AddNewSeriesModalContent.css'; + +class AddNewSeriesModalContent extends Component { + + // + // Lifecycle + + constructor(props, context) { + super(props, context); + + this.state = { + seriesType: props.initialSeriesType === seriesTypes.STANDARD ? + props.seriesType.value : + props.initialSeriesType + }; + } + + componentDidUpdate(prevProps) { + if (this.props.seriesType.value !== prevProps.seriesType.value) { + this.setState({ seriesType: this.props.seriesType.value }); + } + } + + // + // Listeners + + onQualityProfileIdChange = ({ value }) => { + this.props.onInputChange({ name: 'qualityProfileId', value: parseInt(value) }); + }; + + onAddSeriesPress = () => { + const { + seriesType + } = this.state; + + this.props.onAddSeriesPress( + seriesType + ); + }; + + // + // Render + + render() { + const { + title, + year, + overview, + images, + isAdding, + rootFolderPath, + monitor, + qualityProfileId, + seriesType, + seasonFolder, + searchForMissingEpisodes, + searchForCutoffUnmetEpisodes, + folder, + tags, + isSmallScreen, + isWindows, + onModalClose, + onInputChange, + ...otherProps + } = this.props; + + return ( + + + {title} + + { + !title.contains(year) && !!year && + ({year}) + } + + + +
+ { + isSmallScreen ? + null : +
+ +
+ } + +
+ { + overview ? +
+ {overview} +
: + null + } + +
+ + {translate('RootFolder')} + + + + + + + {translate('Monitor')} + + + } + title={translate('MonitoringOptions')} + body={} + position={tooltipPositions.RIGHT} + /> + + + + + + + {translate('QualityProfile')} + + + + + + + {translate('SeriesType')} + + + } + title={translate('SeriesTypes')} + body={} + position={tooltipPositions.RIGHT} + /> + + + + + + + {translate('SeasonFolder')} + + + + + + {translate('Tags')} + + + +
+
+
+
+ + +
+ + + +
+ + + {translate('AddSeriesWithTitle', { title })} + +
+
+ ); + } +} + +AddNewSeriesModalContent.propTypes = { + title: PropTypes.string.isRequired, + year: PropTypes.number.isRequired, + overview: PropTypes.string, + initialSeriesType: PropTypes.string.isRequired, + images: PropTypes.arrayOf(PropTypes.object).isRequired, + isAdding: PropTypes.bool.isRequired, + addError: PropTypes.object, + rootFolderPath: PropTypes.object, + monitor: PropTypes.object.isRequired, + qualityProfileId: PropTypes.object, + seriesType: PropTypes.object.isRequired, + seasonFolder: PropTypes.object.isRequired, + searchForMissingEpisodes: PropTypes.object.isRequired, + searchForCutoffUnmetEpisodes: PropTypes.object.isRequired, + folder: PropTypes.string.isRequired, + tags: PropTypes.object.isRequired, + isSmallScreen: PropTypes.bool.isRequired, + isWindows: PropTypes.bool.isRequired, + onModalClose: PropTypes.func.isRequired, + onInputChange: PropTypes.func.isRequired, + onAddSeriesPress: PropTypes.func.isRequired +}; + +export default AddNewSeriesModalContent; diff --git a/frontend/src/AddSeries/AddNewSeries/AddNewSeriesModalContentConnector.js b/frontend/src/AddSeries/AddNewSeries/AddNewSeriesModalContentConnector.js new file mode 100644 index 000000000..f40b3a2f1 --- /dev/null +++ b/frontend/src/AddSeries/AddNewSeries/AddNewSeriesModalContentConnector.js @@ -0,0 +1,110 @@ +import PropTypes from 'prop-types'; +import React, { Component } from 'react'; +import { connect } from 'react-redux'; +import { createSelector } from 'reselect'; +import { addSeries, setAddSeriesDefault } from 'Store/Actions/addSeriesActions'; +import createDimensionsSelector from 'Store/Selectors/createDimensionsSelector'; +import createSystemStatusSelector from 'Store/Selectors/createSystemStatusSelector'; +import selectSettings from 'Store/Selectors/selectSettings'; +import AddNewSeriesModalContent from './AddNewSeriesModalContent'; + +function createMapStateToProps() { + return createSelector( + (state) => state.addSeries, + createDimensionsSelector(), + createSystemStatusSelector(), + (addSeriesState, dimensions, systemStatus) => { + const { + isAdding, + addError, + defaults + } = addSeriesState; + + const { + settings, + validationErrors, + validationWarnings + } = selectSettings(defaults, {}, addError); + + return { + isAdding, + addError, + isSmallScreen: dimensions.isSmallScreen, + validationErrors, + validationWarnings, + isWindows: systemStatus.isWindows, + ...settings + }; + } + ); +} + +const mapDispatchToProps = { + setAddSeriesDefault, + addSeries +}; + +class AddNewSeriesModalContentConnector extends Component { + + // + // Listeners + + onInputChange = ({ name, value }) => { + this.props.setAddSeriesDefault({ [name]: value }); + }; + + onAddSeriesPress = (seriesType) => { + const { + tvdbId, + rootFolderPath, + monitor, + qualityProfileId, + seasonFolder, + searchForMissingEpisodes, + searchForCutoffUnmetEpisodes, + tags + } = this.props; + + this.props.addSeries({ + tvdbId, + rootFolderPath: rootFolderPath.value, + monitor: monitor.value, + qualityProfileId: qualityProfileId.value, + seriesType, + seasonFolder: seasonFolder.value, + searchForMissingEpisodes: searchForMissingEpisodes.value, + searchForCutoffUnmetEpisodes: searchForCutoffUnmetEpisodes.value, + tags: tags.value + }); + }; + + // + // Render + + render() { + return ( + + ); + } +} + +AddNewSeriesModalContentConnector.propTypes = { + tvdbId: PropTypes.number.isRequired, + rootFolderPath: PropTypes.object, + monitor: PropTypes.object.isRequired, + qualityProfileId: PropTypes.object, + seriesType: PropTypes.object.isRequired, + seasonFolder: PropTypes.object.isRequired, + searchForMissingEpisodes: PropTypes.object.isRequired, + searchForCutoffUnmetEpisodes: PropTypes.object.isRequired, + tags: PropTypes.object.isRequired, + onModalClose: PropTypes.func.isRequired, + setAddSeriesDefault: PropTypes.func.isRequired, + addSeries: PropTypes.func.isRequired +}; + +export default connect(createMapStateToProps, mapDispatchToProps)(AddNewSeriesModalContentConnector); diff --git a/frontend/src/AddSeries/AddNewSeries/AddNewSeriesSearchResult.css b/frontend/src/AddSeries/AddNewSeries/AddNewSeriesSearchResult.css new file mode 100644 index 000000000..dcf3f6de3 --- /dev/null +++ b/frontend/src/AddSeries/AddNewSeries/AddNewSeriesSearchResult.css @@ -0,0 +1,113 @@ +.searchResult { + position: relative; + margin: 20px 0; + padding: 20px; + width: 100%; + color: inherit; +} + +.underlay { + @add-mixin cover; + + background-color: var(--addSeriesBackgroundColor); + transition: background 500ms; + + &:hover { + background-color: var(--pageBackground); + box-shadow: 0 0 12px var(--black); + color: inherit; + text-decoration: none; + transition: all 200ms ease-in; + } +} + +.overlay { + @add-mixin linkOverlay; + + position: relative; + display: flex; +} + +.poster { + flex: 0 0 170px; + margin-right: 20px; + height: 250px; +} + +.content { + display: flex; + flex: 0 1 100%; + flex-direction: column; + overflow: hidden; +} + +.titleRow { + display: flex; +} + +.titleContainer { + display: flex; + align-items: flex-end; + flex: 0 1 auto; +} + +.title { + font-weight: 300; + font-size: 36px; +} + +.year { + margin-left: 10px; + color: var(--disabledColor); +} + +.icons { + display: flex; + align-items: center; + justify-content: space-between; + flex: 1 0 auto; + height: 55px; +} + +.originalLanguageName, +.network, +.genres { + margin-left: 8px; +} + +.genres { + pointer-events: all; +} + +.tvdbLink { + composes: link from '~Components/Link/Link.css'; + + margin-top: -4px; + margin-left: auto; + color: var(--textColor); +} + +.tvdbLinkIcon { + margin-left: 10px; +} + +.alreadyExistsIcon { + margin-left: 10px; + color: #37bc9b; + pointer-events: all; +} + +.overview { + margin-top: 20px; +} + +@media only screen and (max-width: $breakpointMedium) { + .titleRow { + justify-content: space-between; + overflow: hidden; + } + + .overview { + margin-bottom: 20px; + } +} diff --git a/frontend/src/AddSeries/AddNewSeries/AddNewSeriesSearchResult.css.d.ts b/frontend/src/AddSeries/AddNewSeries/AddNewSeriesSearchResult.css.d.ts new file mode 100644 index 000000000..b6fcfe361 --- /dev/null +++ b/frontend/src/AddSeries/AddNewSeries/AddNewSeriesSearchResult.css.d.ts @@ -0,0 +1,23 @@ +// This file is automatically generated. +// Please do not change this file! +interface CssExports { + 'alreadyExistsIcon': string; + 'content': string; + 'genres': string; + 'icons': string; + 'network': string; + 'originalLanguageName': string; + 'overlay': string; + 'overview': string; + 'poster': string; + 'searchResult': string; + 'title': string; + 'titleContainer': string; + 'titleRow': string; + 'tvdbLink': string; + 'tvdbLinkIcon': string; + 'underlay': string; + 'year': string; +} +export const cssExports: CssExports; +export default cssExports; diff --git a/frontend/src/AddSeries/AddNewSeries/AddNewSeriesSearchResult.js b/frontend/src/AddSeries/AddNewSeries/AddNewSeriesSearchResult.js new file mode 100644 index 000000000..8ce556456 --- /dev/null +++ b/frontend/src/AddSeries/AddNewSeries/AddNewSeriesSearchResult.js @@ -0,0 +1,276 @@ +import PropTypes from 'prop-types'; +import React, { Component } from 'react'; +import HeartRating from 'Components/HeartRating'; +import Icon from 'Components/Icon'; +import Label from 'Components/Label'; +import Link from 'Components/Link/Link'; +import MetadataAttribution from 'Components/MetadataAttribution'; +import { icons, kinds, sizes } from 'Helpers/Props'; +import SeriesGenres from 'Series/SeriesGenres'; +import SeriesPoster from 'Series/SeriesPoster'; +import translate from 'Utilities/String/translate'; +import AddNewSeriesModal from './AddNewSeriesModal'; +import styles from './AddNewSeriesSearchResult.css'; + +class AddNewSeriesSearchResult extends Component { + + // + // Lifecycle + + constructor(props, context) { + super(props, context); + + this.state = { + isNewAddSeriesModalOpen: false + }; + } + + componentDidUpdate(prevProps) { + if (!prevProps.isExistingSeries && this.props.isExistingSeries) { + this.onAddSeriesModalClose(); + } + } + + // + // Listeners + + onPress = () => { + this.setState({ isNewAddSeriesModalOpen: true }); + }; + + onAddSeriesModalClose = () => { + this.setState({ isNewAddSeriesModalOpen: false }); + }; + + onTVDBLinkPress = (event) => { + event.stopPropagation(); + }; + + // + // Render + + render() { + const { + tvdbId, + title, + titleSlug, + year, + network, + originalLanguage, + genres, + status, + overview, + statistics, + ratings, + folder, + seriesType, + images, + isExistingSeries, + isSmallScreen + } = this.props; + + const seasonCount = statistics.seasonCount; + + const { + isNewAddSeriesModalOpen + } = this.state; + + const linkProps = isExistingSeries ? { to: `/series/${titleSlug}` } : { onPress: this.onPress }; + let seasons = translate('OneSeason'); + + if (seasonCount > 1) { + seasons = translate('CountSeasons', { count: seasonCount }); + } + + return ( +
+ + +
+ { + isSmallScreen ? + null : + + } + +
+
+
+
+ {title} + + { + !title.contains(year) && year ? + + ({year}) + : + null + } +
+
+ +
+ { + isExistingSeries ? + : + null + } + + + + +
+
+ +
+ + + { + originalLanguage?.name ? + : + null + } + + { + network ? + : + null + } + + { + genres.length > 0 ? + : + null + } + + { + seasonCount ? + : + null + } + + { + status === 'ended' ? + : + null + } + + { + status === 'upcoming' ? + : + null + } +
+ +
+ {overview} +
+ + +
+
+ + +
+ ); + } +} + +AddNewSeriesSearchResult.propTypes = { + tvdbId: PropTypes.number.isRequired, + title: PropTypes.string.isRequired, + titleSlug: PropTypes.string.isRequired, + year: PropTypes.number.isRequired, + network: PropTypes.string, + originalLanguage: PropTypes.object, + genres: PropTypes.arrayOf(PropTypes.string), + status: PropTypes.string.isRequired, + overview: PropTypes.string, + statistics: PropTypes.object.isRequired, + ratings: PropTypes.object.isRequired, + folder: PropTypes.string.isRequired, + seriesType: PropTypes.string.isRequired, + images: PropTypes.arrayOf(PropTypes.object).isRequired, + isExistingSeries: PropTypes.bool.isRequired, + isSmallScreen: PropTypes.bool.isRequired +}; + +AddNewSeriesSearchResult.defaultProps = { + genres: [] +}; + +export default AddNewSeriesSearchResult; diff --git a/frontend/src/AddSeries/AddNewSeries/AddNewSeriesSearchResultConnector.js b/frontend/src/AddSeries/AddNewSeries/AddNewSeriesSearchResultConnector.js new file mode 100644 index 000000000..c1207c9ef --- /dev/null +++ b/frontend/src/AddSeries/AddNewSeries/AddNewSeriesSearchResultConnector.js @@ -0,0 +1,20 @@ +import { connect } from 'react-redux'; +import { createSelector } from 'reselect'; +import createDimensionsSelector from 'Store/Selectors/createDimensionsSelector'; +import createExistingSeriesSelector from 'Store/Selectors/createExistingSeriesSelector'; +import AddNewSeriesSearchResult from './AddNewSeriesSearchResult'; + +function createMapStateToProps() { + return createSelector( + createExistingSeriesSelector(), + createDimensionsSelector(), + (isExistingSeries, dimensions) => { + return { + isExistingSeries, + isSmallScreen: dimensions.isSmallScreen + }; + } + ); +} + +export default connect(createMapStateToProps)(AddNewSeriesSearchResult); diff --git a/frontend/src/AddSeries/ImportSeries/Import/ImportSeries.js b/frontend/src/AddSeries/ImportSeries/Import/ImportSeries.js new file mode 100644 index 000000000..eecdf8495 --- /dev/null +++ b/frontend/src/AddSeries/ImportSeries/Import/ImportSeries.js @@ -0,0 +1,179 @@ +import { reduce } from 'lodash'; +import PropTypes from 'prop-types'; +import React, { Component } from 'react'; +import Alert from 'Components/Alert'; +import LoadingIndicator from 'Components/Loading/LoadingIndicator'; +import PageContent from 'Components/Page/PageContent'; +import PageContentBody from 'Components/Page/PageContentBody'; +import { kinds } from 'Helpers/Props'; +import translate from 'Utilities/String/translate'; +import selectAll from 'Utilities/Table/selectAll'; +import toggleSelected from 'Utilities/Table/toggleSelected'; +import ImportSeriesFooterConnector from './ImportSeriesFooterConnector'; +import ImportSeriesTableConnector from './ImportSeriesTableConnector'; + +class ImportSeries extends Component { + + // + // Lifecycle + + constructor(props, context) { + super(props, context); + + this.scrollerRef = React.createRef(); + + this.state = { + allSelected: false, + allUnselected: false, + lastToggled: null, + selectedState: {} + }; + } + + // + // Listeners + + getSelectedIds = () => { + return reduce( + this.state.selectedState, + (result, value, id) => { + if (value) { + result.push(id); + } + + return result; + }, + [] + ); + }; + + onSelectAllChange = ({ value }) => { + // Only select non-dupes + this.setState(selectAll(this.state.selectedState, value)); + }; + + onSelectedChange = ({ id, value, shiftKey = false }) => { + this.setState((state) => { + return toggleSelected(state, this.props.items, id, value, shiftKey); + }); + }; + + onRemoveSelectedStateItem = (id) => { + this.setState((state) => { + const selectedState = Object.assign({}, state.selectedState); + delete selectedState[id]; + + return { + ...state, + selectedState + }; + }); + }; + + onInputChange = ({ name, value }) => { + this.props.onInputChange(this.getSelectedIds(), name, value); + }; + + onImportPress = () => { + this.props.onImportPress(this.getSelectedIds()); + }; + + // + // Render + + render() { + const { + rootFolderId, + path, + rootFoldersFetching, + rootFoldersPopulated, + rootFoldersError, + unmappedFolders + } = this.props; + + const { + allSelected, + allUnselected, + selectedState + } = this.state; + + return ( + + + { + rootFoldersFetching ? : null + } + + { + !rootFoldersFetching && !!rootFoldersError ? + + {translate('RootFoldersLoadError')} + : + null + } + + { + !rootFoldersError && + !rootFoldersFetching && + rootFoldersPopulated && + !unmappedFolders.length ? + + {translate('AllSeriesInRootFolderHaveBeenImported', { path })} + : + null + } + + { + !rootFoldersError && + !rootFoldersFetching && + rootFoldersPopulated && + !!unmappedFolders.length && + this.scrollerRef.current ? + : + null + } + + + { + !rootFoldersError && + !rootFoldersFetching && + !!unmappedFolders.length ? + : + null + } + + ); + } +} + +ImportSeries.propTypes = { + rootFolderId: PropTypes.number.isRequired, + path: PropTypes.string, + rootFoldersFetching: PropTypes.bool.isRequired, + rootFoldersPopulated: PropTypes.bool.isRequired, + rootFoldersError: PropTypes.object, + unmappedFolders: PropTypes.arrayOf(PropTypes.object), + items: PropTypes.arrayOf(PropTypes.object), + onInputChange: PropTypes.func.isRequired, + onImportPress: PropTypes.func.isRequired +}; + +ImportSeries.defaultProps = { + unmappedFolders: [] +}; + +export default ImportSeries; diff --git a/frontend/src/AddSeries/ImportSeries/Import/ImportSeriesConnector.js b/frontend/src/AddSeries/ImportSeries/Import/ImportSeriesConnector.js new file mode 100644 index 000000000..50436ba88 --- /dev/null +++ b/frontend/src/AddSeries/ImportSeries/Import/ImportSeriesConnector.js @@ -0,0 +1,153 @@ +import _ from 'lodash'; +import PropTypes from 'prop-types'; +import React, { Component } from 'react'; +import { connect } from 'react-redux'; +import { createSelector } from 'reselect'; +import createRouteMatchShape from 'Helpers/Props/Shapes/createRouteMatchShape'; +import { setAddSeriesDefault } from 'Store/Actions/addSeriesActions'; +import { clearImportSeries, importSeries, setImportSeriesValue } from 'Store/Actions/importSeriesActions'; +import { fetchRootFolders } from 'Store/Actions/rootFolderActions'; +import ImportSeries from './ImportSeries'; + +function createMapStateToProps() { + return createSelector( + (state, { match }) => match, + (state) => state.rootFolders, + (state) => state.addSeries, + (state) => state.importSeries, + (state) => state.settings.qualityProfiles, + ( + match, + rootFolders, + addSeries, + importSeriesState, + qualityProfiles + ) => { + const { + isFetching: rootFoldersFetching, + isPopulated: rootFoldersPopulated, + error: rootFoldersError, + items + } = rootFolders; + + const rootFolderId = parseInt(match.params.rootFolderId); + + const result = { + rootFolderId, + rootFoldersFetching, + rootFoldersPopulated, + rootFoldersError, + qualityProfiles: qualityProfiles.items, + defaultQualityProfileId: addSeries.defaults.qualityProfileId + }; + + if (items.length) { + const rootFolder = _.find(items, { id: rootFolderId }); + + return { + ...result, + ...rootFolder, + items: importSeriesState.items + }; + } + + return result; + } + ); +} + +const mapDispatchToProps = { + dispatchSetImportSeriesValue: setImportSeriesValue, + dispatchImportSeries: importSeries, + dispatchClearImportSeries: clearImportSeries, + dispatchFetchRootFolders: fetchRootFolders, + dispatchSetAddSeriesDefault: setAddSeriesDefault +}; + +class ImportSeriesConnector extends Component { + + // + // Lifecycle + + componentDidMount() { + const { + rootFolderId, + qualityProfiles, + defaultQualityProfileId, + dispatchFetchRootFolders, + dispatchSetAddSeriesDefault + } = this.props; + + dispatchFetchRootFolders({ id: rootFolderId, timeout: false }); + + let setDefaults = false; + const setDefaultPayload = {}; + + if ( + !defaultQualityProfileId || + !qualityProfiles.some((p) => p.id === defaultQualityProfileId) + ) { + setDefaults = true; + setDefaultPayload.qualityProfileId = qualityProfiles[0].id; + } + + if (setDefaults) { + dispatchSetAddSeriesDefault(setDefaultPayload); + } + } + + componentWillUnmount() { + this.props.dispatchClearImportSeries(); + } + + // + // Listeners + + onInputChange = (ids, name, value) => { + this.props.dispatchSetAddSeriesDefault({ [name]: value }); + + ids.forEach((id) => { + this.props.dispatchSetImportSeriesValue({ + id, + [name]: value + }); + }); + }; + + onImportPress = (ids) => { + this.props.dispatchImportSeries({ ids }); + }; + + // + // Render + + render() { + return ( + + ); + } +} + +const routeMatchShape = createRouteMatchShape({ + rootFolderId: PropTypes.string.isRequired +}); + +ImportSeriesConnector.propTypes = { + match: routeMatchShape.isRequired, + rootFolderId: PropTypes.number.isRequired, + rootFoldersFetching: PropTypes.bool.isRequired, + rootFoldersPopulated: PropTypes.bool.isRequired, + qualityProfiles: PropTypes.arrayOf(PropTypes.object).isRequired, + defaultQualityProfileId: PropTypes.number.isRequired, + dispatchSetImportSeriesValue: PropTypes.func.isRequired, + dispatchImportSeries: PropTypes.func.isRequired, + dispatchClearImportSeries: PropTypes.func.isRequired, + dispatchFetchRootFolders: PropTypes.func.isRequired, + dispatchSetAddSeriesDefault: PropTypes.func.isRequired +}; + +export default connect(createMapStateToProps, mapDispatchToProps)(ImportSeriesConnector); diff --git a/frontend/src/AddSeries/ImportSeries/Import/ImportSeriesFooter.css b/frontend/src/AddSeries/ImportSeries/Import/ImportSeriesFooter.css new file mode 100644 index 000000000..d0c6e98ae --- /dev/null +++ b/frontend/src/AddSeries/ImportSeries/Import/ImportSeriesFooter.css @@ -0,0 +1,51 @@ +.inputContainer { + margin-right: 20px; + min-width: 150px; +} + +.label { + margin-bottom: 10px; + font-weight: bold; +} + +.importButtonContainer { + display: flex; + align-items: center; +} + +.importButton { + composes: button from '~Components/Link/SpinnerButton.css'; + + height: 35px; +} + +.loadingButton { + composes: importButton; + + margin-left: 10px; +} + +.loading { + composes: loading from '~Components/Loading/LoadingIndicator.css'; + + margin: 0 10px 0 12px; + text-align: left; +} + +.importError { + margin-left: 10px; +} + +@media only screen and (max-width: $breakpointSmall) { + .inputContainer { + margin-top: 10px; + + &:first-child { + margin-top: 0; + } + } + + .importButtonContainer { + margin-top: 10px; + } +} diff --git a/frontend/src/AddSeries/ImportSeries/Import/ImportSeriesFooter.css.d.ts b/frontend/src/AddSeries/ImportSeries/Import/ImportSeriesFooter.css.d.ts new file mode 100644 index 000000000..d107ffc8d --- /dev/null +++ b/frontend/src/AddSeries/ImportSeries/Import/ImportSeriesFooter.css.d.ts @@ -0,0 +1,13 @@ +// This file is automatically generated. +// Please do not change this file! +interface CssExports { + 'importButton': string; + 'importButtonContainer': string; + 'importError': string; + 'inputContainer': string; + 'label': string; + 'loading': string; + 'loadingButton': string; +} +export const cssExports: CssExports; +export default cssExports; diff --git a/frontend/src/AddSeries/ImportSeries/Import/ImportSeriesFooter.js b/frontend/src/AddSeries/ImportSeries/Import/ImportSeriesFooter.js new file mode 100644 index 000000000..a2e4cffff --- /dev/null +++ b/frontend/src/AddSeries/ImportSeries/Import/ImportSeriesFooter.js @@ -0,0 +1,300 @@ +import _ from 'lodash'; +import PropTypes from 'prop-types'; +import React, { Component } from 'react'; +import CheckInput from 'Components/Form/CheckInput'; +import FormInputGroup from 'Components/Form/FormInputGroup'; +import Icon from 'Components/Icon'; +import Button from 'Components/Link/Button'; +import SpinnerButton from 'Components/Link/SpinnerButton'; +import LoadingIndicator from 'Components/Loading/LoadingIndicator'; +import PageContentFooter from 'Components/Page/PageContentFooter'; +import Popover from 'Components/Tooltip/Popover'; +import { icons, inputTypes, kinds, tooltipPositions } from 'Helpers/Props'; +import translate from 'Utilities/String/translate'; +import styles from './ImportSeriesFooter.css'; + +const MIXED = 'mixed'; + +class ImportSeriesFooter extends Component { + + // + // Lifecycle + + constructor(props, context) { + super(props, context); + + const { + defaultMonitor, + defaultQualityProfileId, + defaultSeasonFolder, + defaultSeriesType + } = props; + + this.state = { + monitor: defaultMonitor, + qualityProfileId: defaultQualityProfileId, + seriesType: defaultSeriesType, + seasonFolder: defaultSeasonFolder + }; + } + + componentDidUpdate(prevProps, prevState) { + const { + defaultMonitor, + defaultQualityProfileId, + defaultSeriesType, + defaultSeasonFolder, + isMonitorMixed, + isQualityProfileIdMixed, + isSeriesTypeMixed, + isSeasonFolderMixed + } = this.props; + + const { + monitor, + qualityProfileId, + seriesType, + seasonFolder + } = this.state; + + const newState = {}; + + if (isMonitorMixed && monitor !== MIXED) { + newState.monitor = MIXED; + } else if (!isMonitorMixed && monitor !== defaultMonitor) { + newState.monitor = defaultMonitor; + } + + if (isQualityProfileIdMixed && qualityProfileId !== MIXED) { + newState.qualityProfileId = MIXED; + } else if (!isQualityProfileIdMixed && qualityProfileId !== defaultQualityProfileId) { + newState.qualityProfileId = defaultQualityProfileId; + } + + if (isSeriesTypeMixed && seriesType !== MIXED) { + newState.seriesType = MIXED; + } else if (!isSeriesTypeMixed && seriesType !== defaultSeriesType) { + newState.seriesType = defaultSeriesType; + } + + if (isSeasonFolderMixed && seasonFolder != null) { + newState.seasonFolder = null; + } else if (!isSeasonFolderMixed && seasonFolder !== defaultSeasonFolder) { + newState.seasonFolder = defaultSeasonFolder; + } + + if (!_.isEmpty(newState)) { + this.setState(newState); + } + } + + // + // Listeners + + onInputChange = ({ name, value }) => { + this.setState({ [name]: value }); + this.props.onInputChange({ name, value }); + }; + + // + // Render + + render() { + const { + selectedCount, + isImporting, + isLookingUpSeries, + isMonitorMixed, + isQualityProfileIdMixed, + isSeriesTypeMixed, + hasUnsearchedItems, + importError, + onImportPress, + onLookupPress, + onCancelLookupPress + } = this.props; + + const { + monitor, + qualityProfileId, + seriesType, + seasonFolder + } = this.state; + + return ( + +
+
+ {translate('Monitor')} +
+ + +
+ +
+
+ {translate('QualityProfile')} +
+ + +
+ +
+
+ {translate('SeriesType')} +
+ + +
+ +
+
+ {translate('SeasonFolder')} +
+ + +
+ +
+
+   +
+ +
+ + {translate('ImportCountSeries', { selectedCount })} + + + { + isLookingUpSeries ? + : + null + } + + { + hasUnsearchedItems ? + : + null + } + + { + isLookingUpSeries ? + : + null + } + + { + isLookingUpSeries ? + translate('ProcessingFolders') : + null + } + + { + importError ? + + } + title={translate('ImportErrors')} + body={ +
    + { + Array.isArray(importError.responseJSON) ? + importError.responseJSON.map((error, index) => { + return ( +
  • + {error.errorMessage} +
  • + ); + }) : +
  • + { + JSON.stringify(importError.responseJSON) + } +
  • + } +
+ } + position={tooltipPositions.RIGHT} + /> : + null + } +
+
+
+ ); + } +} + +ImportSeriesFooter.propTypes = { + selectedCount: PropTypes.number.isRequired, + isImporting: PropTypes.bool.isRequired, + isLookingUpSeries: PropTypes.bool.isRequired, + defaultMonitor: PropTypes.string.isRequired, + defaultQualityProfileId: PropTypes.number, + defaultSeriesType: PropTypes.string.isRequired, + defaultSeasonFolder: PropTypes.bool.isRequired, + isMonitorMixed: PropTypes.bool.isRequired, + isQualityProfileIdMixed: PropTypes.bool.isRequired, + isSeriesTypeMixed: PropTypes.bool.isRequired, + isSeasonFolderMixed: PropTypes.bool.isRequired, + hasUnsearchedItems: PropTypes.bool.isRequired, + importError: PropTypes.object, + onInputChange: PropTypes.func.isRequired, + onImportPress: PropTypes.func.isRequired, + onLookupPress: PropTypes.func.isRequired, + onCancelLookupPress: PropTypes.func.isRequired +}; + +export default ImportSeriesFooter; diff --git a/frontend/src/AddSeries/ImportSeries/Import/ImportSeriesFooterConnector.js b/frontend/src/AddSeries/ImportSeries/Import/ImportSeriesFooterConnector.js new file mode 100644 index 000000000..12a90aae7 --- /dev/null +++ b/frontend/src/AddSeries/ImportSeries/Import/ImportSeriesFooterConnector.js @@ -0,0 +1,63 @@ +import _ from 'lodash'; +import { connect } from 'react-redux'; +import { createSelector } from 'reselect'; +import { cancelLookupSeries, lookupUnsearchedSeries } from 'Store/Actions/importSeriesActions'; +import ImportSeriesFooter from './ImportSeriesFooter'; + +function isMixed(items, selectedIds, defaultValue, key) { + return _.some(items, (series) => { + return selectedIds.indexOf(series.id) > -1 && series[key] !== defaultValue; + }); +} + +function createMapStateToProps() { + return createSelector( + (state) => state.addSeries, + (state) => state.importSeries, + (state, { selectedIds }) => selectedIds, + (addSeries, importSeries, selectedIds) => { + const { + monitor: defaultMonitor, + qualityProfileId: defaultQualityProfileId, + seriesType: defaultSeriesType, + seasonFolder: defaultSeasonFolder + } = addSeries.defaults; + + const { + isLookingUpSeries, + isImporting, + items, + importError + } = importSeries; + + const isMonitorMixed = isMixed(items, selectedIds, defaultMonitor, 'monitor'); + const isQualityProfileIdMixed = isMixed(items, selectedIds, defaultQualityProfileId, 'qualityProfileId'); + const isSeriesTypeMixed = isMixed(items, selectedIds, defaultSeriesType, 'seriesType'); + const isSeasonFolderMixed = isMixed(items, selectedIds, defaultSeasonFolder, 'seasonFolder'); + const hasUnsearchedItems = !isLookingUpSeries && items.some((item) => !item.isPopulated); + + return { + selectedCount: selectedIds.length, + isLookingUpSeries, + isImporting, + defaultMonitor, + defaultQualityProfileId, + defaultSeriesType, + defaultSeasonFolder, + isMonitorMixed, + isQualityProfileIdMixed, + isSeriesTypeMixed, + isSeasonFolderMixed, + importError, + hasUnsearchedItems + }; + } + ); +} + +const mapDispatchToProps = { + onLookupPress: lookupUnsearchedSeries, + onCancelLookupPress: cancelLookupSeries +}; + +export default connect(createMapStateToProps, mapDispatchToProps)(ImportSeriesFooter); diff --git a/frontend/src/AddSeries/ImportSeries/Import/ImportSeriesHeader.css b/frontend/src/AddSeries/ImportSeries/Import/ImportSeriesHeader.css new file mode 100644 index 000000000..df5214bdd --- /dev/null +++ b/frontend/src/AddSeries/ImportSeries/Import/ImportSeriesHeader.css @@ -0,0 +1,44 @@ +.folder { + composes: headerCell from '~Components/Table/VirtualTableHeaderCell.css'; + + flex: 1 0 200px; +} + +.monitor { + composes: headerCell from '~Components/Table/VirtualTableHeaderCell.css'; + + flex: 0 1 200px; + min-width: 185px; +} + +.qualityProfile { + composes: headerCell from '~Components/Table/VirtualTableHeaderCell.css'; + + flex: 0 1 250px; + min-width: 170px; +} + +.seriesType { + composes: headerCell from '~Components/Table/VirtualTableHeaderCell.css'; + + flex: 0 1 200px; + min-width: 120px; +} + +.seasonFolder { + composes: headerCell from '~Components/Table/VirtualTableHeaderCell.css'; + + flex: 0 1 150px; + min-width: 120px; +} + +.series { + composes: headerCell from '~Components/Table/VirtualTableHeaderCell.css'; + + flex: 0 1 400px; + min-width: 300px; +} + +.detailsIcon { + margin-left: 8px; +} diff --git a/frontend/src/AddSeries/ImportSeries/Import/ImportSeriesHeader.css.d.ts b/frontend/src/AddSeries/ImportSeries/Import/ImportSeriesHeader.css.d.ts new file mode 100644 index 000000000..ecf1347f5 --- /dev/null +++ b/frontend/src/AddSeries/ImportSeries/Import/ImportSeriesHeader.css.d.ts @@ -0,0 +1,13 @@ +// This file is automatically generated. +// Please do not change this file! +interface CssExports { + 'detailsIcon': string; + 'folder': string; + 'monitor': string; + 'qualityProfile': string; + 'seasonFolder': string; + 'series': string; + 'seriesType': string; +} +export const cssExports: CssExports; +export default cssExports; diff --git a/frontend/src/AddSeries/ImportSeries/Import/ImportSeriesHeader.js b/frontend/src/AddSeries/ImportSeries/Import/ImportSeriesHeader.js new file mode 100644 index 000000000..6f44b9754 --- /dev/null +++ b/frontend/src/AddSeries/ImportSeries/Import/ImportSeriesHeader.js @@ -0,0 +1,104 @@ +import PropTypes from 'prop-types'; +import React from 'react'; +import SeriesMonitoringOptionsPopoverContent from 'AddSeries/SeriesMonitoringOptionsPopoverContent'; +import SeriesTypePopoverContent from 'AddSeries/SeriesTypePopoverContent'; +import Icon from 'Components/Icon'; +import VirtualTableHeader from 'Components/Table/VirtualTableHeader'; +import VirtualTableHeaderCell from 'Components/Table/VirtualTableHeaderCell'; +import VirtualTableSelectAllHeaderCell from 'Components/Table/VirtualTableSelectAllHeaderCell'; +import Popover from 'Components/Tooltip/Popover'; +import { icons, tooltipPositions } from 'Helpers/Props'; +import translate from 'Utilities/String/translate'; +import styles from './ImportSeriesHeader.css'; + +function ImportSeriesHeader(props) { + const { + allSelected, + allUnselected, + onSelectAllChange + } = props; + + return ( + + + + + {translate('Folder')} + + + + {translate('Monitor')} + + + } + title={translate('MonitoringOptions')} + body={} + position={tooltipPositions.RIGHT} + /> + + + + {translate('QualityProfile')} + + + + {translate('SeriesType')} + + + } + title={translate('SeriesType')} + body={} + position={tooltipPositions.RIGHT} + /> + + + + {translate('SeasonFolder')} + + + + {translate('Series')} + + + ); +} + +ImportSeriesHeader.propTypes = { + allSelected: PropTypes.bool.isRequired, + allUnselected: PropTypes.bool.isRequired, + onSelectAllChange: PropTypes.func.isRequired +}; + +export default ImportSeriesHeader; diff --git a/frontend/src/AddSeries/ImportSeries/Import/ImportSeriesRow.css b/frontend/src/AddSeries/ImportSeries/Import/ImportSeriesRow.css new file mode 100644 index 000000000..c75b47dba --- /dev/null +++ b/frontend/src/AddSeries/ImportSeries/Import/ImportSeriesRow.css @@ -0,0 +1,45 @@ +.selectInput { + composes: input from '~Components/Form/CheckInput.css'; +} + +.folder { + composes: cell from '~Components/Table/Cells/VirtualTableRowCell.css'; + + flex: 1 0 200px; + line-height: 36px; +} + +.monitor { + composes: cell from '~Components/Table/Cells/VirtualTableRowCell.css'; + + flex: 0 1 200px; + min-width: 185px; +} + +.qualityProfile { + composes: cell from '~Components/Table/Cells/VirtualTableRowCell.css'; + + flex: 0 1 250px; + min-width: 170px; +} + +.seriesType { + composes: cell from '~Components/Table/Cells/VirtualTableRowCell.css'; + + flex: 0 1 200px; + min-width: 120px; +} + +.seasonFolder { + composes: cell from '~Components/Table/Cells/VirtualTableRowCell.css'; + + flex: 0 1 150px; + min-width: 120px; +} + +.series { + composes: cell from '~Components/Table/Cells/VirtualTableRowCell.css'; + + flex: 0 1 400px; + min-width: 300px; +} diff --git a/frontend/src/AddSeries/ImportSeries/Import/ImportSeriesRow.css.d.ts b/frontend/src/AddSeries/ImportSeries/Import/ImportSeriesRow.css.d.ts new file mode 100644 index 000000000..4339b9d05 --- /dev/null +++ b/frontend/src/AddSeries/ImportSeries/Import/ImportSeriesRow.css.d.ts @@ -0,0 +1,13 @@ +// This file is automatically generated. +// Please do not change this file! +interface CssExports { + 'folder': string; + 'monitor': string; + 'qualityProfile': string; + 'seasonFolder': string; + 'selectInput': string; + 'series': string; + 'seriesType': string; +} +export const cssExports: CssExports; +export default cssExports; diff --git a/frontend/src/AddSeries/ImportSeries/Import/ImportSeriesRow.js b/frontend/src/AddSeries/ImportSeries/Import/ImportSeriesRow.js new file mode 100644 index 000000000..7777c768f --- /dev/null +++ b/frontend/src/AddSeries/ImportSeries/Import/ImportSeriesRow.js @@ -0,0 +1,105 @@ +import PropTypes from 'prop-types'; +import React from 'react'; +import FormInputGroup from 'Components/Form/FormInputGroup'; +import VirtualTableRowCell from 'Components/Table/Cells/VirtualTableRowCell'; +import VirtualTableSelectCell from 'Components/Table/Cells/VirtualTableSelectCell'; +import { inputTypes } from 'Helpers/Props'; +import ImportSeriesSelectSeriesConnector from './SelectSeries/ImportSeriesSelectSeriesConnector'; +import styles from './ImportSeriesRow.css'; + +function ImportSeriesRow(props) { + const { + id, + relativePath, + monitor, + qualityProfileId, + seasonFolder, + seriesType, + selectedSeries, + isExistingSeries, + isSelected, + onSelectedChange, + onInputChange + } = props; + + return ( + <> + + + + {relativePath} + + + + + + + + + + + + + + + + + + + + + + + ); +} + +ImportSeriesRow.propTypes = { + id: PropTypes.string.isRequired, + relativePath: PropTypes.string.isRequired, + monitor: PropTypes.string.isRequired, + qualityProfileId: PropTypes.number.isRequired, + seriesType: PropTypes.string.isRequired, + seasonFolder: PropTypes.bool.isRequired, + selectedSeries: PropTypes.object, + isExistingSeries: PropTypes.bool.isRequired, + items: PropTypes.arrayOf(PropTypes.object).isRequired, + isSelected: PropTypes.bool, + onSelectedChange: PropTypes.func.isRequired, + onInputChange: PropTypes.func.isRequired +}; + +ImportSeriesRow.defaultsProps = { + items: [] +}; + +export default ImportSeriesRow; diff --git a/frontend/src/AddSeries/ImportSeries/Import/ImportSeriesRowConnector.js b/frontend/src/AddSeries/ImportSeries/Import/ImportSeriesRowConnector.js new file mode 100644 index 000000000..3149f9719 --- /dev/null +++ b/frontend/src/AddSeries/ImportSeries/Import/ImportSeriesRowConnector.js @@ -0,0 +1,89 @@ +import _ from 'lodash'; +import PropTypes from 'prop-types'; +import React, { Component } from 'react'; +import { connect } from 'react-redux'; +import { createSelector } from 'reselect'; +import { setImportSeriesValue } from 'Store/Actions/importSeriesActions'; +import createAllSeriesSelector from 'Store/Selectors/createAllSeriesSelector'; +import ImportSeriesRow from './ImportSeriesRow'; + +function createImportSeriesItemSelector() { + return createSelector( + (state, { id }) => id, + (state) => state.importSeries.items, + (id, items) => { + return _.find(items, { id }) || {}; + } + ); +} + +function createMapStateToProps() { + return createSelector( + createImportSeriesItemSelector(), + createAllSeriesSelector(), + (item, series) => { + const selectedSeries = item && item.selectedSeries; + const isExistingSeries = !!selectedSeries && _.some(series, { tvdbId: selectedSeries.tvdbId }); + + return { + ...item, + isExistingSeries + }; + } + ); +} + +const mapDispatchToProps = { + setImportSeriesValue +}; + +class ImportSeriesRowConnector extends Component { + + // + // Listeners + + onInputChange = ({ name, value }) => { + this.props.setImportSeriesValue({ + id: this.props.id, + [name]: value + }); + }; + + // + // Render + + render() { + // Don't show the row until we have the information we require for it. + + const { + items, + monitor, + seriesType, + seasonFolder + } = this.props; + + if (!items || !monitor || !seriesType || !seasonFolder == null) { + return null; + } + + return ( + + ); + } +} + +ImportSeriesRowConnector.propTypes = { + rootFolderId: PropTypes.number.isRequired, + id: PropTypes.string.isRequired, + monitor: PropTypes.string, + seriesType: PropTypes.string, + seasonFolder: PropTypes.bool, + items: PropTypes.arrayOf(PropTypes.object), + setImportSeriesValue: PropTypes.func.isRequired +}; + +export default connect(createMapStateToProps, mapDispatchToProps)(ImportSeriesRowConnector); diff --git a/frontend/src/AddSeries/ImportSeries/Import/ImportSeriesSelected.css b/frontend/src/AddSeries/ImportSeries/Import/ImportSeriesSelected.css new file mode 100644 index 000000000..51fe4ce39 --- /dev/null +++ b/frontend/src/AddSeries/ImportSeries/Import/ImportSeriesSelected.css @@ -0,0 +1,3 @@ +.input { + composes: input from '~Components/Form/CheckInput.css'; +} diff --git a/frontend/src/AddSeries/ImportSeries/Import/ImportSeriesTable.js b/frontend/src/AddSeries/ImportSeries/Import/ImportSeriesTable.js new file mode 100644 index 000000000..aa78925f2 --- /dev/null +++ b/frontend/src/AddSeries/ImportSeries/Import/ImportSeriesTable.js @@ -0,0 +1,188 @@ +import _ from 'lodash'; +import PropTypes from 'prop-types'; +import React, { Component } from 'react'; +import VirtualTable from 'Components/Table/VirtualTable'; +import VirtualTableRow from 'Components/Table/VirtualTableRow'; +import ImportSeriesHeader from './ImportSeriesHeader'; +import ImportSeriesRowConnector from './ImportSeriesRowConnector'; + +class ImportSeriesTable extends Component { + + // + // Lifecycle + + componentDidMount() { + const { + unmappedFolders, + defaultMonitor, + defaultQualityProfileId, + defaultSeriesType, + defaultSeasonFolder, + onSeriesLookup, + onSetImportSeriesValue + } = this.props; + + const values = { + monitor: defaultMonitor, + qualityProfileId: defaultQualityProfileId, + seriesType: defaultSeriesType, + seasonFolder: defaultSeasonFolder + }; + + unmappedFolders.forEach((unmappedFolder) => { + const id = unmappedFolder.name; + + onSeriesLookup(id, unmappedFolder.path, unmappedFolder.relativePath); + + onSetImportSeriesValue({ + id, + ...values + }); + }); + } + + // This isn't great, but it's the most reliable way to ensure the items + // are checked off even if they aren't actually visible since the cells + // are virtualized. + + componentDidUpdate(prevProps) { + const { + items, + selectedState, + onSelectedChange, + onRemoveSelectedStateItem + } = this.props; + + prevProps.items.forEach((prevItem) => { + const { + id + } = prevItem; + + const item = _.find(items, { id }); + + if (!item) { + onRemoveSelectedStateItem(id); + return; + } + + const selectedSeries = item.selectedSeries; + const isSelected = selectedState[id]; + + const isExistingSeries = !!selectedSeries && + _.some(prevProps.allSeries, { tvdbId: selectedSeries.tvdbId }); + + // Props doesn't have a selected series or + // the selected series is an existing series. + if ((!selectedSeries && prevItem.selectedSeries) || (isExistingSeries && !prevItem.selectedSeries)) { + onSelectedChange({ id, value: false }); + + return; + } + + // State is selected, but a series isn't selected or + // the selected series is an existing series. + if (isSelected && (!selectedSeries || isExistingSeries)) { + onSelectedChange({ id, value: false }); + + return; + } + + // A series is being selected that wasn't previously selected. + if (selectedSeries && selectedSeries !== prevItem.selectedSeries) { + onSelectedChange({ id, value: true }); + + return; + } + }); + } + + // + // Control + + rowRenderer = ({ key, rowIndex, style }) => { + const { + rootFolderId, + items, + selectedState, + onSelectedChange + } = this.props; + + const item = items[rowIndex]; + + return ( + + + + ); + }; + + // + // Render + + render() { + const { + items, + allSelected, + allUnselected, + isSmallScreen, + scroller, + selectedState, + onSelectAllChange + } = this.props; + + if (!items.length) { + return null; + } + + return ( + + } + selectedState={selectedState} + /> + ); + } +} + +ImportSeriesTable.propTypes = { + rootFolderId: PropTypes.number.isRequired, + items: PropTypes.arrayOf(PropTypes.object), + unmappedFolders: PropTypes.arrayOf(PropTypes.object), + defaultMonitor: PropTypes.string.isRequired, + defaultQualityProfileId: PropTypes.number, + defaultSeriesType: PropTypes.string.isRequired, + defaultSeasonFolder: PropTypes.bool.isRequired, + allSelected: PropTypes.bool.isRequired, + allUnselected: PropTypes.bool.isRequired, + selectedState: PropTypes.object.isRequired, + isSmallScreen: PropTypes.bool.isRequired, + allSeries: PropTypes.arrayOf(PropTypes.object), + scroller: PropTypes.instanceOf(Element).isRequired, + onSelectAllChange: PropTypes.func.isRequired, + onSelectedChange: PropTypes.func.isRequired, + onRemoveSelectedStateItem: PropTypes.func.isRequired, + onSeriesLookup: PropTypes.func.isRequired, + onSetImportSeriesValue: PropTypes.func.isRequired +}; + +export default ImportSeriesTable; diff --git a/frontend/src/AddSeries/ImportSeries/Import/ImportSeriesTableConnector.js b/frontend/src/AddSeries/ImportSeries/Import/ImportSeriesTableConnector.js new file mode 100644 index 000000000..8a26fbe79 --- /dev/null +++ b/frontend/src/AddSeries/ImportSeries/Import/ImportSeriesTableConnector.js @@ -0,0 +1,44 @@ +import { connect } from 'react-redux'; +import { createSelector } from 'reselect'; +import { queueLookupSeries, setImportSeriesValue } from 'Store/Actions/importSeriesActions'; +import createAllSeriesSelector from 'Store/Selectors/createAllSeriesSelector'; +import ImportSeriesTable from './ImportSeriesTable'; + +function createMapStateToProps() { + return createSelector( + (state) => state.addSeries, + (state) => state.importSeries, + (state) => state.app.dimensions, + createAllSeriesSelector(), + (addSeries, importSeries, dimensions, allSeries) => { + return { + defaultMonitor: addSeries.defaults.monitor, + defaultQualityProfileId: addSeries.defaults.qualityProfileId, + defaultSeriesType: addSeries.defaults.seriesType, + defaultSeasonFolder: addSeries.defaults.seasonFolder, + items: importSeries.items, + isSmallScreen: dimensions.isSmallScreen, + allSeries + }; + } + ); +} + +function createMapDispatchToProps(dispatch, props) { + return { + onSeriesLookup(name, path, relativePath) { + dispatch(queueLookupSeries({ + name, + path, + relativePath, + term: name + })); + }, + + onSetImportSeriesValue(values) { + dispatch(setImportSeriesValue(values)); + } + }; +} + +export default connect(createMapStateToProps, createMapDispatchToProps)(ImportSeriesTable); diff --git a/frontend/src/AddSeries/ImportSeries/Import/SelectSeries/ImportSeriesSearchResult.css b/frontend/src/AddSeries/ImportSeries/Import/SelectSeries/ImportSeriesSearchResult.css new file mode 100644 index 000000000..70a646cab --- /dev/null +++ b/frontend/src/AddSeries/ImportSeries/Import/SelectSeries/ImportSeriesSearchResult.css @@ -0,0 +1,25 @@ +.container { + display: flex; + padding: 10px 20px; + width: 100%; + + &:hover { + background-color: var(--menuItemHoverBackgroundColor); + } +} + +.series { + flex: 1 0 0; + overflow: hidden; +} + +.tvdbLink { + composes: link from '~Components/Link/Link.css'; + + margin-left: auto; + color: var(--textColor); +} + +.tvdbLinkIcon { + margin-left: 10px; +} diff --git a/frontend/src/AddSeries/ImportSeries/Import/SelectSeries/ImportSeriesSearchResult.css.d.ts b/frontend/src/AddSeries/ImportSeries/Import/SelectSeries/ImportSeriesSearchResult.css.d.ts new file mode 100644 index 000000000..ff161359d --- /dev/null +++ b/frontend/src/AddSeries/ImportSeries/Import/SelectSeries/ImportSeriesSearchResult.css.d.ts @@ -0,0 +1,10 @@ +// This file is automatically generated. +// Please do not change this file! +interface CssExports { + 'container': string; + 'series': string; + 'tvdbLink': string; + 'tvdbLinkIcon': string; +} +export const cssExports: CssExports; +export default cssExports; diff --git a/frontend/src/AddSeries/ImportSeries/Import/SelectSeries/ImportSeriesSearchResult.js b/frontend/src/AddSeries/ImportSeries/Import/SelectSeries/ImportSeriesSearchResult.js new file mode 100644 index 000000000..60848ce85 --- /dev/null +++ b/frontend/src/AddSeries/ImportSeries/Import/SelectSeries/ImportSeriesSearchResult.js @@ -0,0 +1,58 @@ +import PropTypes from 'prop-types'; +import React, { useCallback } from 'react'; +import Icon from 'Components/Icon'; +import Link from 'Components/Link/Link'; +import { icons } from 'Helpers/Props'; +import ImportSeriesTitle from './ImportSeriesTitle'; +import styles from './ImportSeriesSearchResult.css'; + +function ImportSeriesSearchResult(props) { + const { + tvdbId, + title, + year, + network, + isExistingSeries, + onPress + } = props; + + const onPressCallback = useCallback(() => onPress(tvdbId), [tvdbId, onPress]); + + return ( +
+ + + + + + + +
+ ); +} + +ImportSeriesSearchResult.propTypes = { + tvdbId: PropTypes.number.isRequired, + title: PropTypes.string.isRequired, + year: PropTypes.number.isRequired, + network: PropTypes.string, + isExistingSeries: PropTypes.bool.isRequired, + onPress: PropTypes.func.isRequired +}; + +export default ImportSeriesSearchResult; diff --git a/frontend/src/AddSeries/ImportSeries/Import/SelectSeries/ImportSeriesSearchResultConnector.js b/frontend/src/AddSeries/ImportSeries/Import/SelectSeries/ImportSeriesSearchResultConnector.js new file mode 100644 index 000000000..81bb3059b --- /dev/null +++ b/frontend/src/AddSeries/ImportSeries/Import/SelectSeries/ImportSeriesSearchResultConnector.js @@ -0,0 +1,17 @@ +import { connect } from 'react-redux'; +import { createSelector } from 'reselect'; +import createExistingSeriesSelector from 'Store/Selectors/createExistingSeriesSelector'; +import ImportSeriesSearchResult from './ImportSeriesSearchResult'; + +function createMapStateToProps() { + return createSelector( + createExistingSeriesSelector(), + (isExistingSeries) => { + return { + isExistingSeries + }; + } + ); +} + +export default connect(createMapStateToProps)(ImportSeriesSearchResult); diff --git a/frontend/src/AddSeries/ImportSeries/Import/SelectSeries/ImportSeriesSelectSeries.css b/frontend/src/AddSeries/ImportSeries/Import/SelectSeries/ImportSeriesSelectSeries.css new file mode 100644 index 000000000..89b03301b --- /dev/null +++ b/frontend/src/AddSeries/ImportSeries/Import/SelectSeries/ImportSeriesSelectSeries.css @@ -0,0 +1,77 @@ +.button { + composes: link from '~Components/Link/Link.css'; + + display: flex; + align-items: center; + padding: 6px 16px; + width: 100%; + height: 35px; + border: 1px solid var(--inputBorderColor); + border-radius: 4px; + background-color: var(--inputBackgroundColor); + box-shadow: inset 0 1px 1px var(--inputBoxShadowColor); +} + +.loading { + display: inline-block; +} + +.warningIcon { + margin-right: 8px; +} + +.existing { + margin-left: 5px; +} + +.dropdownArrowContainer { + flex: 1 0 auto; + margin-left: 5px; + text-align: right; +} + +.contentContainer { + z-index: $popperZIndex; + margin-top: 4px; + /* 400px container width with 8px padding on each side */ + width: 384px; +} + +.content { + padding: 4px; + border: 1px solid var(--inputBorderColor); + border-radius: 4px; + background-color: var(--inputBackgroundColor); +} + +.searchContainer { + display: flex; +} + +.searchIconContainer { + width: 58px; + border: 1px solid var(--inputBorderColor); + border-right: none; + border-radius: 4px; + border-top-right-radius: 0; + border-bottom-right-radius: 0; + background-color: var(--searchIconContainerBackgroundColor); + text-align: center; + line-height: 33px; +} + +.searchInput { + composes: input from '~Components/Form/TextInput.css'; + + border-radius: 0; +} + +.results { + @add-mixin scrollbar; + @add-mixin scrollbarTrack; + @add-mixin scrollbarThumb; + + overflow-x: hidden; + overflow-y: scroll; + max-height: 165px; +} diff --git a/frontend/src/AddSeries/ImportSeries/Import/SelectSeries/ImportSeriesSelectSeries.css.d.ts b/frontend/src/AddSeries/ImportSeries/Import/SelectSeries/ImportSeriesSelectSeries.css.d.ts new file mode 100644 index 000000000..d5aa6bc94 --- /dev/null +++ b/frontend/src/AddSeries/ImportSeries/Import/SelectSeries/ImportSeriesSelectSeries.css.d.ts @@ -0,0 +1,17 @@ +// This file is automatically generated. +// Please do not change this file! +interface CssExports { + 'button': string; + 'content': string; + 'contentContainer': string; + 'dropdownArrowContainer': string; + 'existing': string; + 'loading': string; + 'results': string; + 'searchContainer': string; + 'searchIconContainer': string; + 'searchInput': string; + 'warningIcon': string; +} +export const cssExports: CssExports; +export default cssExports; diff --git a/frontend/src/AddSeries/ImportSeries/Import/SelectSeries/ImportSeriesSelectSeries.js b/frontend/src/AddSeries/ImportSeries/Import/SelectSeries/ImportSeriesSelectSeries.js new file mode 100644 index 000000000..1257be9b1 --- /dev/null +++ b/frontend/src/AddSeries/ImportSeries/Import/SelectSeries/ImportSeriesSelectSeries.js @@ -0,0 +1,303 @@ +import PropTypes from 'prop-types'; +import React, { Component } from 'react'; +import { Manager, Popper, Reference } from 'react-popper'; +import FormInputButton from 'Components/Form/FormInputButton'; +import TextInput from 'Components/Form/TextInput'; +import Icon from 'Components/Icon'; +import Link from 'Components/Link/Link'; +import LoadingIndicator from 'Components/Loading/LoadingIndicator'; +import Portal from 'Components/Portal'; +import { icons, kinds } from 'Helpers/Props'; +import getUniqueElementId from 'Utilities/getUniqueElementId'; +import translate from 'Utilities/String/translate'; +import ImportSeriesSearchResultConnector from './ImportSeriesSearchResultConnector'; +import ImportSeriesTitle from './ImportSeriesTitle'; +import styles from './ImportSeriesSelectSeries.css'; + +class ImportSeriesSelectSeries extends Component { + + // + // Lifecycle + + constructor(props, context) { + super(props, context); + + this._seriesLookupTimeout = null; + this._scheduleUpdate = null; + this._buttonId = getUniqueElementId(); + this._contentId = getUniqueElementId(); + + this.state = { + term: props.id, + isOpen: false + }; + } + + componentDidUpdate() { + if (this._scheduleUpdate) { + this._scheduleUpdate(); + } + } + + // + // Control + + _addListener() { + window.addEventListener('click', this.onWindowClick); + } + + _removeListener() { + window.removeEventListener('click', this.onWindowClick); + } + + // + // Listeners + + onWindowClick = (event) => { + const button = document.getElementById(this._buttonId); + const content = document.getElementById(this._contentId); + + if (!button || !content) { + return; + } + + if ( + !button.contains(event.target) && + !content.contains(event.target) && + this.state.isOpen + ) { + this.setState({ isOpen: false }); + this._removeListener(); + } + }; + + onPress = () => { + if (this.state.isOpen) { + this._removeListener(); + } else { + this._addListener(); + } + + this.setState({ isOpen: !this.state.isOpen }); + }; + + onSearchInputChange = ({ value }) => { + if (this._seriesLookupTimeout) { + clearTimeout(this._seriesLookupTimeout); + } + + this.setState({ term: value }, () => { + this._seriesLookupTimeout = setTimeout(() => { + this.props.onSearchInputChange(value); + }, 200); + }); + }; + + onRefreshPress = () => { + this.props.onSearchInputChange(this.state.term); + }; + + onSeriesSelect = (tvdbId) => { + this.setState({ isOpen: false }); + + this.props.onSeriesSelect(tvdbId); + }; + + // + // Render + + render() { + const { + selectedSeries, + isExistingSeries, + isFetching, + isPopulated, + error, + items, + isQueued, + isLookingUpSeries + } = this.props; + + const errorMessage = error && + error.responseJSON && + error.responseJSON.message; + + return ( + + + {({ ref }) => ( +
+ + { + isLookingUpSeries && isQueued && !isPopulated ? + : + null + } + + { + isPopulated && selectedSeries && isExistingSeries ? + : + null + } + + { + isPopulated && selectedSeries ? + : + null + } + + { + isPopulated && !selectedSeries ? +
+ + + {translate('NoMatchFound')} +
: + null + } + + { + !isFetching && !!error ? +
+ + + {translate('SearchFailedError')} +
: + null + } + +
+ +
+ +
+ )} +
+ + + + {({ ref, style, scheduleUpdate }) => { + this._scheduleUpdate = scheduleUpdate; + + return ( +
+ { + this.state.isOpen ? +
+
+
+ +
+ + + + + + +
+ +
+ { + items.map((item) => { + return ( + + ); + }) + } +
+
: + null + } +
+ ); + }} +
+
+
+ ); + } +} + +ImportSeriesSelectSeries.propTypes = { + id: PropTypes.string.isRequired, + selectedSeries: PropTypes.object, + isExistingSeries: PropTypes.bool.isRequired, + isFetching: PropTypes.bool.isRequired, + isPopulated: PropTypes.bool.isRequired, + error: PropTypes.object, + items: PropTypes.arrayOf(PropTypes.object).isRequired, + isQueued: PropTypes.bool.isRequired, + isLookingUpSeries: PropTypes.bool.isRequired, + onSearchInputChange: PropTypes.func.isRequired, + onSeriesSelect: PropTypes.func.isRequired +}; + +ImportSeriesSelectSeries.defaultProps = { + isFetching: true, + isPopulated: false, + items: [], + isQueued: true +}; + +export default ImportSeriesSelectSeries; diff --git a/frontend/src/AddSeries/ImportSeries/Import/SelectSeries/ImportSeriesSelectSeriesConnector.js b/frontend/src/AddSeries/ImportSeries/Import/SelectSeries/ImportSeriesSelectSeriesConnector.js new file mode 100644 index 000000000..935c95f4e --- /dev/null +++ b/frontend/src/AddSeries/ImportSeries/Import/SelectSeries/ImportSeriesSelectSeriesConnector.js @@ -0,0 +1,87 @@ +import PropTypes from 'prop-types'; +import React, { Component } from 'react'; +import { connect } from 'react-redux'; +import { createSelector } from 'reselect'; +import { queueLookupSeries, setImportSeriesValue } from 'Store/Actions/importSeriesActions'; +import createImportSeriesItemSelector from 'Store/Selectors/createImportSeriesItemSelector'; +import * as seriesTypes from 'Utilities/Series/seriesTypes'; +import ImportSeriesSelectSeries from './ImportSeriesSelectSeries'; + +function createMapStateToProps() { + return createSelector( + (state) => state.importSeries.isLookingUpSeries, + createImportSeriesItemSelector(), + (isLookingUpSeries, item) => { + return { + isLookingUpSeries, + ...item + }; + } + ); +} + +const mapDispatchToProps = { + queueLookupSeries, + setImportSeriesValue +}; + +class ImportSeriesSelectSeriesConnector extends Component { + + // + // Listeners + + onSearchInputChange = (term) => { + this.props.queueLookupSeries({ + name: this.props.id, + term, + topOfQueue: true + }); + }; + + onSeriesSelect = (tvdbId) => { + const { + id, + items, + onInputChange + } = this.props; + + const selectedSeries = items.find((item) => item.tvdbId === tvdbId); + + this.props.setImportSeriesValue({ + id, + selectedSeries + }); + + if (selectedSeries.seriesType !== seriesTypes.STANDARD) { + onInputChange({ + name: 'seriesType', + value: selectedSeries.seriesType + }); + } + }; + + // + // Render + + render() { + return ( + + ); + } +} + +ImportSeriesSelectSeriesConnector.propTypes = { + id: PropTypes.string.isRequired, + items: PropTypes.arrayOf(PropTypes.object), + selectedSeries: PropTypes.object, + isSelected: PropTypes.bool, + onInputChange: PropTypes.func.isRequired, + queueLookupSeries: PropTypes.func.isRequired, + setImportSeriesValue: PropTypes.func.isRequired +}; + +export default connect(createMapStateToProps, mapDispatchToProps)(ImportSeriesSelectSeriesConnector); diff --git a/frontend/src/AddSeries/ImportSeries/Import/SelectSeries/ImportSeriesTitle.css b/frontend/src/AddSeries/ImportSeries/Import/SelectSeries/ImportSeriesTitle.css new file mode 100644 index 000000000..ed00effa7 --- /dev/null +++ b/frontend/src/AddSeries/ImportSeries/Import/SelectSeries/ImportSeriesTitle.css @@ -0,0 +1,20 @@ +.titleContainer { + display: flex; + align-items: center; + flex: 0 1 auto; + overflow: hidden; +} + +.title { + @add-mixin truncate; +} + +.year { + margin-right: 5px; + margin-left: 5px; + color: var(--disabledColor); +} + +.existing { + margin-left: 5px; +} diff --git a/frontend/src/AddSeries/ImportSeries/Import/SelectSeries/ImportSeriesTitle.css.d.ts b/frontend/src/AddSeries/ImportSeries/Import/SelectSeries/ImportSeriesTitle.css.d.ts new file mode 100644 index 000000000..1816cf49e --- /dev/null +++ b/frontend/src/AddSeries/ImportSeries/Import/SelectSeries/ImportSeriesTitle.css.d.ts @@ -0,0 +1,10 @@ +// This file is automatically generated. +// Please do not change this file! +interface CssExports { + 'existing': string; + 'title': string; + 'titleContainer': string; + 'year': string; +} +export const cssExports: CssExports; +export default cssExports; diff --git a/frontend/src/AddSeries/ImportSeries/Import/SelectSeries/ImportSeriesTitle.js b/frontend/src/AddSeries/ImportSeries/Import/SelectSeries/ImportSeriesTitle.js new file mode 100644 index 000000000..c7ea7b961 --- /dev/null +++ b/frontend/src/AddSeries/ImportSeries/Import/SelectSeries/ImportSeriesTitle.js @@ -0,0 +1,57 @@ +import PropTypes from 'prop-types'; +import React from 'react'; +import Label from 'Components/Label'; +import { kinds } from 'Helpers/Props'; +import translate from 'Utilities/String/translate'; +import styles from './ImportSeriesTitle.css'; + +function ImportSeriesTitle(props) { + const { + title, + year, + network, + isExistingSeries + } = props; + + return ( +
+
+ {title} +
+ + { + !title.contains(year) && + year > 0 ? + + ({year}) + : + null + } + + { + network ? + : + null + } + + { + isExistingSeries ? + : + null + } +
+ ); +} + +ImportSeriesTitle.propTypes = { + title: PropTypes.string.isRequired, + year: PropTypes.number.isRequired, + network: PropTypes.string, + isExistingSeries: PropTypes.bool.isRequired +}; + +export default ImportSeriesTitle; diff --git a/frontend/src/AddSeries/ImportSeries/ImportSeries.js b/frontend/src/AddSeries/ImportSeries/ImportSeries.js new file mode 100644 index 000000000..8f9fed325 --- /dev/null +++ b/frontend/src/AddSeries/ImportSeries/ImportSeries.js @@ -0,0 +1,30 @@ +import React, { Component } from 'react'; +import { Route } from 'react-router-dom'; +import ImportSeriesConnector from 'AddSeries/ImportSeries/Import/ImportSeriesConnector'; +import ImportSeriesSelectFolderConnector from 'AddSeries/ImportSeries/SelectFolder/ImportSeriesSelectFolderConnector'; +import Switch from 'Components/Router/Switch'; + +class ImportSeries extends Component { + + // + // Render + + render() { + return ( + + + + + + ); + } +} + +export default ImportSeries; diff --git a/frontend/src/AddSeries/ImportSeries/SelectFolder/ImportSeriesSelectFolder.css b/frontend/src/AddSeries/ImportSeries/SelectFolder/ImportSeriesSelectFolder.css new file mode 100644 index 000000000..7c0dbc2aa --- /dev/null +++ b/frontend/src/AddSeries/ImportSeries/SelectFolder/ImportSeriesSelectFolder.css @@ -0,0 +1,38 @@ +.header { + margin-bottom: 40px; + text-align: center; + font-weight: 300; + font-size: 36px; +} + +.tips { + font-size: 20px; +} + +.tip { + font-size: $defaultFontSize; +} + +.code { + font-size: 12px; + font-family: $monoSpaceFontFamily; +} + +.recentFolders { + margin-top: 40px; +} + +.startImport { + margin-top: 40px; + text-align: center; +} + +.importButtonIcon { + margin-right: 8px; +} + +.addErrorAlert { + composes: alert from '~Components/Alert.css'; + + margin: 20px 0; +} diff --git a/frontend/src/AddSeries/ImportSeries/SelectFolder/ImportSeriesSelectFolder.css.d.ts b/frontend/src/AddSeries/ImportSeries/SelectFolder/ImportSeriesSelectFolder.css.d.ts new file mode 100644 index 000000000..e9d3bbc92 --- /dev/null +++ b/frontend/src/AddSeries/ImportSeries/SelectFolder/ImportSeriesSelectFolder.css.d.ts @@ -0,0 +1,14 @@ +// This file is automatically generated. +// Please do not change this file! +interface CssExports { + 'addErrorAlert': string; + 'code': string; + 'header': string; + 'importButtonIcon': string; + 'recentFolders': string; + 'startImport': string; + 'tip': string; + 'tips': string; +} +export const cssExports: CssExports; +export default cssExports; diff --git a/frontend/src/AddSeries/ImportSeries/SelectFolder/ImportSeriesSelectFolder.js b/frontend/src/AddSeries/ImportSeries/SelectFolder/ImportSeriesSelectFolder.js new file mode 100644 index 000000000..24fcff3dc --- /dev/null +++ b/frontend/src/AddSeries/ImportSeries/SelectFolder/ImportSeriesSelectFolder.js @@ -0,0 +1,188 @@ +import PropTypes from 'prop-types'; +import React, { Component } from 'react'; +import Alert from 'Components/Alert'; +import FieldSet from 'Components/FieldSet'; +import FileBrowserModal from 'Components/FileBrowser/FileBrowserModal'; +import Icon from 'Components/Icon'; +import Button from 'Components/Link/Button'; +import LoadingIndicator from 'Components/Loading/LoadingIndicator'; +import InlineMarkdown from 'Components/Markdown/InlineMarkdown'; +import PageContent from 'Components/Page/PageContent'; +import PageContentBody from 'Components/Page/PageContentBody'; +import { icons, kinds, sizes } from 'Helpers/Props'; +import RootFolders from 'RootFolder/RootFolders'; +import translate from 'Utilities/String/translate'; +import styles from './ImportSeriesSelectFolder.css'; + +class ImportSeriesSelectFolder extends Component { + + // + // Lifecycle + + constructor(props, context) { + super(props, context); + + this.state = { + isAddNewRootFolderModalOpen: false + }; + } + + // + // Lifecycle + + onAddNewRootFolderPress = () => { + this.setState({ isAddNewRootFolderModalOpen: true }); + }; + + onNewRootFolderSelect = ({ value }) => { + this.props.onNewRootFolderSelect(value); + }; + + onAddRootFolderModalClose = () => { + this.setState({ isAddNewRootFolderModalOpen: false }); + }; + + // + // Render + + render() { + const { + isWindows, + isFetching, + isPopulated, + isSaving, + error, + saveError, + items + } = this.props; + + const hasRootFolders = items.length > 0; + const goodFolderExample = (isWindows) ? 'C:\\tv shows' : '/tv shows'; + const badFolderExample = (isWindows) ? 'C:\\tv shows\\the simpsons' : '/tv shows/the simpsons'; + + return ( + + + { + isFetching && !isPopulated ? + : + null + } + + { + !isFetching && error ? + {translate('RootFoldersLoadError')} : + null + } + + { + !error && isPopulated && +
+
+ {translate('LibraryImportSeriesHeader')} +
+ +
+ {translate('LibraryImportTips')} +
    +
  • + +
  • +
  • + +
  • +
  • + {translate('LibraryImportTipsDontUseDownloadsFolder')} +
  • +
+
+ + { + hasRootFolders ? +
+
+ +
+
: + null + } + + { + !isSaving && saveError ? + + {translate('AddRootFolderError')} + +
    + { + Array.isArray(saveError.responseJSON) ? + saveError.responseJSON.map((e, index) => { + return ( +
  • + {e.errorMessage} +
  • + ); + }) : +
  • + { + JSON.stringify(saveError.responseJSON) + } +
  • + } +
+
: + null + } + +
+ +
+ + +
+ } +
+
+ ); + } +} + +ImportSeriesSelectFolder.propTypes = { + isWindows: PropTypes.bool.isRequired, + isFetching: PropTypes.bool.isRequired, + isPopulated: PropTypes.bool.isRequired, + isSaving: PropTypes.bool.isRequired, + error: PropTypes.object, + saveError: PropTypes.object, + items: PropTypes.arrayOf(PropTypes.object).isRequired, + onNewRootFolderSelect: PropTypes.func.isRequired +}; + +export default ImportSeriesSelectFolder; diff --git a/frontend/src/AddSeries/ImportSeries/SelectFolder/ImportSeriesSelectFolderConnector.js b/frontend/src/AddSeries/ImportSeries/SelectFolder/ImportSeriesSelectFolderConnector.js new file mode 100644 index 000000000..1df231f4e --- /dev/null +++ b/frontend/src/AddSeries/ImportSeries/SelectFolder/ImportSeriesSelectFolderConnector.js @@ -0,0 +1,85 @@ +import { push } from 'connected-react-router'; +import _ from 'lodash'; +import PropTypes from 'prop-types'; +import React, { Component } from 'react'; +import { connect } from 'react-redux'; +import { createSelector } from 'reselect'; +import { addRootFolder, fetchRootFolders } from 'Store/Actions/rootFolderActions'; +import createRootFoldersSelector from 'Store/Selectors/createRootFoldersSelector'; +import createSystemStatusSelector from 'Store/Selectors/createSystemStatusSelector'; +import ImportSeriesSelectFolder from './ImportSeriesSelectFolder'; + +function createMapStateToProps() { + return createSelector( + createRootFoldersSelector(), + createSystemStatusSelector(), + (rootFolders, systemStatus) => { + return { + ...rootFolders, + isWindows: systemStatus.isWindows + }; + } + ); +} + +const mapDispatchToProps = { + fetchRootFolders, + addRootFolder, + push +}; + +class ImportSeriesSelectFolderConnector extends Component { + + // + // Lifecycle + + componentDidMount() { + this.props.fetchRootFolders(); + } + + componentDidUpdate(prevProps) { + const { + items, + isSaving, + saveError + } = this.props; + + if (prevProps.isSaving && !isSaving && !saveError) { + const newRootFolders = _.differenceBy(items, prevProps.items, (item) => item.id); + + if (newRootFolders.length === 1) { + this.props.push(`${window.Sonarr.urlBase}/add/import/${newRootFolders[0].id}`); + } + } + } + + // + // Listeners + + onNewRootFolderSelect = (path) => { + this.props.addRootFolder({ path }); + }; + + // + // Render + + render() { + return ( + + ); + } +} + +ImportSeriesSelectFolderConnector.propTypes = { + isSaving: PropTypes.bool.isRequired, + saveError: PropTypes.object, + items: PropTypes.arrayOf(PropTypes.object).isRequired, + fetchRootFolders: PropTypes.func.isRequired, + addRootFolder: PropTypes.func.isRequired, + push: PropTypes.func.isRequired +}; + +export default connect(createMapStateToProps, mapDispatchToProps)(ImportSeriesSelectFolderConnector); diff --git a/frontend/src/AddSeries/SeriesMonitorNewItemsOptionsPopoverContent.js b/frontend/src/AddSeries/SeriesMonitorNewItemsOptionsPopoverContent.js new file mode 100644 index 000000000..c70ec0dec --- /dev/null +++ b/frontend/src/AddSeries/SeriesMonitorNewItemsOptionsPopoverContent.js @@ -0,0 +1,22 @@ +import React from 'react'; +import DescriptionList from 'Components/DescriptionList/DescriptionList'; +import DescriptionListItem from 'Components/DescriptionList/DescriptionListItem'; +import translate from 'Utilities/String/translate'; + +function SeriesMonitorNewItemsOptionsPopoverContent() { + return ( + + + + + + ); +} + +export default SeriesMonitorNewItemsOptionsPopoverContent; diff --git a/frontend/src/AddSeries/SeriesMonitoringOptionsPopoverContent.js b/frontend/src/AddSeries/SeriesMonitoringOptionsPopoverContent.js new file mode 100644 index 000000000..21289fcb8 --- /dev/null +++ b/frontend/src/AddSeries/SeriesMonitoringOptionsPopoverContent.js @@ -0,0 +1,67 @@ +import React from 'react'; +import DescriptionList from 'Components/DescriptionList/DescriptionList'; +import DescriptionListItem from 'Components/DescriptionList/DescriptionListItem'; +import translate from 'Utilities/String/translate'; + +function SeriesMonitoringOptionsPopoverContent() { + return ( + + + + + + + + + + + + + + + + + + + + + + + + ); +} + +export default SeriesMonitoringOptionsPopoverContent; diff --git a/frontend/src/AddSeries/SeriesTypePopoverContent.js b/frontend/src/AddSeries/SeriesTypePopoverContent.js new file mode 100644 index 000000000..9771bd8db --- /dev/null +++ b/frontend/src/AddSeries/SeriesTypePopoverContent.js @@ -0,0 +1,27 @@ +import React from 'react'; +import DescriptionList from 'Components/DescriptionList/DescriptionList'; +import DescriptionListItem from 'Components/DescriptionList/DescriptionListItem'; +import translate from 'Utilities/String/translate'; + +function SeriesTypePopoverContent() { + return ( + + + + + + + + ); +} + +export default SeriesTypePopoverContent; diff --git a/frontend/src/App/App.tsx b/frontend/src/App/App.tsx new file mode 100644 index 000000000..b71199bb3 --- /dev/null +++ b/frontend/src/App/App.tsx @@ -0,0 +1,35 @@ +import { QueryClient, QueryClientProvider } from '@tanstack/react-query'; +import { ConnectedRouter, ConnectedRouterProps } from 'connected-react-router'; +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'; + +interface AppProps { + store: Store; + history: ConnectedRouterProps['history']; +} + +const queryClient = new QueryClient(); + +function App({ store, history }: AppProps) { + return ( + + + + + + + + + + + + + ); +} + +export default App; diff --git a/frontend/src/App/AppRoutes.tsx b/frontend/src/App/AppRoutes.tsx new file mode 100644 index 000000000..fbe4a15bb --- /dev/null +++ b/frontend/src/App/AppRoutes.tsx @@ -0,0 +1,167 @@ +import React from 'react'; +import { Redirect, Route } from 'react-router-dom'; +import Blocklist from 'Activity/Blocklist/Blocklist'; +import History from 'Activity/History/History'; +import Queue from 'Activity/Queue/Queue'; +import AddNewSeriesConnector from 'AddSeries/AddNewSeries/AddNewSeriesConnector'; +import ImportSeries from 'AddSeries/ImportSeries/ImportSeries'; +import CalendarPage from 'Calendar/CalendarPage'; +import NotFound from 'Components/NotFound'; +import Switch from 'Components/Router/Switch'; +import SeriesDetailsPageConnector from 'Series/Details/SeriesDetailsPageConnector'; +import SeriesIndex from 'Series/Index/SeriesIndex'; +import CustomFormatSettingsPage from 'Settings/CustomFormats/CustomFormatSettingsPage'; +import DownloadClientSettingsConnector from 'Settings/DownloadClients/DownloadClientSettingsConnector'; +import GeneralSettingsConnector from 'Settings/General/GeneralSettingsConnector'; +import ImportListSettingsConnector from 'Settings/ImportLists/ImportListSettingsConnector'; +import IndexerSettingsConnector from 'Settings/Indexers/IndexerSettingsConnector'; +import MediaManagementConnector from 'Settings/MediaManagement/MediaManagementConnector'; +import MetadataSettings from 'Settings/Metadata/MetadataSettings'; +import MetadataSourceSettings from 'Settings/MetadataSource/MetadataSourceSettings'; +import NotificationSettings from 'Settings/Notifications/NotificationSettings'; +import Profiles from 'Settings/Profiles/Profiles'; +import QualityConnector from 'Settings/Quality/QualityConnector'; +import Settings from 'Settings/Settings'; +import TagSettings from 'Settings/Tags/TagSettings'; +import UISettingsConnector from 'Settings/UI/UISettingsConnector'; +import BackupsConnector from 'System/Backup/BackupsConnector'; +import LogsTableConnector from 'System/Events/LogsTableConnector'; +import Logs from 'System/Logs/Logs'; +import Status from 'System/Status/Status'; +import Tasks from 'System/Tasks/Tasks'; +import Updates from 'System/Updates/Updates'; +import getPathWithUrlBase from 'Utilities/getPathWithUrlBase'; +import CutoffUnmetConnector from 'Wanted/CutoffUnmet/CutoffUnmetConnector'; +import MissingConnector from 'Wanted/Missing/MissingConnector'; + +function RedirectWithUrlBase() { + return ; +} + +function AppRoutes() { + return ( + + {/* + Series + */} + + + + {window.Sonarr.urlBase && ( + + )} + + + + + + + + + + + + {/* + Calendar + */} + + + + {/* + Activity + */} + + + + + + + + {/* + Wanted + */} + + + + + + {/* + Settings + */} + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + {/* + System + */} + + + + + + + + + + + + + + {/* + Not Found + */} + + + + ); +} + +export default AppRoutes; diff --git a/frontend/src/App/AppUpdatedModal.tsx b/frontend/src/App/AppUpdatedModal.tsx new file mode 100644 index 000000000..696d36fb2 --- /dev/null +++ b/frontend/src/App/AppUpdatedModal.tsx @@ -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 ( + + + + ); +} + +export default AppUpdatedModal; diff --git a/frontend/src/App/AppUpdatedModalContent.css b/frontend/src/App/AppUpdatedModalContent.css new file mode 100644 index 000000000..0df4183a6 --- /dev/null +++ b/frontend/src/App/AppUpdatedModalContent.css @@ -0,0 +1,16 @@ +.version { + margin: 0 3px; + font-weight: bold; + font-family: var(--defaultFontFamily); +} + +.maintenance { + margin-top: 20px; +} + +.changes { + margin-top: 20px; + padding-bottom: 5px; + border-bottom: 1px solid #e5e5e5; + font-size: 18px; +} diff --git a/frontend/src/App/AppUpdatedModalContent.css.d.ts b/frontend/src/App/AppUpdatedModalContent.css.d.ts new file mode 100644 index 000000000..70ddbf6a1 --- /dev/null +++ b/frontend/src/App/AppUpdatedModalContent.css.d.ts @@ -0,0 +1,9 @@ +// This file is automatically generated. +// Please do not change this file! +interface CssExports { + 'changes': string; + 'maintenance': string; + 'version': string; +} +export const cssExports: CssExports; +export default cssExports; diff --git a/frontend/src/App/AppUpdatedModalContent.tsx b/frontend/src/App/AppUpdatedModalContent.tsx new file mode 100644 index 000000000..6553d6270 --- /dev/null +++ b/frontend/src/App/AppUpdatedModalContent.tsx @@ -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 ( + + {translate('AppUpdated')} + + +
+ +
+ + {isPopulated && !error && !!update ? ( +
+ {update.changes ? ( +
+ {translate('MaintenanceRelease')} +
+ ) : null} + + {update.changes ? ( +
+
{translate('WhatsNew')}
+ + + + +
+ ) : null} +
+ ) : null} + + {!isPopulated && !error ? : null} +
+ + + + + + +
+ ); +} + +export default AppUpdatedModalContent; diff --git a/frontend/src/App/ApplyTheme.tsx b/frontend/src/App/ApplyTheme.tsx new file mode 100644 index 000000000..ce598f2dc --- /dev/null +++ b/frontend/src/App/ApplyTheme.tsx @@ -0,0 +1,33 @@ +import { useCallback, useEffect } from 'react'; +import { useSelector } from 'react-redux'; +import { createSelector } from 'reselect'; +import themes from 'Styles/Themes'; +import AppState from './State/AppState'; + +function createThemeSelector() { + return createSelector( + (state: AppState) => state.settings.ui.item.theme || window.Sonarr.theme, + (theme) => { + return theme; + } + ); +} + +function ApplyTheme() { + const theme = useSelector(createThemeSelector()); + + const updateCSSVariables = useCallback(() => { + Object.entries(themes[theme]).forEach(([key, value]) => { + document.documentElement.style.setProperty(`--${key}`, value); + }); + }, [theme]); + + // On Component Mount and Component Update + useEffect(() => { + updateCSSVariables(); + }, [updateCSSVariables, theme]); + + return null; +} + +export default ApplyTheme; diff --git a/frontend/src/App/ColorImpairedContext.ts b/frontend/src/App/ColorImpairedContext.ts new file mode 100644 index 000000000..de98ac8fb --- /dev/null +++ b/frontend/src/App/ColorImpairedContext.ts @@ -0,0 +1,6 @@ +import React from 'react'; + +const ColorImpairedContext = React.createContext(false); +export const ColorImpairedConsumer = ColorImpairedContext.Consumer; + +export default ColorImpairedContext; diff --git a/frontend/src/App/ConnectionLostModal.css b/frontend/src/App/ConnectionLostModal.css new file mode 100644 index 000000000..f0a9d220f --- /dev/null +++ b/frontend/src/App/ConnectionLostModal.css @@ -0,0 +1,3 @@ +.automatic { + margin-top: 20px; +} diff --git a/frontend/src/App/ConnectionLostModal.css.d.ts b/frontend/src/App/ConnectionLostModal.css.d.ts new file mode 100644 index 000000000..027f2a9a3 --- /dev/null +++ b/frontend/src/App/ConnectionLostModal.css.d.ts @@ -0,0 +1,7 @@ +// This file is automatically generated. +// Please do not change this file! +interface CssExports { + 'automatic': string; +} +export const cssExports: CssExports; +export default cssExports; diff --git a/frontend/src/App/ConnectionLostModal.tsx b/frontend/src/App/ConnectionLostModal.tsx new file mode 100644 index 000000000..f08f2c0e2 --- /dev/null +++ b/frontend/src/App/ConnectionLostModal.tsx @@ -0,0 +1,45 @@ +import React, { useCallback } from 'react'; +import Button from 'Components/Link/Button'; +import Modal from 'Components/Modal/Modal'; +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 translate from 'Utilities/String/translate'; +import styles from './ConnectionLostModal.css'; + +interface ConnectionLostModalProps { + isOpen: boolean; +} + +function ConnectionLostModal(props: ConnectionLostModalProps) { + const { isOpen } = props; + + const handleModalClose = useCallback(() => { + location.reload(); + }, []); + + return ( + + + {translate('ConnectionLost')} + + +
{translate('ConnectionLostToBackend')}
+ +
+ {translate('ConnectionLostReconnect')} +
+
+ + + +
+
+ ); +} + +export default ConnectionLostModal; diff --git a/frontend/src/App/ModelBase.ts b/frontend/src/App/ModelBase.ts new file mode 100644 index 000000000..187b12fb2 --- /dev/null +++ b/frontend/src/App/ModelBase.ts @@ -0,0 +1,5 @@ +interface ModelBase { + id: number; +} + +export default ModelBase; diff --git a/frontend/src/App/SelectContext.tsx b/frontend/src/App/SelectContext.tsx new file mode 100644 index 000000000..66be388ce --- /dev/null +++ b/frontend/src/App/SelectContext.tsx @@ -0,0 +1,83 @@ +import { cloneDeep } from 'lodash'; +import React, { useCallback, useEffect } from 'react'; +import useSelectState, { SelectState } from 'Helpers/Hooks/useSelectState'; +import ModelBase from './ModelBase'; + +export type SelectContextAction = + | { type: 'reset' } + | { type: 'selectAll' } + | { type: 'unselectAll' } + | { + type: 'toggleSelected'; + id: number; + isSelected: boolean; + shiftKey: boolean; + } + | { + type: 'removeItem'; + id: number; + } + | { + type: 'updateItems'; + items: ModelBase[]; + }; + +export type SelectDispatch = (action: SelectContextAction) => void; + +interface SelectProviderOptions { + // eslint-disable-next-line @typescript-eslint/no-explicit-any + children: any; + items: Array; +} + +const SelectContext = React.createContext< + [SelectState, SelectDispatch] | undefined +>(cloneDeep(undefined)); + +export function SelectProvider( + props: SelectProviderOptions +) { + const { items } = props; + const [state, dispatch] = useSelectState(); + + const dispatchWrapper = useCallback( + (action: SelectContextAction) => { + switch (action.type) { + case 'reset': + case 'removeItem': + dispatch(action); + break; + + default: + dispatch({ + ...action, + items, + }); + break; + } + }, + [items, dispatch] + ); + + const value: [SelectState, SelectDispatch] = [state, dispatchWrapper]; + + useEffect(() => { + dispatch({ type: 'updateItems', items }); + }, [items, dispatch]); + + return ( + + {props.children} + + ); +} + +export function useSelect() { + const context = React.useContext(SelectContext); + + if (context === undefined) { + throw new Error('useSelect must be used within a SelectProvider'); + } + + return context; +} diff --git a/frontend/src/App/State/AppSectionState.ts b/frontend/src/App/State/AppSectionState.ts new file mode 100644 index 000000000..4e9dbe7a0 --- /dev/null +++ b/frontend/src/App/State/AppSectionState.ts @@ -0,0 +1,85 @@ +import Column from 'Components/Table/Column'; +import { SortDirection } from 'Helpers/Props/sortDirections'; +import { ValidationFailure } from 'typings/pending'; +import { FilterBuilderProp, PropertyFilter } from './AppState'; + +export interface Error { + status?: number; + responseJSON: + | { + message: string | undefined; + } + | ValidationFailure[] + | undefined; +} + +export interface AppSectionDeleteState { + isDeleting: boolean; + deleteError: Error; +} + +export interface AppSectionSaveState { + isSaving: boolean; + saveError: Error; +} + +export interface PagedAppSectionState { + page: number; + pageSize: number; + totalPages: number; + totalRecords?: number; +} +export interface TableAppSectionState { + columns: Column[]; +} + +export interface AppSectionFilterState { + selectedFilterKey: string; + filters: PropertyFilter[]; + filterBuilderProps: FilterBuilderProp[]; +} + +export interface AppSectionSchemaState { + isSchemaFetching: boolean; + isSchemaPopulated: boolean; + schemaError: Error; + schema: { + items: T[]; + }; +} + +export interface AppSectionItemSchemaState { + isSchemaFetching: boolean; + isSchemaPopulated: boolean; + schemaError: Error; + schema: T; +} + +export interface AppSectionItemState { + isFetching: boolean; + isPopulated: boolean; + error: Error; + pendingChanges: Partial; + item: T; +} + +export interface AppSectionProviderState + extends AppSectionDeleteState, + AppSectionSaveState { + isFetching: boolean; + isPopulated: boolean; + error: Error; + items: T[]; + pendingChanges: Partial; +} + +interface AppSectionState { + isFetching: boolean; + isPopulated: boolean; + error: Error; + items: T[]; + sortKey: string; + sortDirection: SortDirection; +} + +export default AppSectionState; diff --git a/frontend/src/App/State/AppState.ts b/frontend/src/App/State/AppState.ts new file mode 100644 index 000000000..84bd5d0b4 --- /dev/null +++ b/frontend/src/App/State/AppState.ts @@ -0,0 +1,95 @@ +import BlocklistAppState from './BlocklistAppState'; +import CalendarAppState from './CalendarAppState'; +import CaptchaAppState from './CaptchaAppState'; +import CommandAppState from './CommandAppState'; +import EpisodeFilesAppState from './EpisodeFilesAppState'; +import EpisodesAppState from './EpisodesAppState'; +import HistoryAppState from './HistoryAppState'; +import InteractiveImportAppState from './InteractiveImportAppState'; +import OAuthAppState from './OAuthAppState'; +import ParseAppState from './ParseAppState'; +import PathsAppState from './PathsAppState'; +import ProviderOptionsAppState from './ProviderOptionsAppState'; +import QueueAppState from './QueueAppState'; +import ReleasesAppState from './ReleasesAppState'; +import RootFolderAppState from './RootFolderAppState'; +import SeriesAppState, { SeriesIndexAppState } from './SeriesAppState'; +import SettingsAppState from './SettingsAppState'; +import SystemAppState from './SystemAppState'; +import TagsAppState from './TagsAppState'; +import WantedAppState from './WantedAppState'; + +interface FilterBuilderPropOption { + id: string; + name: string; +} + +export interface FilterBuilderProp { + name: string; + label: string; + type: string; + valueType?: string; + optionsSelector?: (items: T[]) => FilterBuilderPropOption[]; +} + +export interface PropertyFilter { + key: string; + value: boolean | string | number | string[] | number[]; + type: string; +} + +export interface Filter { + key: string; + label: string; + filters: PropertyFilter[]; +} + +export interface CustomFilter { + id: number; + type: string; + label: string; + filters: PropertyFilter[]; +} + +export interface AppSectionState { + isConnected: boolean; + isReconnecting: boolean; + isSidebarVisible: boolean; + version: string; + prevVersion?: string; + dimensions: { + isSmallScreen: boolean; + isLargeScreen: boolean; + width: number; + height: number; + }; +} + +interface AppState { + app: AppSectionState; + blocklist: BlocklistAppState; + calendar: CalendarAppState; + captcha: CaptchaAppState; + commands: CommandAppState; + episodeFiles: EpisodeFilesAppState; + episodeHistory: HistoryAppState; + episodes: EpisodesAppState; + episodesSelection: EpisodesAppState; + history: HistoryAppState; + interactiveImport: InteractiveImportAppState; + oAuth: OAuthAppState; + parse: ParseAppState; + paths: PathsAppState; + providerOptions: ProviderOptionsAppState; + queue: QueueAppState; + releases: ReleasesAppState; + rootFolders: RootFolderAppState; + series: SeriesAppState; + seriesIndex: SeriesIndexAppState; + settings: SettingsAppState; + system: SystemAppState; + tags: TagsAppState; + wanted: WantedAppState; +} + +export default AppState; diff --git a/frontend/src/App/State/BlocklistAppState.ts b/frontend/src/App/State/BlocklistAppState.ts new file mode 100644 index 000000000..004a30732 --- /dev/null +++ b/frontend/src/App/State/BlocklistAppState.ts @@ -0,0 +1,16 @@ +import Blocklist from 'typings/Blocklist'; +import AppSectionState, { + AppSectionFilterState, + PagedAppSectionState, + TableAppSectionState, +} from './AppSectionState'; + +interface BlocklistAppState + extends AppSectionState, + AppSectionFilterState, + PagedAppSectionState, + TableAppSectionState { + isRemoving: boolean; +} + +export default BlocklistAppState; diff --git a/frontend/src/App/State/CalendarAppState.ts b/frontend/src/App/State/CalendarAppState.ts new file mode 100644 index 000000000..75c8b5e50 --- /dev/null +++ b/frontend/src/App/State/CalendarAppState.ts @@ -0,0 +1,29 @@ +import moment from 'moment'; +import AppSectionState, { + AppSectionFilterState, +} from 'App/State/AppSectionState'; +import { CalendarView } from 'Calendar/calendarViews'; +import { CalendarItem } from 'typings/Calendar'; + +interface CalendarOptions { + showEpisodeInformation: boolean; + showFinaleIcon: boolean; + showSpecialIcon: boolean; + showCutoffUnmetIcon: boolean; + collapseMultipleEpisodes: boolean; + fullColorEvents: boolean; +} + +interface CalendarAppState + extends AppSectionState, + AppSectionFilterState { + searchMissingCommandId: number | null; + start: moment.Moment; + end: moment.Moment; + dates: string[]; + time: string; + view: CalendarView; + options: CalendarOptions; +} + +export default CalendarAppState; diff --git a/frontend/src/App/State/CaptchaAppState.ts b/frontend/src/App/State/CaptchaAppState.ts new file mode 100644 index 000000000..7252937eb --- /dev/null +++ b/frontend/src/App/State/CaptchaAppState.ts @@ -0,0 +1,11 @@ +interface CaptchaAppState { + refreshing: false; + token: string; + siteKey: unknown; + secretToken: unknown; + ray: unknown; + stoken: unknown; + responseUrl: unknown; +} + +export default CaptchaAppState; diff --git a/frontend/src/App/State/ClientSideCollectionAppState.ts b/frontend/src/App/State/ClientSideCollectionAppState.ts new file mode 100644 index 000000000..f4110ef73 --- /dev/null +++ b/frontend/src/App/State/ClientSideCollectionAppState.ts @@ -0,0 +1,8 @@ +import { CustomFilter } from './AppState'; + +interface ClientSideCollectionAppState { + totalItems: number; + customFilters: CustomFilter[]; +} + +export default ClientSideCollectionAppState; diff --git a/frontend/src/App/State/CommandAppState.ts b/frontend/src/App/State/CommandAppState.ts new file mode 100644 index 000000000..1bde37371 --- /dev/null +++ b/frontend/src/App/State/CommandAppState.ts @@ -0,0 +1,6 @@ +import AppSectionState from 'App/State/AppSectionState'; +import Command from 'Commands/Command'; + +export type CommandAppState = AppSectionState; + +export default CommandAppState; diff --git a/frontend/src/App/State/CustomFiltersAppState.ts b/frontend/src/App/State/CustomFiltersAppState.ts new file mode 100644 index 000000000..6ac4820c7 --- /dev/null +++ b/frontend/src/App/State/CustomFiltersAppState.ts @@ -0,0 +1,10 @@ +import AppSectionState, { + AppSectionDeleteState, +} from 'App/State/AppSectionState'; +import { CustomFilter } from './AppState'; + +interface CustomFiltersAppState + extends AppSectionState, + AppSectionDeleteState {} + +export default CustomFiltersAppState; diff --git a/frontend/src/App/State/EpisodeFilesAppState.ts b/frontend/src/App/State/EpisodeFilesAppState.ts new file mode 100644 index 000000000..5e6e94a06 --- /dev/null +++ b/frontend/src/App/State/EpisodeFilesAppState.ts @@ -0,0 +1,10 @@ +import AppSectionState, { + AppSectionDeleteState, +} from 'App/State/AppSectionState'; +import { EpisodeFile } from 'EpisodeFile/EpisodeFile'; + +interface EpisodeFilesAppState + extends AppSectionState, + AppSectionDeleteState {} + +export default EpisodeFilesAppState; diff --git a/frontend/src/App/State/EpisodesAppState.ts b/frontend/src/App/State/EpisodesAppState.ts new file mode 100644 index 000000000..4234c0bcb --- /dev/null +++ b/frontend/src/App/State/EpisodesAppState.ts @@ -0,0 +1,6 @@ +import AppSectionState from 'App/State/AppSectionState'; +import Episode from 'Episode/Episode'; + +type EpisodesAppState = AppSectionState; + +export default EpisodesAppState; diff --git a/frontend/src/App/State/HistoryAppState.ts b/frontend/src/App/State/HistoryAppState.ts new file mode 100644 index 000000000..632b82179 --- /dev/null +++ b/frontend/src/App/State/HistoryAppState.ts @@ -0,0 +1,14 @@ +import AppSectionState, { + AppSectionFilterState, + PagedAppSectionState, + TableAppSectionState, +} from 'App/State/AppSectionState'; +import History from 'typings/History'; + +interface HistoryAppState + extends AppSectionState, + AppSectionFilterState, + PagedAppSectionState, + TableAppSectionState {} + +export default HistoryAppState; diff --git a/frontend/src/App/State/InteractiveImportAppState.ts b/frontend/src/App/State/InteractiveImportAppState.ts new file mode 100644 index 000000000..84fd9f4c1 --- /dev/null +++ b/frontend/src/App/State/InteractiveImportAppState.ts @@ -0,0 +1,21 @@ +import AppSectionState from 'App/State/AppSectionState'; +import ImportMode from 'InteractiveImport/ImportMode'; +import InteractiveImport from 'InteractiveImport/InteractiveImport'; + +interface FavoriteFolder { + folder: string; +} + +interface RecentFolder { + folder: string; + lastUsed: string; +} + +interface InteractiveImportAppState extends AppSectionState { + originalItems: InteractiveImport[]; + importMode: ImportMode; + favoriteFolders: FavoriteFolder[]; + recentFolders: RecentFolder[]; +} + +export default InteractiveImportAppState; diff --git a/frontend/src/App/State/MetadataAppState.ts b/frontend/src/App/State/MetadataAppState.ts new file mode 100644 index 000000000..495f109d8 --- /dev/null +++ b/frontend/src/App/State/MetadataAppState.ts @@ -0,0 +1,6 @@ +import { AppSectionProviderState } from 'App/State/AppSectionState'; +import Metadata from 'typings/Metadata'; + +type MetadataAppState = AppSectionProviderState; + +export default MetadataAppState; diff --git a/frontend/src/App/State/OAuthAppState.ts b/frontend/src/App/State/OAuthAppState.ts new file mode 100644 index 000000000..619767929 --- /dev/null +++ b/frontend/src/App/State/OAuthAppState.ts @@ -0,0 +1,9 @@ +import { Error } from './AppSectionState'; + +interface OAuthAppState { + authorizing: boolean; + result: Record | null; + error: Error; +} + +export default OAuthAppState; diff --git a/frontend/src/App/State/ParseAppState.ts b/frontend/src/App/State/ParseAppState.ts new file mode 100644 index 000000000..67fb4cc63 --- /dev/null +++ b/frontend/src/App/State/ParseAppState.ts @@ -0,0 +1,54 @@ +import ModelBase from 'App/ModelBase'; +import { AppSectionItemState } from 'App/State/AppSectionState'; +import Episode from 'Episode/Episode'; +import Language from 'Language/Language'; +import { QualityModel } from 'Quality/Quality'; +import Series from 'Series/Series'; +import CustomFormat from 'typings/CustomFormat'; + +export interface SeriesTitleInfo { + title: string; + titleWithoutYear: string; + year: number; + allTitles: string[]; +} + +export interface ParsedEpisodeInfo { + releaseTitle: string; + seriesTitle: string; + seriesTitleInfo: SeriesTitleInfo; + quality: QualityModel; + seasonNumber: number; + episodeNumbers: number[]; + absoluteEpisodeNumbers: number[]; + specialAbsoluteEpisodeNumbers: number[]; + languages: Language[]; + fullSeason: boolean; + isPartialSeason: boolean; + isMultiSeason: boolean; + isSeasonExtra: boolean; + special: boolean; + releaseHash: string; + seasonPart: number; + releaseGroup?: string; + releaseTokens: string; + airDate?: string; + isDaily: boolean; + isAbsoluteNumbering: boolean; + isPossibleSpecialEpisode: boolean; + isPossibleSceneSeasonSpecial: boolean; +} + +export interface ParseModel extends ModelBase { + title: string; + parsedEpisodeInfo: ParsedEpisodeInfo; + series?: Series; + episodes: Episode[]; + languages?: Language[]; + customFormats?: CustomFormat[]; + customFormatScore?: number; +} + +type ParseAppState = AppSectionItemState; + +export default ParseAppState; diff --git a/frontend/src/App/State/PathsAppState.ts b/frontend/src/App/State/PathsAppState.ts new file mode 100644 index 000000000..068a48dc0 --- /dev/null +++ b/frontend/src/App/State/PathsAppState.ts @@ -0,0 +1,29 @@ +interface BasePath { + name: string; + path: string; + size: number; + lastModified: string; +} + +interface File extends BasePath { + type: 'file'; +} + +interface Folder extends BasePath { + type: 'folder'; +} + +export type PathType = 'file' | 'folder' | 'drive' | 'computer' | 'parent'; +export type Path = File | Folder; + +interface PathsAppState { + currentPath: string; + isFetching: boolean; + isPopulated: boolean; + error: Error; + directories: Folder[]; + files: File[]; + parent: string | null; +} + +export default PathsAppState; diff --git a/frontend/src/App/State/ProviderOptionsAppState.ts b/frontend/src/App/State/ProviderOptionsAppState.ts new file mode 100644 index 000000000..7fb5df02b --- /dev/null +++ b/frontend/src/App/State/ProviderOptionsAppState.ts @@ -0,0 +1,22 @@ +import AppSectionState from 'App/State/AppSectionState'; +import Field, { FieldSelectOption } from 'typings/Field'; + +export interface ProviderOptions { + fields?: Field[]; +} + +interface ProviderOptionsDevice { + id: string; + name: string; +} + +interface ProviderOptionsAppState { + devices: AppSectionState; + servers: AppSectionState>; + newznabCategories: AppSectionState>; + getProfiles: AppSectionState>; + getTags: AppSectionState>; + getRootFolders: AppSectionState>; +} + +export default ProviderOptionsAppState; diff --git a/frontend/src/App/State/QueueAppState.ts b/frontend/src/App/State/QueueAppState.ts new file mode 100644 index 000000000..954d649a2 --- /dev/null +++ b/frontend/src/App/State/QueueAppState.ts @@ -0,0 +1,44 @@ +import Queue from 'typings/Queue'; +import AppSectionState, { + AppSectionFilterState, + AppSectionItemState, + Error, + PagedAppSectionState, + TableAppSectionState, +} from './AppSectionState'; + +export interface QueueStatus { + totalCount: number; + count: number; + unknownCount: number; + errors: boolean; + warnings: boolean; + unknownErrors: boolean; + unknownWarnings: boolean; +} + +export interface QueueDetailsAppState extends AppSectionState { + params: unknown; +} + +export interface QueuePagedAppState + extends AppSectionState, + AppSectionFilterState, + PagedAppSectionState, + TableAppSectionState { + isGrabbing: boolean; + grabError: Error; + isRemoving: boolean; + removeError: Error; +} + +interface QueueAppState { + status: AppSectionItemState; + details: QueueDetailsAppState; + paged: QueuePagedAppState; + options: { + includeUnknownSeriesItems: boolean; + }; +} + +export default QueueAppState; diff --git a/frontend/src/App/State/ReleasesAppState.ts b/frontend/src/App/State/ReleasesAppState.ts new file mode 100644 index 000000000..350f6eac8 --- /dev/null +++ b/frontend/src/App/State/ReleasesAppState.ts @@ -0,0 +1,10 @@ +import AppSectionState, { + AppSectionFilterState, +} from 'App/State/AppSectionState'; +import Release from 'typings/Release'; + +interface ReleasesAppState + extends AppSectionState, + AppSectionFilterState {} + +export default ReleasesAppState; diff --git a/frontend/src/App/State/RootFolderAppState.ts b/frontend/src/App/State/RootFolderAppState.ts new file mode 100644 index 000000000..9e636c95f --- /dev/null +++ b/frontend/src/App/State/RootFolderAppState.ts @@ -0,0 +1,12 @@ +import AppSectionState, { + AppSectionDeleteState, + AppSectionSaveState, +} from 'App/State/AppSectionState'; +import RootFolder from 'typings/RootFolder'; + +interface RootFolderAppState + extends AppSectionState, + AppSectionDeleteState, + AppSectionSaveState {} + +export default RootFolderAppState; diff --git a/frontend/src/App/State/SeriesAppState.ts b/frontend/src/App/State/SeriesAppState.ts new file mode 100644 index 000000000..5da5987dd --- /dev/null +++ b/frontend/src/App/State/SeriesAppState.ts @@ -0,0 +1,66 @@ +import AppSectionState, { + AppSectionDeleteState, + AppSectionSaveState, +} from 'App/State/AppSectionState'; +import Column from 'Components/Table/Column'; +import { SortDirection } from 'Helpers/Props/sortDirections'; +import Series from 'Series/Series'; +import { Filter, FilterBuilderProp } from './AppState'; + +export interface SeriesIndexAppState { + sortKey: string; + sortDirection: SortDirection; + secondarySortKey: string; + secondarySortDirection: SortDirection; + view: string; + + posterOptions: { + detailedProgressBar: boolean; + size: string; + showTitle: boolean; + showMonitored: boolean; + showQualityProfile: boolean; + showTags: boolean; + showSearchAction: boolean; + }; + + overviewOptions: { + detailedProgressBar: boolean; + size: string; + showMonitored: boolean; + showNetwork: boolean; + showQualityProfile: boolean; + showPreviousAiring: boolean; + showAdded: boolean; + showSeasonCount: boolean; + showPath: boolean; + showSizeOnDisk: boolean; + showTags: boolean; + showSearchAction: boolean; + }; + + tableOptions: { + showBanners: boolean; + showSearchAction: boolean; + }; + + selectedFilterKey: string; + filterBuilderProps: FilterBuilderProp[]; + filters: Filter[]; + columns: Column[]; +} + +interface SeriesAppState + extends AppSectionState, + AppSectionDeleteState, + AppSectionSaveState { + itemMap: Record; + + deleteOptions: { + addImportListExclusion: boolean; + }; + + pendingChanges: Partial; +} + +export default SeriesAppState; diff --git a/frontend/src/App/State/SettingsAppState.ts b/frontend/src/App/State/SettingsAppState.ts new file mode 100644 index 000000000..b8e6f4954 --- /dev/null +++ b/frontend/src/App/State/SettingsAppState.ts @@ -0,0 +1,109 @@ +import AppSectionState, { + AppSectionDeleteState, + AppSectionItemSchemaState, + AppSectionItemState, + AppSectionSaveState, + PagedAppSectionState, +} from 'App/State/AppSectionState'; +import Language from 'Language/Language'; +import CustomFormat from 'typings/CustomFormat'; +import DownloadClient from 'typings/DownloadClient'; +import ImportList from 'typings/ImportList'; +import ImportListExclusion from 'typings/ImportListExclusion'; +import ImportListOptionsSettings from 'typings/ImportListOptionsSettings'; +import Indexer from 'typings/Indexer'; +import IndexerFlag from 'typings/IndexerFlag'; +import Notification from 'typings/Notification'; +import QualityProfile from 'typings/QualityProfile'; +import General from 'typings/Settings/General'; +import NamingConfig from 'typings/Settings/NamingConfig'; +import NamingExample from 'typings/Settings/NamingExample'; +import ReleaseProfile from 'typings/Settings/ReleaseProfile'; +import UiSettings from 'typings/Settings/UiSettings'; +import MetadataAppState from './MetadataAppState'; + +export interface DownloadClientAppState + extends AppSectionState, + AppSectionDeleteState, + AppSectionSaveState { + isTestingAll: boolean; +} + +export interface GeneralAppState + extends AppSectionItemState, + AppSectionSaveState {} + +export interface NamingAppState + extends AppSectionItemState, + AppSectionSaveState {} + +export type NamingExamplesAppState = AppSectionItemState; + +export interface ImportListAppState + extends AppSectionState, + AppSectionDeleteState, + AppSectionSaveState {} + +export interface IndexerAppState + extends AppSectionState, + AppSectionDeleteState, + AppSectionSaveState { + isTestingAll: boolean; +} + +export interface NotificationAppState + extends AppSectionState, + AppSectionDeleteState {} + +export interface QualityProfilesAppState + extends AppSectionState, + AppSectionItemSchemaState {} + +export interface ReleaseProfilesAppState + extends AppSectionState, + AppSectionSaveState { + pendingChanges: Partial; +} + +export interface CustomFormatAppState + extends AppSectionState, + AppSectionDeleteState, + AppSectionSaveState {} + +export interface ImportListOptionsSettingsAppState + extends AppSectionItemState, + AppSectionSaveState {} + +export interface ImportListExclusionsSettingsAppState + extends AppSectionState, + AppSectionSaveState, + PagedAppSectionState, + AppSectionDeleteState { + pendingChanges: Partial; +} + +export type IndexerFlagSettingsAppState = AppSectionState; +export type LanguageSettingsAppState = AppSectionState; +export type UiSettingsAppState = AppSectionItemState; + +interface SettingsAppState { + advancedSettings: boolean; + customFormats: CustomFormatAppState; + downloadClients: DownloadClientAppState; + general: GeneralAppState; + importListExclusions: ImportListExclusionsSettingsAppState; + importListOptions: ImportListOptionsSettingsAppState; + importLists: ImportListAppState; + indexerFlags: IndexerFlagSettingsAppState; + indexers: IndexerAppState; + languages: LanguageSettingsAppState; + metadata: MetadataAppState; + naming: NamingAppState; + namingExamples: NamingExamplesAppState; + notifications: NotificationAppState; + qualityProfiles: QualityProfilesAppState; + releaseProfiles: ReleaseProfilesAppState; + ui: UiSettingsAppState; +} + +export default SettingsAppState; diff --git a/frontend/src/App/State/SystemAppState.ts b/frontend/src/App/State/SystemAppState.ts new file mode 100644 index 000000000..1161f0e1e --- /dev/null +++ b/frontend/src/App/State/SystemAppState.ts @@ -0,0 +1,22 @@ +import DiskSpace from 'typings/DiskSpace'; +import Health from 'typings/Health'; +import SystemStatus from 'typings/SystemStatus'; +import Task from 'typings/Task'; +import Update from 'typings/Update'; +import AppSectionState, { AppSectionItemState } from './AppSectionState'; + +export type DiskSpaceAppState = AppSectionState; +export type HealthAppState = AppSectionState; +export type SystemStatusAppState = AppSectionItemState; +export type TaskAppState = AppSectionState; +export type UpdateAppState = AppSectionState; + +interface SystemAppState { + diskSpace: DiskSpaceAppState; + health: HealthAppState; + status: SystemStatusAppState; + tasks: TaskAppState; + updates: UpdateAppState; +} + +export default SystemAppState; diff --git a/frontend/src/App/State/TagsAppState.ts b/frontend/src/App/State/TagsAppState.ts new file mode 100644 index 000000000..914df9044 --- /dev/null +++ b/frontend/src/App/State/TagsAppState.ts @@ -0,0 +1,32 @@ +import ModelBase from 'App/ModelBase'; +import AppSectionState, { + AppSectionDeleteState, + AppSectionSaveState, +} from 'App/State/AppSectionState'; + +export interface Tag extends ModelBase { + label: string; +} + +export interface TagDetail extends ModelBase { + label: string; + autoTagIds: number[]; + delayProfileIds: number[]; + downloadClientIds: []; + importListIds: number[]; + indexerIds: number[]; + notificationIds: number[]; + restrictionIds: number[]; + seriesIds: number[]; +} + +export interface TagDetailAppState + extends AppSectionState, + AppSectionDeleteState, + AppSectionSaveState {} + +interface TagsAppState extends AppSectionState, AppSectionDeleteState { + details: TagDetailAppState; +} + +export default TagsAppState; diff --git a/frontend/src/App/State/WantedAppState.ts b/frontend/src/App/State/WantedAppState.ts new file mode 100644 index 000000000..b543d3879 --- /dev/null +++ b/frontend/src/App/State/WantedAppState.ts @@ -0,0 +1,13 @@ +import AppSectionState from 'App/State/AppSectionState'; +import Episode from 'Episode/Episode'; + +type WantedCutoffUnmetAppState = AppSectionState; + +type WantedMissingAppState = AppSectionState; + +interface WantedAppState { + cutoffUnmet: WantedCutoffUnmetAppState; + missing: WantedMissingAppState; +} + +export default WantedAppState; diff --git a/frontend/src/Calendar/Agenda/Agenda.css b/frontend/src/Calendar/Agenda/Agenda.css new file mode 100644 index 000000000..0304d9db5 --- /dev/null +++ b/frontend/src/Calendar/Agenda/Agenda.css @@ -0,0 +1,3 @@ +.agenda { + margin-top: 10px; +} diff --git a/frontend/src/Calendar/Agenda/Agenda.css.d.ts b/frontend/src/Calendar/Agenda/Agenda.css.d.ts new file mode 100644 index 000000000..44421cc99 --- /dev/null +++ b/frontend/src/Calendar/Agenda/Agenda.css.d.ts @@ -0,0 +1,7 @@ +// This file is automatically generated. +// Please do not change this file! +interface CssExports { + 'agenda': string; +} +export const cssExports: CssExports; +export default cssExports; diff --git a/frontend/src/Calendar/Agenda/Agenda.tsx b/frontend/src/Calendar/Agenda/Agenda.tsx new file mode 100644 index 000000000..fdef40466 --- /dev/null +++ b/frontend/src/Calendar/Agenda/Agenda.tsx @@ -0,0 +1,25 @@ +import moment from 'moment'; +import React from 'react'; +import { useSelector } from 'react-redux'; +import AppState from 'App/State/AppState'; +import AgendaEvent from './AgendaEvent'; +import styles from './Agenda.css'; + +function Agenda() { + const { items } = useSelector((state: AppState) => state.calendar); + + return ( +
+ {items.map((item, index) => { + const momentDate = moment(item.airDateUtc); + const showDate = + index === 0 || + !moment(items[index - 1].airDateUtc).isSame(momentDate, 'day'); + + return ; + })} +
+ ); +} + +export default Agenda; diff --git a/frontend/src/Calendar/Agenda/AgendaEvent.css b/frontend/src/Calendar/Agenda/AgendaEvent.css new file mode 100644 index 000000000..7ad9ccf6a --- /dev/null +++ b/frontend/src/Calendar/Agenda/AgendaEvent.css @@ -0,0 +1,138 @@ +.event { + position: relative; + padding: 5px; + border-bottom: 1px solid var(--borderColor); +} + +.underlay { + @add-mixin cover; + + &:hover { + background-color: var(--tableRowHoverBackgroundColor); + } +} + +.overlay { + @add-mixin linkOverlay; + + position: relative; + display: flex; + overflow-x: hidden; + font-size: $defaultFontSize; + + &:global(.colorImpaired) { + border-left-width: 5px; + } +} + +.eventWrapper { + display: flex; + flex: 1 0 1px; + overflow-x: hidden; + padding-left: 6px; + border-left-width: 4px; + border-left-style: solid; +} + +.date { + flex: 0 0 250px; + font-weight: bold; +} + +.time { + flex: 0 0 125px; + margin-right: 10px; + border: none !important; +} + +.seriesTitle, +.episodeTitle { + @add-mixin truncate; + + flex: 0 1 300px; + margin-right: 10px; +} + +.episodeTitle { + flex: 1 1 1px; +} + +.seasonEpisodeNumber { + flex: 0 0 100px; +} + +.episodeSeparator { + display: none; +} + +.absoluteEpisodeNumber { + margin-left: 3px; +} + +.statusIcon { + margin-left: 3px; + cursor: default; + pointer-events: all; +} + +/* + * Status + */ + +.downloaded { + composes: downloaded from '~Calendar/Events/CalendarEvent.css'; +} + +.downloading { + composes: downloading from '~Calendar/Events/CalendarEvent.css'; +} + +.unmonitored { + composes: unmonitored from '~Calendar/Events/CalendarEvent.css'; +} + +.onAir { + composes: onAir from '~Calendar/Events/CalendarEvent.css'; +} + +.missing { + composes: missing from '~Calendar/Events/CalendarEvent.css'; +} + +.premiere { + composes: premiere from '~Calendar/Events/CalendarEvent.css'; +} + +.unaired { + composes: unaired from '~Calendar/Events/CalendarEvent.css'; +} + +@media only screen and (max-width: $breakpointSmall) { + .overlay { + flex-direction: column; + } + + .eventWrapper { + display: block; + flex: 0 0 auto; + } + + .date { + margin-left: 10px; + } + + .date, + .time, + .seriesTitle { + flex: 0 0 100%; + } + + .seasonEpisodeNumber { + flex: 0 0 auto; + } + + .episodeSeparator { + display: inline-block; + margin: 0 5px; + } +} diff --git a/frontend/src/Calendar/Agenda/AgendaEvent.css.d.ts b/frontend/src/Calendar/Agenda/AgendaEvent.css.d.ts new file mode 100644 index 000000000..288e11824 --- /dev/null +++ b/frontend/src/Calendar/Agenda/AgendaEvent.css.d.ts @@ -0,0 +1,25 @@ +// This file is automatically generated. +// Please do not change this file! +interface CssExports { + 'absoluteEpisodeNumber': string; + 'date': string; + 'downloaded': string; + 'downloading': string; + 'episodeSeparator': string; + 'episodeTitle': string; + 'event': string; + 'eventWrapper': string; + 'missing': string; + 'onAir': string; + 'overlay': string; + 'premiere': string; + 'seasonEpisodeNumber': string; + 'seriesTitle': string; + 'statusIcon': string; + 'time': string; + 'unaired': string; + 'underlay': string; + 'unmonitored': string; +} +export const cssExports: CssExports; +export default cssExports; diff --git a/frontend/src/Calendar/Agenda/AgendaEvent.tsx b/frontend/src/Calendar/Agenda/AgendaEvent.tsx new file mode 100644 index 000000000..2fd2d7c54 --- /dev/null +++ b/frontend/src/Calendar/Agenda/AgendaEvent.tsx @@ -0,0 +1,227 @@ +import classNames from 'classnames'; +import moment from 'moment'; +import React, { useCallback, useState } from 'react'; +import { useSelector } from 'react-redux'; +import AppState from 'App/State/AppState'; +import CalendarEventQueueDetails from 'Calendar/Events/CalendarEventQueueDetails'; +import getStatusStyle from 'Calendar/getStatusStyle'; +import Icon from 'Components/Icon'; +import Link from 'Components/Link/Link'; +import EpisodeDetailsModal from 'Episode/EpisodeDetailsModal'; +import episodeEntities from 'Episode/episodeEntities'; +import getFinaleTypeName from 'Episode/getFinaleTypeName'; +import useEpisodeFile from 'EpisodeFile/useEpisodeFile'; +import { icons, kinds } from 'Helpers/Props'; +import useSeries from 'Series/useSeries'; +import { createQueueItemSelectorForHook } from 'Store/Selectors/createQueueItemSelector'; +import createUISettingsSelector from 'Store/Selectors/createUISettingsSelector'; +import formatTime from 'Utilities/Date/formatTime'; +import padNumber from 'Utilities/Number/padNumber'; +import translate from 'Utilities/String/translate'; +import styles from './AgendaEvent.css'; + +interface AgendaEventProps { + id: number; + seriesId: number; + episodeFileId: number; + title: string; + seasonNumber: number; + episodeNumber: number; + absoluteEpisodeNumber?: number; + airDateUtc: string; + monitored: boolean; + unverifiedSceneNumbering?: boolean; + finaleType?: string; + hasFile: boolean; + grabbed?: boolean; + showDate: boolean; +} + +function AgendaEvent(props: AgendaEventProps) { + const { + id, + seriesId, + episodeFileId, + title, + seasonNumber, + episodeNumber, + absoluteEpisodeNumber, + airDateUtc, + monitored, + unverifiedSceneNumbering, + finaleType, + hasFile, + grabbed, + showDate, + } = props; + + const series = useSeries(seriesId)!; + const episodeFile = useEpisodeFile(episodeFileId); + const queueItem = useSelector(createQueueItemSelectorForHook(id)); + const { timeFormat, longDateFormat, enableColorImpairedMode } = useSelector( + createUISettingsSelector() + ); + + const { + showEpisodeInformation, + showFinaleIcon, + showSpecialIcon, + showCutoffUnmetIcon, + } = useSelector((state: AppState) => state.calendar.options); + + const [isDetailsModalOpen, setIsDetailsModalOpen] = useState(false); + + const startTime = moment(airDateUtc); + const endTime = moment(airDateUtc).add(series.runtime, 'minutes'); + const downloading = !!(queueItem || grabbed); + const isMonitored = series.monitored && monitored; + const statusStyle = getStatusStyle( + hasFile, + downloading, + startTime, + endTime, + isMonitored + ); + const missingAbsoluteNumber = + series.seriesType === 'anime' && seasonNumber > 0 && !absoluteEpisodeNumber; + + const handlePress = useCallback(() => { + setIsDetailsModalOpen(true); + }, []); + + const handleDetailsModalClose = useCallback(() => { + setIsDetailsModalOpen(false); + }, []); + + return ( +
+ + +
+
+ {showDate && startTime.format(longDateFormat)} +
+ +
+
+ {formatTime(airDateUtc, timeFormat)} -{' '} + {formatTime(endTime.toISOString(), timeFormat, { + includeMinuteZero: true, + })} +
+ +
{series.title}
+ + {showEpisodeInformation ? ( +
+ {seasonNumber}x{padNumber(episodeNumber, 2)} + {series.seriesType === 'anime' && absoluteEpisodeNumber && ( + + ({absoluteEpisodeNumber}) + + )} +
-
+
+ ) : null} + +
+ {showEpisodeInformation ? title : null} +
+ + {missingAbsoluteNumber ? ( + + ) : null} + + {unverifiedSceneNumbering && !missingAbsoluteNumber ? ( + + ) : null} + + {queueItem ? ( + + + + ) : null} + + {!queueItem && grabbed ? ( + + ) : null} + + {showCutoffUnmetIcon && + episodeFile && + episodeFile.qualityCutoffNotMet ? ( + + ) : null} + + {episodeNumber === 1 && seasonNumber > 0 && ( + + )} + + {showFinaleIcon && finaleType ? ( + + ) : null} + + {showSpecialIcon && (episodeNumber === 0 || seasonNumber === 0) ? ( + + ) : null} +
+
+ + +
+ ); +} + +export default AgendaEvent; diff --git a/frontend/src/Calendar/Calendar.css b/frontend/src/Calendar/Calendar.css new file mode 100644 index 000000000..37e6ff618 --- /dev/null +++ b/frontend/src/Calendar/Calendar.css @@ -0,0 +1,8 @@ +.calendar { + flex-grow: 1; + width: 100%; +} + +.calendarContent { + width: 100%; +} diff --git a/frontend/src/Calendar/Calendar.css.d.ts b/frontend/src/Calendar/Calendar.css.d.ts new file mode 100644 index 000000000..503034402 --- /dev/null +++ b/frontend/src/Calendar/Calendar.css.d.ts @@ -0,0 +1,8 @@ +// This file is automatically generated. +// Please do not change this file! +interface CssExports { + 'calendar': string; + 'calendarContent': string; +} +export const cssExports: CssExports; +export default cssExports; diff --git a/frontend/src/Calendar/Calendar.tsx b/frontend/src/Calendar/Calendar.tsx new file mode 100644 index 000000000..caa337cf0 --- /dev/null +++ b/frontend/src/Calendar/Calendar.tsx @@ -0,0 +1,170 @@ +import React, { useCallback, useEffect, useRef } from 'react'; +import { useDispatch, useSelector } from 'react-redux'; +import AppState from 'App/State/AppState'; +import * as commandNames from 'Commands/commandNames'; +import Alert from 'Components/Alert'; +import LoadingIndicator from 'Components/Loading/LoadingIndicator'; +import Episode from 'Episode/Episode'; +import useCurrentPage from 'Helpers/Hooks/useCurrentPage'; +import usePrevious from 'Helpers/Hooks/usePrevious'; +import { kinds } from 'Helpers/Props'; +import { + clearCalendar, + fetchCalendar, + gotoCalendarToday, +} from 'Store/Actions/calendarActions'; +import { + clearEpisodeFiles, + fetchEpisodeFiles, +} from 'Store/Actions/episodeFileActions'; +import { + clearQueueDetails, + fetchQueueDetails, +} from 'Store/Actions/queueActions'; +import createCommandExecutingSelector from 'Store/Selectors/createCommandExecutingSelector'; +import hasDifferentItems from 'Utilities/Object/hasDifferentItems'; +import selectUniqueIds from 'Utilities/Object/selectUniqueIds'; +import { + registerPagePopulator, + unregisterPagePopulator, +} from 'Utilities/pagePopulator'; +import translate from 'Utilities/String/translate'; +import Agenda from './Agenda/Agenda'; +import CalendarDays from './Day/CalendarDays'; +import DaysOfWeek from './Day/DaysOfWeek'; +import CalendarHeader from './Header/CalendarHeader'; +import styles from './Calendar.css'; + +const UPDATE_DELAY = 3600000; // 1 hour + +function Calendar() { + const dispatch = useDispatch(); + const requestCurrentPage = useCurrentPage(); + const updateTimeout = useRef>(); + + const { isFetching, isPopulated, error, items, time, view } = useSelector( + (state: AppState) => state.calendar + ); + + const isRefreshingSeries = useSelector( + createCommandExecutingSelector(commandNames.REFRESH_SERIES) + ); + + const firstDayOfWeek = useSelector( + (state: AppState) => state.settings.ui.item.firstDayOfWeek + ); + + const wasRefreshingSeries = usePrevious(isRefreshingSeries); + const previousFirstDayOfWeek = usePrevious(firstDayOfWeek); + const previousItems = usePrevious(items); + + const handleScheduleUpdate = useCallback(() => { + clearTimeout(updateTimeout.current); + + function updateCalendar() { + dispatch(gotoCalendarToday()); + updateTimeout.current = setTimeout(updateCalendar, UPDATE_DELAY); + } + + updateTimeout.current = setTimeout(updateCalendar, UPDATE_DELAY); + }, [dispatch]); + + useEffect(() => { + handleScheduleUpdate(); + + return () => { + dispatch(clearCalendar()); + dispatch(clearQueueDetails()); + dispatch(clearEpisodeFiles()); + clearTimeout(updateTimeout.current); + }; + }, [dispatch, handleScheduleUpdate]); + + useEffect(() => { + if (requestCurrentPage) { + dispatch(fetchCalendar()); + } else { + dispatch(gotoCalendarToday()); + } + }, [requestCurrentPage, dispatch]); + + useEffect(() => { + const repopulate = () => { + dispatch(fetchQueueDetails({ time, view })); + dispatch(fetchCalendar({ time, view })); + }; + + registerPagePopulator(repopulate, [ + 'episodeFileUpdated', + 'episodeFileDeleted', + ]); + + return () => { + unregisterPagePopulator(repopulate); + }; + }, [time, view, dispatch]); + + useEffect(() => { + handleScheduleUpdate(); + }, [time, handleScheduleUpdate]); + + useEffect(() => { + if ( + previousFirstDayOfWeek != null && + firstDayOfWeek !== previousFirstDayOfWeek + ) { + dispatch(fetchCalendar({ time, view })); + } + }, [time, view, firstDayOfWeek, previousFirstDayOfWeek, dispatch]); + + useEffect(() => { + if (wasRefreshingSeries && !isRefreshingSeries) { + dispatch(fetchCalendar({ time, view })); + } + }, [time, view, isRefreshingSeries, wasRefreshingSeries, dispatch]); + + useEffect(() => { + if (!previousItems || hasDifferentItems(items, previousItems)) { + const episodeIds = selectUniqueIds(items, 'id'); + const episodeFileIds = selectUniqueIds( + items, + 'episodeFileId' + ); + + if (items.length) { + dispatch(fetchQueueDetails({ episodeIds })); + } + + if (episodeFileIds.length) { + dispatch(fetchEpisodeFiles({ episodeFileIds })); + } + } + }, [items, previousItems, dispatch]); + + return ( +
+ {isFetching && !isPopulated ? : null} + + {!isFetching && error ? ( + {translate('CalendarLoadError')} + ) : null} + + {!error && isPopulated && view === 'agenda' ? ( +
+ + +
+ ) : null} + + {!error && isPopulated && view !== 'agenda' ? ( +
+ + + +
+ ) : null} +
+ ); +} + +export default Calendar; diff --git a/frontend/src/Calendar/CalendarFilterModal.tsx b/frontend/src/Calendar/CalendarFilterModal.tsx new file mode 100644 index 000000000..e26b2928b --- /dev/null +++ b/frontend/src/Calendar/CalendarFilterModal.tsx @@ -0,0 +1,54 @@ +import React, { useCallback } from 'react'; +import { useDispatch, useSelector } from 'react-redux'; +import { createSelector } from 'reselect'; +import AppState from 'App/State/AppState'; +import FilterModal from 'Components/Filter/FilterModal'; +import { setCalendarFilter } from 'Store/Actions/calendarActions'; + +function createCalendarSelector() { + return createSelector( + (state: AppState) => state.calendar.items, + (calendar) => { + return calendar; + } + ); +} + +function createFilterBuilderPropsSelector() { + return createSelector( + (state: AppState) => state.calendar.filterBuilderProps, + (filterBuilderProps) => { + return filterBuilderProps; + } + ); +} + +interface CalendarFilterModalProps { + isOpen: boolean; +} + +export default function CalendarFilterModal(props: CalendarFilterModalProps) { + const sectionItems = useSelector(createCalendarSelector()); + const filterBuilderProps = useSelector(createFilterBuilderPropsSelector()); + const customFilterType = 'calendar'; + + const dispatch = useDispatch(); + + const dispatchSetFilter = useCallback( + (payload: unknown) => { + dispatch(setCalendarFilter(payload)); + }, + [dispatch] + ); + + return ( + + ); +} diff --git a/frontend/src/Calendar/CalendarPage.css b/frontend/src/Calendar/CalendarPage.css new file mode 100644 index 000000000..90ba5c505 --- /dev/null +++ b/frontend/src/Calendar/CalendarPage.css @@ -0,0 +1,14 @@ +.calendarPageBody { + composes: contentBody from '~Components/Page/PageContentBody.css'; + + display: flex; +} + +.calendarInnerPageBody { + composes: innerContentBody from '~Components/Page/PageContentBody.css'; + + display: flex; + flex-direction: column; + flex-grow: 1; + width: 100%; +} diff --git a/frontend/src/Calendar/CalendarPage.css.d.ts b/frontend/src/Calendar/CalendarPage.css.d.ts new file mode 100644 index 000000000..30befba55 --- /dev/null +++ b/frontend/src/Calendar/CalendarPage.css.d.ts @@ -0,0 +1,8 @@ +// This file is automatically generated. +// Please do not change this file! +interface CssExports { + 'calendarInnerPageBody': string; + 'calendarPageBody': string; +} +export const cssExports: CssExports; +export default cssExports; diff --git a/frontend/src/Calendar/CalendarPage.tsx b/frontend/src/Calendar/CalendarPage.tsx new file mode 100644 index 000000000..f408b6a60 --- /dev/null +++ b/frontend/src/Calendar/CalendarPage.tsx @@ -0,0 +1,226 @@ +import moment from 'moment'; +import React, { useCallback, useState } from 'react'; +import { useDispatch, useSelector } from 'react-redux'; +import { createSelector } from 'reselect'; +import AppState from 'App/State/AppState'; +import * as commandNames from 'Commands/commandNames'; +import Measure from 'Components/Measure'; +import FilterMenu from 'Components/Menu/FilterMenu'; +import PageContent from 'Components/Page/PageContent'; +import PageContentBody from 'Components/Page/PageContentBody'; +import PageToolbar from 'Components/Page/Toolbar/PageToolbar'; +import PageToolbarButton from 'Components/Page/Toolbar/PageToolbarButton'; +import PageToolbarSection from 'Components/Page/Toolbar/PageToolbarSection'; +import PageToolbarSeparator from 'Components/Page/Toolbar/PageToolbarSeparator'; +import { align, icons } from 'Helpers/Props'; +import NoSeries from 'Series/NoSeries'; +import { + searchMissing, + setCalendarDaysCount, + setCalendarFilter, +} from 'Store/Actions/calendarActions'; +import { executeCommand } from 'Store/Actions/commandActions'; +import { createCustomFiltersSelector } from 'Store/Selectors/createClientSideCollectionSelector'; +import createCommandExecutingSelector from 'Store/Selectors/createCommandExecutingSelector'; +import createCommandsSelector from 'Store/Selectors/createCommandsSelector'; +import createSeriesCountSelector from 'Store/Selectors/createSeriesCountSelector'; +import { isCommandExecuting } from 'Utilities/Command'; +import isBefore from 'Utilities/Date/isBefore'; +import translate from 'Utilities/String/translate'; +import Calendar from './Calendar'; +import CalendarFilterModal from './CalendarFilterModal'; +import CalendarLinkModal from './iCal/CalendarLinkModal'; +import Legend from './Legend/Legend'; +import CalendarOptionsModal from './Options/CalendarOptionsModal'; +import styles from './CalendarPage.css'; + +const MINIMUM_DAY_WIDTH = 120; + +function createMissingEpisodeIdsSelector() { + return createSelector( + (state: AppState) => state.calendar.start, + (state: AppState) => state.calendar.end, + (state: AppState) => state.calendar.items, + (state: AppState) => state.queue.details.items, + (start, end, episodes, queueDetails) => { + return episodes.reduce((acc, episode) => { + const airDateUtc = episode.airDateUtc; + + if ( + !episode.episodeFileId && + moment(airDateUtc).isAfter(start) && + moment(airDateUtc).isBefore(end) && + isBefore(episode.airDateUtc) && + !queueDetails.some( + (details) => !!details.episode && details.episode.id === episode.id + ) + ) { + acc.push(episode.id); + } + + return acc; + }, []); + } + ); +} + +function createIsSearchingSelector() { + return createSelector( + (state: AppState) => state.calendar.searchMissingCommandId, + createCommandsSelector(), + (searchMissingCommandId, commands) => { + if (searchMissingCommandId == null) { + return false; + } + + return isCommandExecuting( + commands.find((command) => { + return command.id === searchMissingCommandId; + }) + ); + } + ); +} + +function CalendarPage() { + const dispatch = useDispatch(); + + const { selectedFilterKey, filters } = useSelector( + (state: AppState) => state.calendar + ); + const missingEpisodeIds = useSelector(createMissingEpisodeIdsSelector()); + const isSearchingForMissing = useSelector(createIsSearchingSelector()); + const isRssSyncExecuting = useSelector( + createCommandExecutingSelector(commandNames.RSS_SYNC) + ); + const customFilters = useSelector(createCustomFiltersSelector('calendar')); + const hasSeries = !!useSelector(createSeriesCountSelector()); + + const [isCalendarLinkModalOpen, setIsCalendarLinkModalOpen] = useState(false); + const [isOptionsModalOpen, setIsOptionsModalOpen] = useState(false); + const [width, setWidth] = useState(0); + + const isMeasured = width > 0; + const PageComponent = hasSeries ? Calendar : NoSeries; + + const handleMeasure = useCallback( + ({ width: newWidth }: { width: number }) => { + setWidth(newWidth); + + const dayCount = Math.max( + 3, + Math.min(7, Math.floor(newWidth / MINIMUM_DAY_WIDTH)) + ); + + dispatch(setCalendarDaysCount({ dayCount })); + }, + [dispatch] + ); + + const handleGetCalendarLinkPress = useCallback(() => { + setIsCalendarLinkModalOpen(true); + }, []); + + const handleGetCalendarLinkModalClose = useCallback(() => { + setIsCalendarLinkModalOpen(false); + }, []); + + const handleOptionsPress = useCallback(() => { + setIsOptionsModalOpen(true); + }, []); + + const handleOptionsModalClose = useCallback(() => { + setIsOptionsModalOpen(false); + }, []); + + const handleRssSyncPress = useCallback(() => { + dispatch( + executeCommand({ + name: commandNames.RSS_SYNC, + }) + ); + }, [dispatch]); + + const handleSearchMissingPress = useCallback(() => { + dispatch(searchMissing({ episodeIds: missingEpisodeIds })); + }, [missingEpisodeIds, dispatch]); + + const handleFilterSelect = useCallback( + (key: string) => { + dispatch(setCalendarFilter({ selectedFilterKey: key })); + }, + [dispatch] + ); + + return ( + + + + + + + + + + + + + + + + + + + + + + {isMeasured ? :
} + + + {hasSeries && } + + + + + + + ); +} + +export default CalendarPage; diff --git a/frontend/src/Calendar/Day/CalendarDay.css b/frontend/src/Calendar/Day/CalendarDay.css new file mode 100644 index 000000000..22d1b1ccf --- /dev/null +++ b/frontend/src/Calendar/Day/CalendarDay.css @@ -0,0 +1,25 @@ +.day { + flex: 1 0 14.28%; + overflow: hidden; + min-height: 70px; + border-bottom: 1px solid var(--calendarBorderColor); + border-left: 1px solid var(--calendarBorderColor); +} + +.isSingleDay { + width: 100%; +} + +.dayOfMonth { + padding-right: 5px; + border-bottom: 1px solid var(--calendarBorderColor); + text-align: right; +} + +.isToday { + background-color: var(--calendarTodayBackgroundColor); +} + +.isDifferentMonth { + color: var(--disabledColor); +} diff --git a/frontend/src/Calendar/Day/CalendarDay.css.d.ts b/frontend/src/Calendar/Day/CalendarDay.css.d.ts new file mode 100644 index 000000000..f32def3dd --- /dev/null +++ b/frontend/src/Calendar/Day/CalendarDay.css.d.ts @@ -0,0 +1,11 @@ +// This file is automatically generated. +// Please do not change this file! +interface CssExports { + 'day': string; + 'dayOfMonth': string; + 'isDifferentMonth': string; + 'isSingleDay': string; + 'isToday': string; +} +export const cssExports: CssExports; +export default cssExports; diff --git a/frontend/src/Calendar/Day/CalendarDay.tsx b/frontend/src/Calendar/Day/CalendarDay.tsx new file mode 100644 index 000000000..a619109ca --- /dev/null +++ b/frontend/src/Calendar/Day/CalendarDay.tsx @@ -0,0 +1,159 @@ +import classNames from 'classnames'; +import moment from 'moment'; +import React from 'react'; +import { useSelector } from 'react-redux'; +import { createSelector } from 'reselect'; +import AppState from 'App/State/AppState'; +import * as calendarViews from 'Calendar/calendarViews'; +import CalendarEvent from 'Calendar/Events/CalendarEvent'; +import CalendarEventGroup from 'Calendar/Events/CalendarEventGroup'; +import { + CalendarEvent as CalendarEventModel, + CalendarEventGroup as CalendarEventGroupModel, + CalendarItem, +} from 'typings/Calendar'; +import styles from './CalendarDay.css'; + +function sort(items: (CalendarEventModel | CalendarEventGroupModel)[]) { + return items.sort((a, b) => { + const aDate = a.isGroup + ? moment(a.events[0].airDateUtc).unix() + : moment(a.airDateUtc).unix(); + + const bDate = b.isGroup + ? moment(b.events[0].airDateUtc).unix() + : moment(b.airDateUtc).unix(); + + return aDate - bDate; + }); +} + +function createCalendarEventsConnector(date: string) { + return createSelector( + (state: AppState) => state.calendar.items, + (state: AppState) => state.calendar.options.collapseMultipleEpisodes, + (items, collapseMultipleEpisodes) => { + const momentDate = moment(date); + + const filtered = items.filter((item) => { + return momentDate.isSame(moment(item.airDateUtc), 'day'); + }); + + if (!collapseMultipleEpisodes) { + return sort( + filtered.map((item) => ({ + isGroup: false, + ...item, + })) + ); + } + + const groupedObject = Object.groupBy( + filtered, + (item: CalendarItem) => `${item.seriesId}-${item.seasonNumber}` + ); + + const grouped = Object.entries(groupedObject).reduce< + (CalendarEventModel | CalendarEventGroupModel)[] + >((acc, [, events]) => { + if (!events) { + return acc; + } + + if (events.length === 1) { + acc.push({ + isGroup: false, + ...events[0], + }); + } else { + acc.push({ + isGroup: true, + seriesId: events[0].seriesId, + seasonNumber: events[0].seasonNumber, + episodeIds: events.map((event) => event.id), + events: events.sort( + (a, b) => + moment(a.airDateUtc).unix() - moment(b.airDateUtc).unix() + ), + }); + } + + return acc; + }, []); + + return sort(grouped); + } + ); +} + +interface CalendarDayProps { + date: string; + isTodaysDate: boolean; + onEventModalOpenToggle(isOpen: boolean): unknown; +} + +function CalendarDay({ + date, + isTodaysDate, + onEventModalOpenToggle, +}: CalendarDayProps) { + const { time, view } = useSelector((state: AppState) => state.calendar); + const events = useSelector(createCalendarEventsConnector(date)); + + const ref = React.useRef(null); + + React.useEffect(() => { + if (isTodaysDate && view === calendarViews.MONTH && ref.current) { + ref.current.scrollIntoView(); + } + }, [time, isTodaysDate, view]); + + return ( +
+ {view === calendarViews.MONTH && ( +
+ {moment(date).date()} +
+ )} +
+ {events.map((event) => { + if (event.isGroup) { + return ( + + ); + } + + return ( + + ); + })} +
+
+ ); +} + +export default CalendarDay; diff --git a/frontend/src/Calendar/Day/CalendarDays.css b/frontend/src/Calendar/Day/CalendarDays.css new file mode 100644 index 000000000..507dd0ede --- /dev/null +++ b/frontend/src/Calendar/Day/CalendarDays.css @@ -0,0 +1,14 @@ +.days { + display: flex; + border-right: 1px solid var(--calendarBorderColor); +} + +.day, +.week, +.forecast { + flex-wrap: nowrap; +} + +.month { + flex-wrap: wrap; +} diff --git a/frontend/src/Calendar/Day/CalendarDays.css.d.ts b/frontend/src/Calendar/Day/CalendarDays.css.d.ts new file mode 100644 index 000000000..ae3e7aebc --- /dev/null +++ b/frontend/src/Calendar/Day/CalendarDays.css.d.ts @@ -0,0 +1,11 @@ +// This file is automatically generated. +// Please do not change this file! +interface CssExports { + 'day': string; + 'days': string; + 'forecast': string; + 'month': string; + 'week': string; +} +export const cssExports: CssExports; +export default cssExports; diff --git a/frontend/src/Calendar/Day/CalendarDays.tsx b/frontend/src/Calendar/Day/CalendarDays.tsx new file mode 100644 index 000000000..149dc1455 --- /dev/null +++ b/frontend/src/Calendar/Day/CalendarDays.tsx @@ -0,0 +1,135 @@ +import classNames from 'classnames'; +import moment from 'moment'; +import React, { useCallback, useEffect, useRef, useState } from 'react'; +import { useDispatch, useSelector } from 'react-redux'; +import AppState from 'App/State/AppState'; +import * as calendarViews from 'Calendar/calendarViews'; +import { + gotoCalendarNextRange, + gotoCalendarPreviousRange, +} from 'Store/Actions/calendarActions'; +import CalendarDay from './CalendarDay'; +import styles from './CalendarDays.css'; + +function CalendarDays() { + const dispatch = useDispatch(); + const { dates, view } = useSelector((state: AppState) => state.calendar); + const isSidebarVisible = useSelector( + (state: AppState) => state.app.isSidebarVisible + ); + + const updateTimeout = useRef>(); + const touchStart = useRef(null); + const isEventModalOpen = useRef(false); + const [todaysDate, setTodaysDate] = useState( + moment().startOf('day').toISOString() + ); + + const handleEventModalOpenToggle = useCallback((isOpen: boolean) => { + isEventModalOpen.current = isOpen; + }, []); + + const scheduleUpdate = useCallback(() => { + clearTimeout(updateTimeout.current); + + const todaysDate = moment().startOf('day'); + const diff = moment().diff(todaysDate.clone().add(1, 'day')); + + setTodaysDate(todaysDate.toISOString()); + + updateTimeout.current = setTimeout(scheduleUpdate, diff); + }, []); + + const handleTouchStart = useCallback( + (event: TouchEvent) => { + const touches = event.touches; + const currentTouch = touches[0].pageX; + + if (touches.length !== 1) { + return; + } + + if (currentTouch < 50 || isSidebarVisible || isEventModalOpen.current) { + return; + } + + touchStart.current = currentTouch; + }, + [isSidebarVisible] + ); + + const handleTouchEnd = useCallback( + (event: TouchEvent) => { + const touches = event.changedTouches; + const currentTouch = touches[0].pageX; + + if (!touchStart.current) { + return; + } + + if ( + currentTouch > touchStart.current && + currentTouch - touchStart.current > 100 + ) { + dispatch(gotoCalendarPreviousRange()); + } else if ( + currentTouch < touchStart.current && + touchStart.current - currentTouch > 100 + ) { + dispatch(gotoCalendarNextRange()); + } + + touchStart.current = null; + }, + [dispatch] + ); + + const handleTouchCancel = useCallback(() => { + touchStart.current = null; + }, []); + + const handleTouchMove = useCallback(() => { + if (!touchStart.current) { + return; + } + }, []); + + useEffect(() => { + if (view === calendarViews.MONTH) { + scheduleUpdate(); + } + }, [view, scheduleUpdate]); + + useEffect(() => { + window.addEventListener('touchstart', handleTouchStart); + window.addEventListener('touchend', handleTouchEnd); + window.addEventListener('touchcancel', handleTouchCancel); + window.addEventListener('touchmove', handleTouchMove); + + return () => { + window.removeEventListener('touchstart', handleTouchStart); + window.removeEventListener('touchend', handleTouchEnd); + window.removeEventListener('touchcancel', handleTouchCancel); + window.removeEventListener('touchmove', handleTouchMove); + }; + }, [handleTouchStart, handleTouchEnd, handleTouchCancel, handleTouchMove]); + + return ( +
+ {dates.map((date) => { + return ( + + ); + })} +
+ ); +} + +export default CalendarDays; diff --git a/frontend/src/Calendar/Day/DayOfWeek.css b/frontend/src/Calendar/Day/DayOfWeek.css new file mode 100644 index 000000000..2d31a30be --- /dev/null +++ b/frontend/src/Calendar/Day/DayOfWeek.css @@ -0,0 +1,13 @@ +.dayOfWeek { + flex: 1 0 14.28%; + background-color: var(--calendarBackgroundColor); + text-align: center; +} + +.isSingleDay { + width: 100%; +} + +.isToday { + background-color: var(--calendarTodayBackgroundColor); +} diff --git a/frontend/src/Calendar/Day/DayOfWeek.css.d.ts b/frontend/src/Calendar/Day/DayOfWeek.css.d.ts new file mode 100644 index 000000000..a377e4a8e --- /dev/null +++ b/frontend/src/Calendar/Day/DayOfWeek.css.d.ts @@ -0,0 +1,9 @@ +// This file is automatically generated. +// Please do not change this file! +interface CssExports { + 'dayOfWeek': string; + 'isSingleDay': string; + 'isToday': string; +} +export const cssExports: CssExports; +export default cssExports; diff --git a/frontend/src/Calendar/Day/DayOfWeek.tsx b/frontend/src/Calendar/Day/DayOfWeek.tsx new file mode 100644 index 000000000..c8b493b7c --- /dev/null +++ b/frontend/src/Calendar/Day/DayOfWeek.tsx @@ -0,0 +1,54 @@ +import classNames from 'classnames'; +import moment from 'moment'; +import React from 'react'; +import * as calendarViews from 'Calendar/calendarViews'; +import getRelativeDate from 'Utilities/Date/getRelativeDate'; +import styles from './DayOfWeek.css'; + +interface DayOfWeekProps { + date: string; + view: string; + isTodaysDate: boolean; + calendarWeekColumnHeader: string; + shortDateFormat: string; + showRelativeDates: boolean; +} + +function DayOfWeek(props: DayOfWeekProps) { + const { + date, + view, + isTodaysDate, + calendarWeekColumnHeader, + shortDateFormat, + showRelativeDates, + } = props; + + const highlightToday = view !== calendarViews.MONTH && isTodaysDate; + const momentDate = moment(date); + let formatedDate = momentDate.format('dddd'); + + if (view === calendarViews.WEEK) { + formatedDate = momentDate.format(calendarWeekColumnHeader); + } else if (view === calendarViews.FORECAST) { + formatedDate = getRelativeDate({ + date, + shortDateFormat, + showRelativeDates, + }); + } + + return ( +
+ {formatedDate} +
+ ); +} + +export default DayOfWeek; diff --git a/frontend/src/Calendar/Day/DaysOfWeek.css b/frontend/src/Calendar/Day/DaysOfWeek.css new file mode 100644 index 000000000..518664633 --- /dev/null +++ b/frontend/src/Calendar/Day/DaysOfWeek.css @@ -0,0 +1,4 @@ +.daysOfWeek { + display: flex; + margin-top: 10px; +} diff --git a/frontend/src/Calendar/Day/DaysOfWeek.css.d.ts b/frontend/src/Calendar/Day/DaysOfWeek.css.d.ts new file mode 100644 index 000000000..5bc224b68 --- /dev/null +++ b/frontend/src/Calendar/Day/DaysOfWeek.css.d.ts @@ -0,0 +1,7 @@ +// This file is automatically generated. +// Please do not change this file! +interface CssExports { + 'daysOfWeek': string; +} +export const cssExports: CssExports; +export default cssExports; diff --git a/frontend/src/Calendar/Day/DaysOfWeek.tsx b/frontend/src/Calendar/Day/DaysOfWeek.tsx new file mode 100644 index 000000000..64bc886cc --- /dev/null +++ b/frontend/src/Calendar/Day/DaysOfWeek.tsx @@ -0,0 +1,60 @@ +import moment from 'moment'; +import React, { useCallback, useEffect, useRef, useState } from 'react'; +import { useSelector } from 'react-redux'; +import AppState from 'App/State/AppState'; +import * as calendarViews from 'Calendar/calendarViews'; +import createUISettingsSelector from 'Store/Selectors/createUISettingsSelector'; +import DayOfWeek from './DayOfWeek'; +import styles from './DaysOfWeek.css'; + +function DaysOfWeek() { + const { dates, view } = useSelector((state: AppState) => state.calendar); + const { calendarWeekColumnHeader, shortDateFormat, showRelativeDates } = + useSelector(createUISettingsSelector()); + + const updateTimeout = useRef>(); + const [todaysDate, setTodaysDate] = useState( + moment().startOf('day').toISOString() + ); + + const scheduleUpdate = useCallback(() => { + clearTimeout(updateTimeout.current); + + const todaysDate = moment().startOf('day'); + const diff = moment().diff(todaysDate.clone().add(1, 'day')); + + setTodaysDate(todaysDate.toISOString()); + + updateTimeout.current = setTimeout(scheduleUpdate, diff); + }, []); + + useEffect(() => { + if (view !== calendarViews.AGENDA && view !== calendarViews.MONTH) { + scheduleUpdate(); + } + }, [view, scheduleUpdate]); + + if (view === calendarViews.AGENDA) { + return null; + } + + return ( +
+ {dates.map((date) => { + return ( + + ); + })} +
+ ); +} + +export default DaysOfWeek; diff --git a/frontend/src/Calendar/Events/CalendarEvent.css b/frontend/src/Calendar/Events/CalendarEvent.css new file mode 100644 index 000000000..679b4cc51 --- /dev/null +++ b/frontend/src/Calendar/Events/CalendarEvent.css @@ -0,0 +1,158 @@ +$fullColorGradient: rgba(244, 245, 246, 0.2); + +.event { + position: relative; + margin: 4px 2px; + padding: 5px; + border-bottom: 1px solid var(--calendarBorderColor); + border-left: 4px solid var(--calendarBorderColor); +} + +.underlay { + @add-mixin cover; +} + +.overlay { + @add-mixin linkOverlay; + + position: relative; + overflow-x: hidden; + font-size: 12px; + + &:global(.colorImpaired) { + border-left-width: 5px; + } +} + +.info, +.episodeInfo { + display: flex; +} + +.episodeInfo { + color: var(--calendarTextDim); +} + +.seriesTitle, +.episodeTitle { + @add-mixin truncate; + flex: 1 0 1px; + margin-right: 10px; +} + +.seriesTitle { + color: var(--calendarTextDimAlternate); + font-size: $defaultFontSize; +} + +.absoluteEpisodeNumber { + margin-left: 3px; +} + +.statusContainer { + display: flex; + align-items: center; + + &:global(.fullColor) { + filter: var(--calendarFullColorFilter) + } +} + +.statusIcon { + margin-left: 3px; + cursor: default; + pointer-events: all; +} + +.airTime { + color: var(--calendarTextDim); +} + +/* + * Status + */ + +.downloaded { + border-left-color: var(--successColor) !important; + + &:global(.fullColor) { + background-color: rgba(39, 194, 76, 0.4) !important; + } + + &:global(.colorImpaired) { + border-left-color: color(#27c24c saturation(+15%)) !important; + } +} + +.downloading { + border-left-color: var(--purple) !important; + + &:global(.fullColor) { + background-color: rgba(122, 67, 182, 0.4) !important; + } +} + +.unmonitored { + border-left-color: var(--gray) !important; + + &:global(.fullColor) { + background-color: rgba(173, 173, 173, 0.5) !important; + } + + &:global(.colorImpaired) { + background: repeating-linear-gradient(45deg, var(--colorImpairedGradientDark), var(--colorImpairedGradientDark) 5px, var(--colorImpairedGradient) 5px, var(--colorImpairedGradient) 10px); + } + + &:global(.fullColor.colorImpaired) { + background: repeating-linear-gradient(45deg, $fullColorGradient, $fullColorGradient 5px, transparent 5px, transparent 10px); + } +} + +.onAir { + border-left-color: var(--warningColor) !important; + + &:global(.fullColor) { + background-color: rgba(255, 165, 0, 0.6) !important; + } + + &:global(.colorImpaired) { + background: repeating-linear-gradient(90deg, var(--colorImpairedGradientDark), var(--colorImpairedGradientDark) 5px, var(--colorImpairedGradient) 5px, var(--colorImpairedGradient) 10px); + } + + &:global(.fullColor.colorImpaired) { + background: repeating-linear-gradient(90deg, $fullColorGradient, $fullColorGradient 5px, transparent 5px, transparent 10px); + } +} + +.missing { + border-left-color: var(--dangerColor) !important; + + &:global(.fullColor) { + background-color: rgba(240, 80, 80, 0.6) !important; + } + + &:global(.colorImpaired) { + border-left-color: color(#f05050 saturation(+15%)) !important; + background: repeating-linear-gradient(90deg, var(--colorImpairedGradientDark), var(--colorImpairedGradientDark) 5px, var(--colorImpairedGradient) 5px, var(--colorImpairedGradient) 10px); + } + + &:global(.fullColor.colorImpaired) { + background: repeating-linear-gradient(90deg, $fullColorGradient, $fullColorGradient 5px, transparent 5px, transparent 10px); + } +} + +.unaired { + border-left-color: var(--primaryColor) !important; + + &:global(.fullColor) { + background-color: rgba(93, 156, 236, 0.4) !important; + } + + &:global(.colorImpaired) { + background: repeating-linear-gradient(90deg, var(--colorImpairedGradientDark), var(--colorImpairedGradientDark) 5px, var(--colorImpairedGradient) 5px, var(--colorImpairedGradient) 10px); + } + + &:global(.fullColor.colorImpaired) { + background: repeating-linear-gradient(90deg, $fullColorGradient, $fullColorGradient 5px, transparent 5px, transparent 10px); + } +} diff --git a/frontend/src/Calendar/Events/CalendarEvent.css.d.ts b/frontend/src/Calendar/Events/CalendarEvent.css.d.ts new file mode 100644 index 000000000..f099df211 --- /dev/null +++ b/frontend/src/Calendar/Events/CalendarEvent.css.d.ts @@ -0,0 +1,23 @@ +// This file is automatically generated. +// Please do not change this file! +interface CssExports { + 'absoluteEpisodeNumber': string; + 'airTime': string; + 'downloaded': string; + 'downloading': string; + 'episodeInfo': string; + 'episodeTitle': string; + 'event': string; + 'info': string; + 'missing': string; + 'onAir': string; + 'overlay': string; + 'seriesTitle': string; + 'statusContainer': string; + 'statusIcon': string; + 'unaired': string; + 'underlay': string; + 'unmonitored': string; +} +export const cssExports: CssExports; +export default cssExports; diff --git a/frontend/src/Calendar/Events/CalendarEvent.tsx b/frontend/src/Calendar/Events/CalendarEvent.tsx new file mode 100644 index 000000000..079256a0e --- /dev/null +++ b/frontend/src/Calendar/Events/CalendarEvent.tsx @@ -0,0 +1,240 @@ +import classNames from 'classnames'; +import moment from 'moment'; +import React, { useCallback, useState } from 'react'; +import { useSelector } from 'react-redux'; +import AppState from 'App/State/AppState'; +import getStatusStyle from 'Calendar/getStatusStyle'; +import Icon from 'Components/Icon'; +import Link from 'Components/Link/Link'; +import EpisodeDetailsModal from 'Episode/EpisodeDetailsModal'; +import episodeEntities from 'Episode/episodeEntities'; +import getFinaleTypeName from 'Episode/getFinaleTypeName'; +import useEpisodeFile from 'EpisodeFile/useEpisodeFile'; +import { icons, kinds } from 'Helpers/Props'; +import useSeries from 'Series/useSeries'; +import { createQueueItemSelectorForHook } from 'Store/Selectors/createQueueItemSelector'; +import createUISettingsSelector from 'Store/Selectors/createUISettingsSelector'; +import formatTime from 'Utilities/Date/formatTime'; +import padNumber from 'Utilities/Number/padNumber'; +import translate from 'Utilities/String/translate'; +import CalendarEventQueueDetails from './CalendarEventQueueDetails'; +import styles from './CalendarEvent.css'; + +interface CalendarEventProps { + id: number; + episodeId: number; + seriesId: number; + episodeFileId?: number; + title: string; + seasonNumber: number; + episodeNumber: number; + absoluteEpisodeNumber?: number; + airDateUtc: string; + monitored: boolean; + unverifiedSceneNumbering?: boolean; + finaleType?: string; + hasFile: boolean; + grabbed?: boolean; + onEventModalOpenToggle: (isOpen: boolean) => void; +} + +function CalendarEvent(props: CalendarEventProps) { + const { + id, + seriesId, + episodeFileId, + title, + seasonNumber, + episodeNumber, + absoluteEpisodeNumber, + airDateUtc, + monitored, + unverifiedSceneNumbering, + finaleType, + hasFile, + grabbed, + onEventModalOpenToggle, + } = props; + + const series = useSeries(seriesId); + const episodeFile = useEpisodeFile(episodeFileId); + const queueItem = useSelector(createQueueItemSelectorForHook(id)); + + const { timeFormat, enableColorImpairedMode } = useSelector( + createUISettingsSelector() + ); + + const { + showEpisodeInformation, + showFinaleIcon, + showSpecialIcon, + showCutoffUnmetIcon, + fullColorEvents, + } = useSelector((state: AppState) => state.calendar.options); + + const [isDetailsModalOpen, setIsDetailsModalOpen] = useState(false); + + const handlePress = useCallback(() => { + setIsDetailsModalOpen(true); + onEventModalOpenToggle(true); + }, [onEventModalOpenToggle]); + + const handleDetailsModalClose = useCallback(() => { + setIsDetailsModalOpen(false); + onEventModalOpenToggle(false); + }, [onEventModalOpenToggle]); + + if (!series) { + return null; + } + + const startTime = moment(airDateUtc); + const endTime = moment(airDateUtc).add(series.runtime, 'minutes'); + const isDownloading = !!(queueItem || grabbed); + const isMonitored = series.monitored && monitored; + const statusStyle = getStatusStyle( + hasFile, + isDownloading, + startTime, + endTime, + isMonitored + ); + const missingAbsoluteNumber = + series.seriesType === 'anime' && seasonNumber > 0 && !absoluteEpisodeNumber; + + return ( +
+ + +
+
+
{series.title}
+ +
+ {missingAbsoluteNumber ? ( + + ) : null} + + {unverifiedSceneNumbering && !missingAbsoluteNumber ? ( + + ) : null} + + {queueItem ? ( + + + + ) : null} + + {!queueItem && grabbed ? ( + + ) : null} + + {showCutoffUnmetIcon && + !!episodeFile && + episodeFile.qualityCutoffNotMet ? ( + + ) : null} + + {episodeNumber === 1 && seasonNumber > 0 ? ( + + ) : null} + + {showFinaleIcon && finaleType ? ( + + ) : null} + + {showSpecialIcon && (episodeNumber === 0 || seasonNumber === 0) ? ( + + ) : null} +
+
+ + {showEpisodeInformation ? ( +
+
{title}
+ +
+ {seasonNumber}x{padNumber(episodeNumber, 2)} + {series.seriesType === 'anime' && absoluteEpisodeNumber ? ( + + ({absoluteEpisodeNumber}) + + ) : null} +
+
+ ) : null} + +
+ {formatTime(airDateUtc, timeFormat)} -{' '} + {formatTime(endTime.toISOString(), timeFormat, { + includeMinuteZero: true, + })} +
+
+ + +
+ ); +} + +export default CalendarEvent; diff --git a/frontend/src/Calendar/Events/CalendarEventGroup.css b/frontend/src/Calendar/Events/CalendarEventGroup.css new file mode 100644 index 000000000..990d994ec --- /dev/null +++ b/frontend/src/Calendar/Events/CalendarEventGroup.css @@ -0,0 +1,97 @@ +.eventGroup { + overflow-x: hidden; + margin: 4px 2px; + padding: 5px; + border-bottom: 1px solid var(--borderColor); + border-left: 4px solid var(--borderColor); + font-size: 12px; +} + +.info, +.airingInfo { + display: flex; +} + +.seriesTitle { + @add-mixin truncate; + flex: 1 0 1px; + margin-right: 10px; + color: var(--calendarTextDimAlternate); + font-size: $defaultFontSize; +} + +.airTime { + flex: 1 0 1px; + color: var(--calendarTextDim); +} + +.episodeInfo { + margin-left: 10px; + color: var(--calendarTextDim); +} + +.absoluteEpisodeNumber { + margin-left: 3px; +} + +.expandContainerInline { + display: flex; + justify-content: flex-end; + flex: 1 0 20px; +} + +.expandContainer, +.collapseContainer { + display: flex; + align-items: center; + justify-content: center; +} + +.collapseContainer { + margin-bottom: 5px; +} + +.statusContainer { + display: flex; + align-items: center; + + &:global(.fullColor) { + filter: var(--calendarFullColorFilter) + } +} + +.statusIcon { + margin-left: 3px; +} + +/* + * Status + */ + +.downloaded { + composes: downloaded from '~Calendar/Events/CalendarEvent.css'; +} + +.downloading { + composes: downloading from '~Calendar/Events/CalendarEvent.css'; +} + +.unmonitored { + composes: unmonitored from '~Calendar/Events/CalendarEvent.css'; +} + +.onAir { + composes: onAir from '~Calendar/Events/CalendarEvent.css'; +} + +.missing { + composes: missing from '~Calendar/Events/CalendarEvent.css'; +} + +.premiere { + composes: premiere from '~Calendar/Events/CalendarEvent.css'; +} + +.unaired { + composes: unaired from '~Calendar/Events/CalendarEvent.css'; +} diff --git a/frontend/src/Calendar/Events/CalendarEventGroup.css.d.ts b/frontend/src/Calendar/Events/CalendarEventGroup.css.d.ts new file mode 100644 index 000000000..c527feff1 --- /dev/null +++ b/frontend/src/Calendar/Events/CalendarEventGroup.css.d.ts @@ -0,0 +1,25 @@ +// This file is automatically generated. +// Please do not change this file! +interface CssExports { + 'absoluteEpisodeNumber': string; + 'airTime': string; + 'airingInfo': string; + 'collapseContainer': string; + 'downloaded': string; + 'downloading': string; + 'episodeInfo': string; + 'eventGroup': string; + 'expandContainer': string; + 'expandContainerInline': string; + 'info': string; + 'missing': string; + 'onAir': string; + 'premiere': string; + 'seriesTitle': string; + 'statusContainer': string; + 'statusIcon': string; + 'unaired': string; + 'unmonitored': string; +} +export const cssExports: CssExports; +export default cssExports; diff --git a/frontend/src/Calendar/Events/CalendarEventGroup.tsx b/frontend/src/Calendar/Events/CalendarEventGroup.tsx new file mode 100644 index 000000000..1ee981cfd --- /dev/null +++ b/frontend/src/Calendar/Events/CalendarEventGroup.tsx @@ -0,0 +1,253 @@ +import classNames from 'classnames'; +import moment from 'moment'; +import React, { useCallback, useMemo, useState } from 'react'; +import { useSelector } from 'react-redux'; +import { createSelector } from 'reselect'; +import AppState from 'App/State/AppState'; +import getStatusStyle from 'Calendar/getStatusStyle'; +import Icon from 'Components/Icon'; +import Link from 'Components/Link/Link'; +import getFinaleTypeName from 'Episode/getFinaleTypeName'; +import { icons, kinds } from 'Helpers/Props'; +import useSeries from 'Series/useSeries'; +import createUISettingsSelector from 'Store/Selectors/createUISettingsSelector'; +import { CalendarItem } from 'typings/Calendar'; +import formatTime from 'Utilities/Date/formatTime'; +import padNumber from 'Utilities/Number/padNumber'; +import translate from 'Utilities/String/translate'; +import CalendarEvent from './CalendarEvent'; +import styles from './CalendarEventGroup.css'; + +function createIsDownloadingSelector(episodeIds: number[]) { + return createSelector( + (state: AppState) => state.queue.details, + (details) => { + return details.items.some((item) => { + return !!(item.episodeId && episodeIds.includes(item.episodeId)); + }); + } + ); +} + +interface CalendarEventGroupProps { + episodeIds: number[]; + seriesId: number; + events: CalendarItem[]; + onEventModalOpenToggle: (isOpen: boolean) => void; +} + +function CalendarEventGroup({ + episodeIds, + seriesId, + events, + onEventModalOpenToggle, +}: CalendarEventGroupProps) { + const isDownloading = useSelector(createIsDownloadingSelector(episodeIds)); + const series = useSeries(seriesId)!; + + const { timeFormat, enableColorImpairedMode } = useSelector( + createUISettingsSelector() + ); + + const { showEpisodeInformation, showFinaleIcon, fullColorEvents } = + useSelector((state: AppState) => state.calendar.options); + + const [isExpanded, setIsExpanded] = useState(false); + + const firstEpisode = events[0]; + const lastEpisode = events[events.length - 1]; + const airDateUtc = firstEpisode.airDateUtc; + const startTime = moment(airDateUtc); + const endTime = moment(lastEpisode.airDateUtc).add(series.runtime, 'minutes'); + const seasonNumber = firstEpisode.seasonNumber; + + const { allDownloaded, anyQueued, anyMonitored, allAbsoluteEpisodeNumbers } = + useMemo(() => { + let files = 0; + let queued = 0; + let monitored = 0; + let absoluteEpisodeNumbers = 0; + + events.forEach((event) => { + if (event.episodeFileId) { + files++; + } + + if (event.queued) { + queued++; + } + + if (series.monitored && event.monitored) { + monitored++; + } + + if (event.absoluteEpisodeNumber) { + absoluteEpisodeNumbers++; + } + }); + + return { + allDownloaded: files === events.length, + anyQueued: queued > 0, + anyMonitored: monitored > 0, + allAbsoluteEpisodeNumbers: absoluteEpisodeNumbers === events.length, + }; + }, [series, events]); + + const anyDownloading = isDownloading || anyQueued; + + const statusStyle = getStatusStyle( + allDownloaded, + anyDownloading, + startTime, + endTime, + anyMonitored + ); + const isMissingAbsoluteNumber = + series.seriesType === 'anime' && + seasonNumber > 0 && + !allAbsoluteEpisodeNumbers; + + const handleExpandPress = useCallback(() => { + setIsExpanded((state) => !state); + }, []); + + if (isExpanded) { + return ( +
+ {events.map((event) => { + return ( + + ); + })} + + + + +
+ ); + } + + return ( +
+
+
{series.title}
+ +
+ {isMissingAbsoluteNumber ? ( + + ) : null} + + {anyDownloading ? ( + + ) : null} + + {firstEpisode.episodeNumber === 1 && seasonNumber > 0 ? ( + + ) : null} + + {showFinaleIcon && lastEpisode.finaleType ? ( + + ) : null} +
+
+ +
+
+ {formatTime(airDateUtc, timeFormat)} -{' '} + {formatTime(endTime.toISOString(), timeFormat, { + includeMinuteZero: true, + })} +
+ + {showEpisodeInformation ? ( +
+ {seasonNumber}x{padNumber(firstEpisode.episodeNumber, 2)}- + {padNumber(lastEpisode.episodeNumber, 2)} + {series.seriesType === 'anime' && + firstEpisode.absoluteEpisodeNumber && + lastEpisode.absoluteEpisodeNumber ? ( + + ({firstEpisode.absoluteEpisodeNumber}- + {lastEpisode.absoluteEpisodeNumber}) + + ) : null} +
+ ) : ( + + + + )} +
+ + {showEpisodeInformation ? ( + +   + +   + + ) : null} +
+ ); +} + +export default CalendarEventGroup; diff --git a/frontend/src/Calendar/Events/CalendarEventQueueDetails.tsx b/frontend/src/Calendar/Events/CalendarEventQueueDetails.tsx new file mode 100644 index 000000000..2372bc78e --- /dev/null +++ b/frontend/src/Calendar/Events/CalendarEventQueueDetails.tsx @@ -0,0 +1,58 @@ +import React from 'react'; +import QueueDetails from 'Activity/Queue/QueueDetails'; +import CircularProgressBar from 'Components/CircularProgressBar'; +import { + QueueTrackedDownloadState, + QueueTrackedDownloadStatus, + StatusMessage, +} from 'typings/Queue'; + +interface CalendarEventQueueDetailsProps { + title: string; + size: number; + sizeleft: number; + estimatedCompletionTime?: string; + status: string; + trackedDownloadState: QueueTrackedDownloadState; + trackedDownloadStatus: QueueTrackedDownloadStatus; + statusMessages?: StatusMessage[]; + errorMessage?: string; +} + +function CalendarEventQueueDetails({ + title, + size, + sizeleft, + estimatedCompletionTime, + status, + trackedDownloadState, + trackedDownloadStatus, + statusMessages, + errorMessage, +}: CalendarEventQueueDetailsProps) { + const progress = size ? 100 - (sizeleft / size) * 100 : 0; + + return ( + + } + /> + ); +} + +export default CalendarEventQueueDetails; diff --git a/frontend/src/Calendar/Header/CalendarHeader.css b/frontend/src/Calendar/Header/CalendarHeader.css new file mode 100644 index 000000000..4b6915406 --- /dev/null +++ b/frontend/src/Calendar/Header/CalendarHeader.css @@ -0,0 +1,53 @@ +.header { + display: flex; +} + +.navigationButtons { + flex: 1 1 33%; + text-align: left; +} + +.todayButton { + composes: button from '~Components/Link/Button.css'; + + margin-left: 5px; +} + +.titleDesktop, +.titleMobile { + text-align: center; + font-size: 18px; +} + +.titleMobile { + margin-bottom: 5px; +} + +.viewButtonsContainer { + display: flex; + justify-content: flex-end; + flex: 1 1 33%; +} + +.viewMenu { + composes: menu from '~Components/Menu/Menu.css'; + + line-height: 31px; +} + +.loading { + composes: loading from '~Components/Loading/LoadingIndicator.css'; + + margin-top: 5px; + margin-right: 10px; +} + +@media only screen and (max-width: $breakpointSmall) { + .navigationButtons { + flex: 1 0 50%; + } + + .viewButtonsContainer { + flex: 0 0 100px; + } +} diff --git a/frontend/src/Calendar/Header/CalendarHeader.css.d.ts b/frontend/src/Calendar/Header/CalendarHeader.css.d.ts new file mode 100644 index 000000000..700b53652 --- /dev/null +++ b/frontend/src/Calendar/Header/CalendarHeader.css.d.ts @@ -0,0 +1,14 @@ +// This file is automatically generated. +// Please do not change this file! +interface CssExports { + 'header': string; + 'loading': string; + 'navigationButtons': string; + 'titleDesktop': string; + 'titleMobile': string; + 'todayButton': string; + 'viewButtonsContainer': string; + 'viewMenu': string; +} +export const cssExports: CssExports; +export default cssExports; diff --git a/frontend/src/Calendar/Header/CalendarHeader.tsx b/frontend/src/Calendar/Header/CalendarHeader.tsx new file mode 100644 index 000000000..2faaca25e --- /dev/null +++ b/frontend/src/Calendar/Header/CalendarHeader.tsx @@ -0,0 +1,221 @@ +import moment from 'moment'; +import React, { useCallback, useMemo } from 'react'; +import { useDispatch, useSelector } from 'react-redux'; +import AppState from 'App/State/AppState'; +import { CalendarView } from 'Calendar/calendarViews'; +import Icon from 'Components/Icon'; +import Button from 'Components/Link/Button'; +import LoadingIndicator from 'Components/Loading/LoadingIndicator'; +import Menu from 'Components/Menu/Menu'; +import MenuButton from 'Components/Menu/MenuButton'; +import MenuContent from 'Components/Menu/MenuContent'; +import ViewMenuItem from 'Components/Menu/ViewMenuItem'; +import { align, icons } from 'Helpers/Props'; +import { + gotoCalendarNextRange, + gotoCalendarPreviousRange, + gotoCalendarToday, + setCalendarView, +} from 'Store/Actions/calendarActions'; +import createDimensionsSelector from 'Store/Selectors/createDimensionsSelector'; +import createUISettingsSelector from 'Store/Selectors/createUISettingsSelector'; +import translate from 'Utilities/String/translate'; +import CalendarHeaderViewButton from './CalendarHeaderViewButton'; +import styles from './CalendarHeader.css'; + +function CalendarHeader() { + const dispatch = useDispatch(); + + const { isFetching, view, time, start, end } = useSelector( + (state: AppState) => state.calendar + ); + + const { isSmallScreen, isLargeScreen } = useSelector( + createDimensionsSelector() + ); + + const { longDateFormat } = useSelector(createUISettingsSelector()); + + const handleViewChange = useCallback( + (newView: CalendarView) => { + dispatch(setCalendarView({ view: newView })); + }, + [dispatch] + ); + + const handleTodayPress = useCallback(() => { + dispatch(gotoCalendarToday()); + }, [dispatch]); + + const handlePreviousPress = useCallback(() => { + dispatch(gotoCalendarPreviousRange()); + }, [dispatch]); + + const handleNextPress = useCallback(() => { + dispatch(gotoCalendarNextRange()); + }, [dispatch]); + + const title = useMemo(() => { + const timeMoment = moment(time); + const startMoment = moment(start); + const endMoment = moment(end); + + if (view === 'day') { + return timeMoment.format(longDateFormat); + } else if (view === 'month') { + return timeMoment.format('MMMM YYYY'); + } else if (view === 'agenda') { + return translate('Agenda'); + } + + let startFormat = 'MMM D YYYY'; + let endFormat = 'MMM D YYYY'; + + if (startMoment.isSame(endMoment, 'month')) { + startFormat = 'MMM D'; + endFormat = 'D YYYY'; + } else if (startMoment.isSame(endMoment, 'year')) { + startFormat = 'MMM D'; + endFormat = 'MMM D YYYY'; + } + + return `${startMoment.format(startFormat)} \u2014 ${endMoment.format( + endFormat + )}`; + }, [time, start, end, view, longDateFormat]); + + return ( +
+ {isSmallScreen ?
{title}
: null} + +
+
+ + + + + +
+ + {isSmallScreen ? null : ( +
{title}
+ )} + +
+ {isFetching ? ( + + ) : null} + + {isLargeScreen ? ( + + + + + + + {isSmallScreen ? null : ( + + {translate('Month')} + + )} + + + {translate('Week')} + + + + {translate('Forecast')} + + + + {translate('Day')} + + + + {translate('Agenda')} + + + + ) : ( + <> + + + + + + + + + + + )} +
+
+
+ ); +} + +export default CalendarHeader; diff --git a/frontend/src/Calendar/Header/CalendarHeaderViewButton.tsx b/frontend/src/Calendar/Header/CalendarHeaderViewButton.tsx new file mode 100644 index 000000000..c9366f9ef --- /dev/null +++ b/frontend/src/Calendar/Header/CalendarHeaderViewButton.tsx @@ -0,0 +1,34 @@ +import React, { useCallback } from 'react'; +import { CalendarView } from 'Calendar/calendarViews'; +import Button, { ButtonProps } from 'Components/Link/Button'; +import titleCase from 'Utilities/String/titleCase'; + +interface CalendarHeaderViewButtonProps + extends Omit { + view: CalendarView; + selectedView: CalendarView; + onPress: (view: CalendarView) => void; +} + +function CalendarHeaderViewButton({ + view, + selectedView, + onPress, + ...otherProps +}: CalendarHeaderViewButtonProps) { + const handlePress = useCallback(() => { + onPress(view); + }, [view, onPress]); + + return ( + + ); +} + +export default CalendarHeaderViewButton; diff --git a/frontend/src/Calendar/Legend/Legend.css b/frontend/src/Calendar/Legend/Legend.css new file mode 100644 index 000000000..296cbd9d5 --- /dev/null +++ b/frontend/src/Calendar/Legend/Legend.css @@ -0,0 +1,6 @@ +.legend { + display: flex; + flex-wrap: wrap; + margin-top: 10px; + padding: 3px 0; +} diff --git a/frontend/src/Calendar/Legend/Legend.css.d.ts b/frontend/src/Calendar/Legend/Legend.css.d.ts new file mode 100644 index 000000000..19c0339b4 --- /dev/null +++ b/frontend/src/Calendar/Legend/Legend.css.d.ts @@ -0,0 +1,7 @@ +// This file is automatically generated. +// Please do not change this file! +interface CssExports { + 'legend': string; +} +export const cssExports: CssExports; +export default cssExports; diff --git a/frontend/src/Calendar/Legend/Legend.tsx b/frontend/src/Calendar/Legend/Legend.tsx new file mode 100644 index 000000000..b9887f856 --- /dev/null +++ b/frontend/src/Calendar/Legend/Legend.tsx @@ -0,0 +1,150 @@ +import React from 'react'; +import { useSelector } from 'react-redux'; +import AppState from 'App/State/AppState'; +import { icons, kinds } from 'Helpers/Props'; +import createUISettingsSelector from 'Store/Selectors/createUISettingsSelector'; +import translate from 'Utilities/String/translate'; +import LegendIconItem from './LegendIconItem'; +import LegendItem from './LegendItem'; +import styles from './Legend.css'; + +function Legend() { + const view = useSelector((state: AppState) => state.calendar.view); + const { + showFinaleIcon, + showSpecialIcon, + showCutoffUnmetIcon, + fullColorEvents, + } = useSelector((state: AppState) => state.calendar.options); + const { enableColorImpairedMode } = useSelector(createUISettingsSelector()); + + const iconsToShow = []; + const isAgendaView = view === 'agenda'; + + if (showFinaleIcon) { + iconsToShow.push( + + ); + + iconsToShow.push( + + ); + } + + if (showSpecialIcon) { + iconsToShow.push( + + ); + } + + if (showCutoffUnmetIcon) { + iconsToShow.push( + + ); + } + + return ( +
+
+ + + +
+ +
+ + + +
+ +
+ + + +
+ +
+ + + {iconsToShow[0]} +
+ + {iconsToShow.length > 1 ? ( +
+ {iconsToShow[1]} + {iconsToShow[2]} +
+ ) : null} + {iconsToShow.length > 3 ?
{iconsToShow[3]}
: null} +
+ ); +} + +export default Legend; diff --git a/frontend/src/Calendar/Legend/LegendIconItem.css b/frontend/src/Calendar/Legend/LegendIconItem.css new file mode 100644 index 000000000..c6c12027d --- /dev/null +++ b/frontend/src/Calendar/Legend/LegendIconItem.css @@ -0,0 +1,14 @@ +.legendIconItem { + margin: 3px 0; + margin-right: 6px; + width: 150px; + cursor: default; +} + +.icon { + margin-right: 5px; + + &:global(.fullColorEvents) { + filter: var(--calendarFullColorFilter) + } +} diff --git a/frontend/src/Calendar/Legend/LegendIconItem.css.d.ts b/frontend/src/Calendar/Legend/LegendIconItem.css.d.ts new file mode 100644 index 000000000..5d618d24b --- /dev/null +++ b/frontend/src/Calendar/Legend/LegendIconItem.css.d.ts @@ -0,0 +1,8 @@ +// This file is automatically generated. +// Please do not change this file! +interface CssExports { + 'icon': string; + 'legendIconItem': string; +} +export const cssExports: CssExports; +export default cssExports; diff --git a/frontend/src/Calendar/Legend/LegendIconItem.tsx b/frontend/src/Calendar/Legend/LegendIconItem.tsx new file mode 100644 index 000000000..88a758c44 --- /dev/null +++ b/frontend/src/Calendar/Legend/LegendIconItem.tsx @@ -0,0 +1,33 @@ +import { FontAwesomeIconProps } from '@fortawesome/react-fontawesome'; +import classNames from 'classnames'; +import React from 'react'; +import Icon, { IconProps } from 'Components/Icon'; +import styles from './LegendIconItem.css'; + +interface LegendIconItemProps extends Pick { + name: string; + fullColorEvents: boolean; + icon: FontAwesomeIconProps['icon']; + tooltip: string; +} + +function LegendIconItem(props: LegendIconItemProps) { + const { name, fullColorEvents, icon, kind, tooltip } = props; + + return ( +
+ + + {name} +
+ ); +} + +export default LegendIconItem; diff --git a/frontend/src/Calendar/Legend/LegendItem.css b/frontend/src/Calendar/Legend/LegendItem.css new file mode 100644 index 000000000..c71a6d916 --- /dev/null +++ b/frontend/src/Calendar/Legend/LegendItem.css @@ -0,0 +1,41 @@ +.legendItem { + margin: 3px 0; + margin-right: 6px; + padding-left: 5px; + width: 150px; + border-left-width: 4px; + border-left-style: solid; + cursor: default; +} + +/* + * Status + */ + +.downloaded { + composes: downloaded from '~Calendar/Events/CalendarEvent.css'; +} + +.downloading { + composes: downloading from '~Calendar/Events/CalendarEvent.css'; +} + +.unmonitored { + composes: unmonitored from '~Calendar/Events/CalendarEvent.css'; +} + +.onAir { + composes: onAir from '~Calendar/Events/CalendarEvent.css'; +} + +.missing { + composes: missing from '~Calendar/Events/CalendarEvent.css'; +} + +.premiere { + composes: premiere from '~Calendar/Events/CalendarEvent.css'; +} + +.unaired { + composes: unaired from '~Calendar/Events/CalendarEvent.css'; +} diff --git a/frontend/src/Calendar/Legend/LegendItem.css.d.ts b/frontend/src/Calendar/Legend/LegendItem.css.d.ts new file mode 100644 index 000000000..155e029c6 --- /dev/null +++ b/frontend/src/Calendar/Legend/LegendItem.css.d.ts @@ -0,0 +1,14 @@ +// This file is automatically generated. +// Please do not change this file! +interface CssExports { + 'downloaded': string; + 'downloading': string; + 'legendItem': string; + 'missing': string; + 'onAir': string; + 'premiere': string; + 'unaired': string; + 'unmonitored': string; +} +export const cssExports: CssExports; +export default cssExports; diff --git a/frontend/src/Calendar/Legend/LegendItem.tsx b/frontend/src/Calendar/Legend/LegendItem.tsx new file mode 100644 index 000000000..40466ab9d --- /dev/null +++ b/frontend/src/Calendar/Legend/LegendItem.tsx @@ -0,0 +1,41 @@ +import classNames from 'classnames'; +import React from 'react'; +import { CalendarStatus } from 'typings/Calendar'; +import titleCase from 'Utilities/String/titleCase'; +import styles from './LegendItem.css'; + +interface LegendItemProps { + name?: string; + status: CalendarStatus; + tooltip: string; + isAgendaView: boolean; + fullColorEvents: boolean; + colorImpairedMode: boolean; +} + +function LegendItem(props: LegendItemProps) { + const { + name, + status, + tooltip, + isAgendaView, + fullColorEvents, + colorImpairedMode, + } = props; + + return ( +
+ {name ? name : titleCase(status)} +
+ ); +} + +export default LegendItem; diff --git a/frontend/src/Calendar/Options/CalendarOptionsModal.tsx b/frontend/src/Calendar/Options/CalendarOptionsModal.tsx new file mode 100644 index 000000000..ae782a684 --- /dev/null +++ b/frontend/src/Calendar/Options/CalendarOptionsModal.tsx @@ -0,0 +1,21 @@ +import React from 'react'; +import Modal from 'Components/Modal/Modal'; +import CalendarOptionsModalContent from './CalendarOptionsModalContent'; + +interface CalendarOptionsModalProps { + isOpen: boolean; + onModalClose: () => void; +} + +function CalendarOptionsModal({ + isOpen, + onModalClose, +}: CalendarOptionsModalProps) { + return ( + + + + ); +} + +export default CalendarOptionsModal; diff --git a/frontend/src/Calendar/Options/CalendarOptionsModalContent.tsx b/frontend/src/Calendar/Options/CalendarOptionsModalContent.tsx new file mode 100644 index 000000000..4f974dda3 --- /dev/null +++ b/frontend/src/Calendar/Options/CalendarOptionsModalContent.tsx @@ -0,0 +1,228 @@ +import React, { useCallback, useEffect, useState } from 'react'; +import { useDispatch, useSelector } from 'react-redux'; +import AppState from 'App/State/AppState'; +import FieldSet from 'Components/FieldSet'; +import Form from 'Components/Form/Form'; +import FormGroup from 'Components/Form/FormGroup'; +import FormInputGroup from 'Components/Form/FormInputGroup'; +import FormLabel from 'Components/Form/FormLabel'; +import Button from 'Components/Link/Button'; +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 { inputTypes } from 'Helpers/Props'; +import { + firstDayOfWeekOptions, + timeFormatOptions, + weekColumnOptions, +} from 'Settings/UI/UISettings'; +import { setCalendarOption } from 'Store/Actions/calendarActions'; +import { saveUISettings } from 'Store/Actions/settingsActions'; +import createUISettingsSelector from 'Store/Selectors/createUISettingsSelector'; +import { InputChanged } from 'typings/inputs'; +import UiSettings from 'typings/Settings/UiSettings'; +import translate from 'Utilities/String/translate'; + +interface CalendarOptionsModalContentProps { + onModalClose: () => void; +} + +function CalendarOptionsModalContent({ + onModalClose, +}: CalendarOptionsModalContentProps) { + const dispatch = useDispatch(); + + const { + collapseMultipleEpisodes, + showEpisodeInformation, + showFinaleIcon, + showSpecialIcon, + showCutoffUnmetIcon, + fullColorEvents, + } = useSelector((state: AppState) => state.calendar.options); + + const uiSettings = useSelector(createUISettingsSelector()); + + const [state, setState] = useState>({ + firstDayOfWeek: uiSettings.firstDayOfWeek, + calendarWeekColumnHeader: uiSettings.calendarWeekColumnHeader, + timeFormat: uiSettings.timeFormat, + enableColorImpairedMode: uiSettings.enableColorImpairedMode, + }); + + const { + firstDayOfWeek, + calendarWeekColumnHeader, + timeFormat, + enableColorImpairedMode, + } = state; + + const handleOptionInputChange = useCallback( + ({ name, value }: InputChanged) => { + dispatch(setCalendarOption({ [name]: value })); + }, + [dispatch] + ); + + const handleGlobalInputChange = useCallback( + ({ name, value }: InputChanged) => { + setState((prevState) => ({ ...prevState, [name]: value })); + + dispatch(saveUISettings({ [name]: value })); + }, + [dispatch] + ); + + useEffect(() => { + setState({ + firstDayOfWeek: uiSettings.firstDayOfWeek, + calendarWeekColumnHeader: uiSettings.calendarWeekColumnHeader, + timeFormat: uiSettings.timeFormat, + enableColorImpairedMode: uiSettings.enableColorImpairedMode, + }); + }, [uiSettings]); + + return ( + + {translate('CalendarOptions')} + + +
+
+ + {translate('CollapseMultipleEpisodes')} + + + + + + {translate('ShowEpisodeInformation')} + + + + + + {translate('IconForFinales')} + + + + + + {translate('IconForSpecials')} + + + + + + {translate('IconForCutoffUnmet')} + + + + + + {translate('FullColorEvents')} + + + +
+
+ +
+
+ + {translate('FirstDayOfWeek')} + + + + + + {translate('WeekColumnHeader')} + + + + + + {translate('TimeFormat')} + + + + + + {translate('EnableColorImpairedMode')} + + + +
+
+
+ + + + +
+ ); +} + +export default CalendarOptionsModalContent; diff --git a/frontend/src/Calendar/calendarViews.ts b/frontend/src/Calendar/calendarViews.ts new file mode 100644 index 000000000..4f5549dbd --- /dev/null +++ b/frontend/src/Calendar/calendarViews.ts @@ -0,0 +1,9 @@ +export const DAY = 'day'; +export const WEEK = 'week'; +export const MONTH = 'month'; +export const FORECAST = 'forecast'; +export const AGENDA = 'agenda'; + +export const all = [DAY, WEEK, MONTH, FORECAST, AGENDA]; + +export type CalendarView = 'agenda' | 'day' | 'forecast' | 'month' | 'week'; diff --git a/frontend/src/Calendar/getStatusStyle.ts b/frontend/src/Calendar/getStatusStyle.ts new file mode 100644 index 000000000..678e6c2a1 --- /dev/null +++ b/frontend/src/Calendar/getStatusStyle.ts @@ -0,0 +1,36 @@ +import moment from 'moment'; +import { CalendarStatus } from 'typings/Calendar'; + +function getStatusStyle( + hasFile: boolean, + downloading: boolean, + startTime: moment.Moment, + endTime: moment.Moment, + isMonitored: boolean +): CalendarStatus { + const currentTime = moment(); + + if (hasFile) { + return 'downloaded'; + } + + if (downloading) { + return 'downloading'; + } + + if (!isMonitored) { + return 'unmonitored'; + } + + if (currentTime.isAfter(startTime) && currentTime.isBefore(endTime)) { + return 'onAir'; + } + + if (endTime.isBefore(currentTime) && !hasFile) { + return 'missing'; + } + + return 'unaired'; +} + +export default getStatusStyle; diff --git a/frontend/src/Calendar/iCal/CalendarLinkModal.tsx b/frontend/src/Calendar/iCal/CalendarLinkModal.tsx new file mode 100644 index 000000000..f0eecbd4a --- /dev/null +++ b/frontend/src/Calendar/iCal/CalendarLinkModal.tsx @@ -0,0 +1,20 @@ +import React from 'react'; +import Modal from 'Components/Modal/Modal'; +import CalendarLinkModalContent from './CalendarLinkModalContent'; + +interface CalendarLinkModalProps { + isOpen: boolean; + onModalClose: () => void; +} + +function CalendarLinkModal(props: CalendarLinkModalProps) { + const { isOpen, onModalClose } = props; + + return ( + + + + ); +} + +export default CalendarLinkModal; diff --git a/frontend/src/Calendar/iCal/CalendarLinkModalContent.tsx b/frontend/src/Calendar/iCal/CalendarLinkModalContent.tsx new file mode 100644 index 000000000..aa90db301 --- /dev/null +++ b/frontend/src/Calendar/iCal/CalendarLinkModalContent.tsx @@ -0,0 +1,166 @@ +import React, { FocusEvent, useCallback, useMemo, useState } from 'react'; +import Form from 'Components/Form/Form'; +import FormGroup from 'Components/Form/FormGroup'; +import FormInputButton from 'Components/Form/FormInputButton'; +import FormInputGroup from 'Components/Form/FormInputGroup'; +import FormLabel from 'Components/Form/FormLabel'; +import Icon from 'Components/Icon'; +import Button from 'Components/Link/Button'; +import ClipboardButton from 'Components/Link/ClipboardButton'; +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 { icons, inputTypes, kinds, sizes } from 'Helpers/Props'; +import { InputChanged } from 'typings/inputs'; +import translate from 'Utilities/String/translate'; + +interface CalendarLinkModalContentProps { + onModalClose: () => void; +} + +function CalendarLinkModalContent({ + onModalClose, +}: CalendarLinkModalContentProps) { + const [state, setState] = useState({ + unmonitored: false, + premieresOnly: false, + asAllDay: false, + tags: [], + }); + + const { unmonitored, premieresOnly, asAllDay, tags } = state; + + const handleInputChange = useCallback(({ name, value }: InputChanged) => { + setState((prevState) => ({ ...prevState, [name]: value })); + }, []); + + const handleLinkFocus = useCallback( + (event: FocusEvent) => { + event.target.select(); + }, + [] + ); + + const { iCalHttpUrl, iCalWebCalUrl } = useMemo(() => { + let icalUrl = `${window.location.host}${window.Sonarr.urlBase}/feed/v3/calendar/Sonarr.ics?`; + + if (unmonitored) { + icalUrl += 'unmonitored=true&'; + } + + if (premieresOnly) { + icalUrl += 'premieresOnly=true&'; + } + + if (asAllDay) { + icalUrl += 'asAllDay=true&'; + } + + if (tags.length) { + icalUrl += `tags=${tags.toString()}&`; + } + + icalUrl += `apikey=${encodeURIComponent(window.Sonarr.apiKey)}`; + + return { + iCalHttpUrl: `${window.location.protocol}//${icalUrl}`, + iCalWebCalUrl: `webcal://${icalUrl}`, + }; + }, [unmonitored, premieresOnly, asAllDay, tags]); + + return ( + + {translate('CalendarFeed')} + + +
+ + {translate('IncludeUnmonitored')} + + + + + + {translate('SeasonPremieresOnly')} + + + + + + {translate('ICalShowAsAllDayEvents')} + + + + + + {translate('Tags')} + + + + + + {translate('ICalFeed')} + + , + + + + , + ]} + onChange={handleInputChange} + onFocus={handleLinkFocus} + /> + +
+
+ + + + +
+ ); +} + +export default CalendarLinkModalContent; diff --git a/frontend/src/Commands/Command.ts b/frontend/src/Commands/Command.ts new file mode 100644 index 000000000..cd875d56b --- /dev/null +++ b/frontend/src/Commands/Command.ts @@ -0,0 +1,52 @@ +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; + completionMessage: string; + requiresDiskAccess: boolean; + isExclusive: boolean; + isLongRunning: boolean; + name: string; + lastExecutionTime: string; + lastStartTime: string; + trigger: string; + suppressMessages: boolean; + seriesId?: number; + seriesIds?: number[]; + seasonNumber?: number; + episodeIds?: number[]; + [key: string]: string | number | boolean | number[] | undefined; +} + +interface Command extends ModelBase { + name: string; + commandName: string; + message: string; + body: CommandBody; + priority: string; + status: CommandStatus; + result: CommandResult; + queued: string; + started: string; + ended: string; + duration: string; + trigger: string; + stateChangeTime: string; + sendUpdatesToClient: boolean; + updateScheduledTask: boolean; + lastExecutionTime: string; +} + +export default Command; diff --git a/frontend/src/Commands/commandNames.js b/frontend/src/Commands/commandNames.js new file mode 100644 index 000000000..13ac9d62c --- /dev/null +++ b/frontend/src/Commands/commandNames.js @@ -0,0 +1,21 @@ +export const APPLICATION_UPDATE = 'ApplicationUpdate'; +export const BACKUP = 'Backup'; +export const REFRESH_MONITORED_DOWNLOADS = 'RefreshMonitoredDownloads'; +export const CLEAR_BLOCKLIST = 'ClearBlocklist'; +export const CLEAR_LOGS = 'ClearLog'; +export const CUTOFF_UNMET_EPISODE_SEARCH = 'CutoffUnmetEpisodeSearch'; +export const DELETE_LOG_FILES = 'DeleteLogFiles'; +export const DELETE_UPDATE_LOG_FILES = 'DeleteUpdateLogFiles'; +export const DOWNLOADED_EPISODES_SCAN = 'DownloadedEpisodesScan'; +export const EPISODE_SEARCH = 'EpisodeSearch'; +export const INTERACTIVE_IMPORT = 'ManualImport'; +export const MISSING_EPISODE_SEARCH = 'MissingEpisodeSearch'; +export const MOVE_SERIES = 'MoveSeries'; +export const REFRESH_SERIES = 'RefreshSeries'; +export const RENAME_FILES = 'RenameFiles'; +export const RENAME_SERIES = 'RenameSeries'; +export const RESET_API_KEY = 'ResetApiKey'; +export const RESET_QUALITY_DEFINITIONS = 'ResetQualityDefinitions'; +export const RSS_SYNC = 'RssSync'; +export const SEASON_SEARCH = 'SeasonSearch'; +export const SERIES_SEARCH = 'SeriesSearch'; diff --git a/frontend/src/Components/Alert.css b/frontend/src/Components/Alert.css new file mode 100644 index 000000000..135d1ee2b --- /dev/null +++ b/frontend/src/Components/Alert.css @@ -0,0 +1,31 @@ +.alert { + display: block; + margin: 5px; + padding: 15px; + border: 1px solid transparent; + border-radius: 4px; +} + +.danger { + border-color: var(--alertDangerBorderColor); + background-color: var(--alertDangerBackgroundColor); + color: var(--alertDangerColor); +} + +.info { + border-color: var(--alertInfoBorderColor); + background-color: var(--alertInfoBackgroundColor); + color: var(--alertInfoColor); +} + +.success { + border-color: var(--alertSuccessBorderColor); + background-color: var(--alertSuccessBackgroundColor); + color: var(--alertSuccessColor); +} + +.warning { + border-color: var(--alertWarningBorderColor); + background-color: var(--alertWarningBackgroundColor); + color: var(--alertWarningColor); +} diff --git a/frontend/src/Components/Alert.css.d.ts b/frontend/src/Components/Alert.css.d.ts new file mode 100644 index 000000000..daffec2e6 --- /dev/null +++ b/frontend/src/Components/Alert.css.d.ts @@ -0,0 +1,11 @@ +// This file is automatically generated. +// Please do not change this file! +interface CssExports { + 'alert': string; + 'danger': string; + 'info': string; + 'success': string; + 'warning': string; +} +export const cssExports: CssExports; +export default cssExports; diff --git a/frontend/src/Components/Alert.tsx b/frontend/src/Components/Alert.tsx new file mode 100644 index 000000000..92c89e741 --- /dev/null +++ b/frontend/src/Components/Alert.tsx @@ -0,0 +1,18 @@ +import classNames from 'classnames'; +import React from 'react'; +import { Kind } from 'Helpers/Props/kinds'; +import styles from './Alert.css'; + +interface AlertProps { + className?: string; + kind?: Extract; + children: React.ReactNode; +} + +function Alert(props: AlertProps) { + const { className = styles.alert, kind = 'info', children } = props; + + return
{children}
; +} + +export default Alert; diff --git a/frontend/src/Components/Card.css b/frontend/src/Components/Card.css new file mode 100644 index 000000000..49a9abd76 --- /dev/null +++ b/frontend/src/Components/Card.css @@ -0,0 +1,19 @@ +.card { + position: relative; + margin: 10px; + padding: 10px; + border-radius: 3px; + background-color: var(--cardBackgroundColor); + box-shadow: 0 0 10px 1px var(--cardShadowColor); + color: var(--defaultColor); +} + +.underlay { + @add-mixin cover; +} + +.overlay { + @add-mixin linkOverlay; + + position: relative; +} diff --git a/frontend/src/Components/Card.css.d.ts b/frontend/src/Components/Card.css.d.ts new file mode 100644 index 000000000..fb3ea792e --- /dev/null +++ b/frontend/src/Components/Card.css.d.ts @@ -0,0 +1,9 @@ +// This file is automatically generated. +// Please do not change this file! +interface CssExports { + 'card': string; + 'overlay': string; + 'underlay': string; +} +export const cssExports: CssExports; +export default cssExports; diff --git a/frontend/src/Components/Card.tsx b/frontend/src/Components/Card.tsx new file mode 100644 index 000000000..24588c841 --- /dev/null +++ b/frontend/src/Components/Card.tsx @@ -0,0 +1,39 @@ +import React from 'react'; +import Link, { LinkProps } from 'Components/Link/Link'; +import styles from './Card.css'; + +interface CardProps extends Pick { + // TODO: Consider using different properties for classname depending if it's overlaying content or not + className?: string; + overlayClassName?: string; + overlayContent?: boolean; + children: React.ReactNode; +} + +function Card(props: CardProps) { + const { + className = styles.card, + overlayClassName = styles.overlay, + overlayContent = false, + children, + onPress, + } = props; + + if (overlayContent) { + return ( +
+ + +
{children}
+
+ ); + } + + return ( + + {children} + + ); +} + +export default Card; diff --git a/frontend/src/Components/CircularProgressBar.css b/frontend/src/Components/CircularProgressBar.css new file mode 100644 index 000000000..32b349404 --- /dev/null +++ b/frontend/src/Components/CircularProgressBar.css @@ -0,0 +1,21 @@ +.circularProgressBarContainer { + position: relative; + display: inline-block; + vertical-align: top; + text-align: center; +} + +.circularProgressBar { + position: absolute; + top: 0; + left: 0; + transform: rotate(-90deg); + transform-origin: center center; +} + +.circularProgressBarText { + position: absolute; + width: 100%; + height: 100%; + font-weight: bold; +} diff --git a/frontend/src/Components/CircularProgressBar.css.d.ts b/frontend/src/Components/CircularProgressBar.css.d.ts new file mode 100644 index 000000000..45179620c --- /dev/null +++ b/frontend/src/Components/CircularProgressBar.css.d.ts @@ -0,0 +1,9 @@ +// This file is automatically generated. +// Please do not change this file! +interface CssExports { + 'circularProgressBar': string; + 'circularProgressBarContainer': string; + 'circularProgressBarText': string; +} +export const cssExports: CssExports; +export default cssExports; diff --git a/frontend/src/Components/CircularProgressBar.tsx b/frontend/src/Components/CircularProgressBar.tsx new file mode 100644 index 000000000..b14f5fc6a --- /dev/null +++ b/frontend/src/Components/CircularProgressBar.tsx @@ -0,0 +1,99 @@ +import React, { useCallback, useEffect, useState } from 'react'; +import styles from './CircularProgressBar.css'; + +interface CircularProgressBarProps { + className?: string; + containerClassName?: string; + size?: number; + progress: number; + strokeWidth?: number; + strokeColor?: string; + showProgressText?: boolean; +} + +function CircularProgressBar({ + className = styles.circularProgressBar, + containerClassName = styles.circularProgressBarContainer, + size = 60, + strokeWidth = 5, + strokeColor = '#35c5f4', + showProgressText = false, + progress, +}: CircularProgressBarProps) { + const [currentProgress, setCurrentProgress] = useState(0); + const raf = React.useRef(0); + const center = size / 2; + const radius = center - strokeWidth; + const circumference = Math.PI * (radius * 2); + const sizeInPixels = `${size}px`; + const strokeDashoffset = ((100 - currentProgress) / 100) * circumference; + const progressText = `${Math.round(currentProgress)}%`; + + const handleAnimation = useCallback( + (p: number) => { + setCurrentProgress((prevProgress) => { + if (prevProgress < p) { + return prevProgress + Math.min(1, p - prevProgress); + } + + return prevProgress; + }); + }, + [setCurrentProgress] + ); + + useEffect(() => { + if (progress > currentProgress) { + cancelAnimationFrame(raf.current); + + raf.current = requestAnimationFrame(() => handleAnimation(progress)); + } + }, [progress, currentProgress, handleAnimation]); + + useEffect( + () => { + return () => cancelAnimationFrame(raf.current); + }, + // We only want to run this effect once + // eslint-disable-next-line react-hooks/exhaustive-deps + [] + ); + + return ( +
+ + + + + {showProgressText && ( +
{progressText}
+ )} +
+ ); +} + +export default CircularProgressBar; diff --git a/frontend/src/Components/DescriptionList/DescriptionList.css b/frontend/src/Components/DescriptionList/DescriptionList.css new file mode 100644 index 000000000..230347f80 --- /dev/null +++ b/frontend/src/Components/DescriptionList/DescriptionList.css @@ -0,0 +1,4 @@ +.descriptionList { + margin-top: 0; + margin-bottom: 0; +} diff --git a/frontend/src/Components/DescriptionList/DescriptionList.css.d.ts b/frontend/src/Components/DescriptionList/DescriptionList.css.d.ts new file mode 100644 index 000000000..34c1578a4 --- /dev/null +++ b/frontend/src/Components/DescriptionList/DescriptionList.css.d.ts @@ -0,0 +1,7 @@ +// This file is automatically generated. +// Please do not change this file! +interface CssExports { + 'descriptionList': string; +} +export const cssExports: CssExports; +export default cssExports; diff --git a/frontend/src/Components/DescriptionList/DescriptionList.tsx b/frontend/src/Components/DescriptionList/DescriptionList.tsx new file mode 100644 index 000000000..6deee77e5 --- /dev/null +++ b/frontend/src/Components/DescriptionList/DescriptionList.tsx @@ -0,0 +1,15 @@ +import React from 'react'; +import styles from './DescriptionList.css'; + +interface DescriptionListProps { + className?: string; + children?: React.ReactNode; +} + +function DescriptionList(props: DescriptionListProps) { + const { className = styles.descriptionList, children } = props; + + return
{children}
; +} + +export default DescriptionList; diff --git a/frontend/src/Components/DescriptionList/DescriptionListItem.tsx b/frontend/src/Components/DescriptionList/DescriptionListItem.tsx new file mode 100644 index 000000000..13a7efdd0 --- /dev/null +++ b/frontend/src/Components/DescriptionList/DescriptionListItem.tsx @@ -0,0 +1,34 @@ +import React from 'react'; +import DescriptionListItemDescription, { + DescriptionListItemDescriptionProps, +} from './DescriptionListItemDescription'; +import DescriptionListItemTitle, { + DescriptionListItemTitleProps, +} from './DescriptionListItemTitle'; + +interface DescriptionListItemProps { + className?: string; + titleClassName?: DescriptionListItemTitleProps['className']; + descriptionClassName?: DescriptionListItemDescriptionProps['className']; + title?: DescriptionListItemTitleProps['children']; + data?: DescriptionListItemDescriptionProps['children']; +} + +function DescriptionListItem(props: DescriptionListItemProps) { + const { className, titleClassName, descriptionClassName, title, data } = + props; + + return ( +
+ + {title} + + + + {data} + +
+ ); +} + +export default DescriptionListItem; diff --git a/frontend/src/Components/DescriptionList/DescriptionListItemDescription.css b/frontend/src/Components/DescriptionList/DescriptionListItemDescription.css new file mode 100644 index 000000000..786123fb7 --- /dev/null +++ b/frontend/src/Components/DescriptionList/DescriptionListItemDescription.css @@ -0,0 +1,11 @@ +.description { + margin-left: 0; + line-height: $lineHeight; + overflow-wrap: break-word; +} + +@media (min-width: 768px) { + .description { + margin-left: 180px; + } +} diff --git a/frontend/src/Components/DescriptionList/DescriptionListItemDescription.css.d.ts b/frontend/src/Components/DescriptionList/DescriptionListItemDescription.css.d.ts new file mode 100644 index 000000000..ff7055b0f --- /dev/null +++ b/frontend/src/Components/DescriptionList/DescriptionListItemDescription.css.d.ts @@ -0,0 +1,7 @@ +// This file is automatically generated. +// Please do not change this file! +interface CssExports { + 'description': string; +} +export const cssExports: CssExports; +export default cssExports; diff --git a/frontend/src/Components/DescriptionList/DescriptionListItemDescription.tsx b/frontend/src/Components/DescriptionList/DescriptionListItemDescription.tsx new file mode 100644 index 000000000..e08c117dc --- /dev/null +++ b/frontend/src/Components/DescriptionList/DescriptionListItemDescription.tsx @@ -0,0 +1,17 @@ +import React, { ReactNode } from 'react'; +import styles from './DescriptionListItemDescription.css'; + +export interface DescriptionListItemDescriptionProps { + className?: string; + children?: ReactNode; +} + +function DescriptionListItemDescription( + props: DescriptionListItemDescriptionProps +) { + const { className = styles.description, children } = props; + + return
{children}
; +} + +export default DescriptionListItemDescription; diff --git a/frontend/src/Components/DescriptionList/DescriptionListItemTitle.css b/frontend/src/Components/DescriptionList/DescriptionListItemTitle.css new file mode 100644 index 000000000..e496e463d --- /dev/null +++ b/frontend/src/Components/DescriptionList/DescriptionListItemTitle.css @@ -0,0 +1,18 @@ +.title { + line-height: $lineHeight; +} + +.title { + font-weight: bold; +} + +@media (min-width: 768px) { + .title { + @add-mixin truncate; + + float: left; + clear: left; + width: 160px; + text-align: right; + } +} diff --git a/frontend/src/Components/DescriptionList/DescriptionListItemTitle.css.d.ts b/frontend/src/Components/DescriptionList/DescriptionListItemTitle.css.d.ts new file mode 100644 index 000000000..86bceec06 --- /dev/null +++ b/frontend/src/Components/DescriptionList/DescriptionListItemTitle.css.d.ts @@ -0,0 +1,7 @@ +// This file is automatically generated. +// Please do not change this file! +interface CssExports { + 'title': string; +} +export const cssExports: CssExports; +export default cssExports; diff --git a/frontend/src/Components/DescriptionList/DescriptionListItemTitle.tsx b/frontend/src/Components/DescriptionList/DescriptionListItemTitle.tsx new file mode 100644 index 000000000..59ea6955c --- /dev/null +++ b/frontend/src/Components/DescriptionList/DescriptionListItemTitle.tsx @@ -0,0 +1,15 @@ +import React, { ReactNode } from 'react'; +import styles from './DescriptionListItemTitle.css'; + +export interface DescriptionListItemTitleProps { + className?: string; + children?: ReactNode; +} + +function DescriptionListItemTitle(props: DescriptionListItemTitleProps) { + const { className = styles.title, children } = props; + + return
{children}
; +} + +export default DescriptionListItemTitle; diff --git a/frontend/src/Components/DragPreviewLayer.css b/frontend/src/Components/DragPreviewLayer.css new file mode 100644 index 000000000..46f721fef --- /dev/null +++ b/frontend/src/Components/DragPreviewLayer.css @@ -0,0 +1,9 @@ +.dragLayer { + position: fixed; + top: 0; + left: 0; + z-index: 9999; + width: 100%; + height: 100%; + pointer-events: none; +} diff --git a/frontend/src/Components/DragPreviewLayer.css.d.ts b/frontend/src/Components/DragPreviewLayer.css.d.ts new file mode 100644 index 000000000..6944a829d --- /dev/null +++ b/frontend/src/Components/DragPreviewLayer.css.d.ts @@ -0,0 +1,7 @@ +// This file is automatically generated. +// Please do not change this file! +interface CssExports { + 'dragLayer': string; +} +export const cssExports: CssExports; +export default cssExports; diff --git a/frontend/src/Components/DragPreviewLayer.tsx b/frontend/src/Components/DragPreviewLayer.tsx new file mode 100644 index 000000000..2e578504b --- /dev/null +++ b/frontend/src/Components/DragPreviewLayer.tsx @@ -0,0 +1,21 @@ +import React from 'react'; +import styles from './DragPreviewLayer.css'; + +interface DragPreviewLayerProps { + className?: string; + children?: React.ReactNode; +} + +function DragPreviewLayer({ + className = styles.dragLayer, + children, + ...otherProps +}: DragPreviewLayerProps) { + return ( +
+ {children} +
+ ); +} + +export default DragPreviewLayer; diff --git a/frontend/src/Components/Error/ErrorBoundary.tsx b/frontend/src/Components/Error/ErrorBoundary.tsx new file mode 100644 index 000000000..6b27f7a09 --- /dev/null +++ b/frontend/src/Components/Error/ErrorBoundary.tsx @@ -0,0 +1,46 @@ +import * as sentry from '@sentry/browser'; +import React, { Component, ErrorInfo } from 'react'; + +interface ErrorBoundaryProps { + children: React.ReactNode; + errorComponent: React.ElementType; +} + +interface ErrorBoundaryState { + error: Error | null; + info: ErrorInfo | null; +} + +// Class component until componentDidCatch is supported in functional components +class ErrorBoundary extends Component { + constructor(props: ErrorBoundaryProps) { + super(props); + + this.state = { + error: null, + info: null, + }; + } + + componentDidCatch(error: Error, info: ErrorInfo) { + this.setState({ + error, + info, + }); + + sentry.captureException(error); + } + + render() { + const { children, errorComponent: ErrorComponent } = this.props; + const { error, info } = this.state; + + if (error) { + return ; + } + + return children; + } +} + +export default ErrorBoundary; diff --git a/frontend/src/Components/Error/ErrorBoundaryError.css b/frontend/src/Components/Error/ErrorBoundaryError.css new file mode 100644 index 000000000..3e7a04302 --- /dev/null +++ b/frontend/src/Components/Error/ErrorBoundaryError.css @@ -0,0 +1,42 @@ +.container { + text-align: center; +} + +.message { + margin: 50px 0; + text-align: center; + font-weight: 300; + font-size: 36px; +} + +.imageContainer { + display: flex; + justify-content: center; + flex: 0 0 auto; +} + +.image { + height: 350px; +} + +.details { + margin: 20px; + text-align: left; + white-space: pre-wrap; +} + +.version { + margin-top: 20px; +} + +@media only screen and (max-width: $breakpointMedium) { + .image { + height: 250px; + } +} + +@media only screen and (max-width: $breakpointSmall) { + .image { + height: 150px; + } +} diff --git a/frontend/src/Components/Error/ErrorBoundaryError.css.d.ts b/frontend/src/Components/Error/ErrorBoundaryError.css.d.ts new file mode 100644 index 000000000..e19fd804d --- /dev/null +++ b/frontend/src/Components/Error/ErrorBoundaryError.css.d.ts @@ -0,0 +1,12 @@ +// This file is automatically generated. +// Please do not change this file! +interface CssExports { + 'container': string; + 'details': string; + 'image': string; + 'imageContainer': string; + 'message': string; + 'version': string; +} +export const cssExports: CssExports; +export default cssExports; diff --git a/frontend/src/Components/Error/ErrorBoundaryError.tsx b/frontend/src/Components/Error/ErrorBoundaryError.tsx new file mode 100644 index 000000000..870b28058 --- /dev/null +++ b/frontend/src/Components/Error/ErrorBoundaryError.tsx @@ -0,0 +1,73 @@ +import React, { useEffect, useState } from 'react'; +import StackTrace from 'stacktrace-js'; +import translate from 'Utilities/String/translate'; +import styles from './ErrorBoundaryError.css'; + +interface ErrorBoundaryErrorProps { + className: string; + messageClassName: string; + detailsClassName: string; + message: string; + error: Error; + info: { + componentStack: string; + }; +} + +function ErrorBoundaryError(props: ErrorBoundaryErrorProps) { + const { + className = styles.container, + messageClassName = styles.message, + detailsClassName = styles.details, + message = translate('ErrorLoadingContent'), + error, + info, + } = props; + + const [detailedError, setDetailedError] = useState< + StackTrace.StackFrame[] | null + >(null); + + useEffect(() => { + if (error) { + StackTrace.fromError(error).then((de) => { + setDetailedError(de); + }); + } else { + setDetailedError(null); + } + }, [error, setDetailedError]); + + return ( +
+
{message}
+ +
+ +
+ +
+ {error ?
{error.message}
: null} + + {detailedError ? ( + detailedError.map((d, index) => { + return ( +
+ {` at ${d.functionName} (${d.fileName}:${d.lineNumber}:${d.columnNumber})`} +
+ ); + }) + ) : ( +
{info.componentStack}
+ )} + +
Version: {window.Sonarr.version}
+
+
+ ); +} + +export default ErrorBoundaryError; diff --git a/frontend/src/Components/FieldSet.css b/frontend/src/Components/FieldSet.css new file mode 100644 index 000000000..9ea0dbab1 --- /dev/null +++ b/frontend/src/Components/FieldSet.css @@ -0,0 +1,24 @@ +.fieldSet { + margin: 0; + margin-bottom: 20px; + padding: 0; + min-width: 0; + border: 0; +} + +.legend { + display: block; + margin-bottom: 21px; + padding: 0; + width: 100%; + border: 0; + border-bottom: 1px solid #e5e5e5; + color: var(--textColor); + font-size: 21px; + line-height: inherit; + + &.small { + color: #909293; + font-size: 18px; + } +} diff --git a/frontend/src/Components/FieldSet.css.d.ts b/frontend/src/Components/FieldSet.css.d.ts new file mode 100644 index 000000000..74e99779a --- /dev/null +++ b/frontend/src/Components/FieldSet.css.d.ts @@ -0,0 +1,9 @@ +// This file is automatically generated. +// Please do not change this file! +interface CssExports { + 'fieldSet': string; + 'legend': string; + 'small': string; +} +export const cssExports: CssExports; +export default cssExports; diff --git a/frontend/src/Components/FieldSet.tsx b/frontend/src/Components/FieldSet.tsx new file mode 100644 index 000000000..c2ff03a7f --- /dev/null +++ b/frontend/src/Components/FieldSet.tsx @@ -0,0 +1,29 @@ +import classNames from 'classnames'; +import React, { ComponentProps } from 'react'; +import { sizes } from 'Helpers/Props'; +import { Size } from 'Helpers/Props/sizes'; +import styles from './FieldSet.css'; + +interface FieldSetProps { + size?: Size; + legend?: ComponentProps<'legend'>['children']; + children?: React.ReactNode; +} + +function FieldSet({ size = sizes.MEDIUM, legend, children }: FieldSetProps) { + return ( +
+ + {legend} + + {children} +
+ ); +} + +export default FieldSet; diff --git a/frontend/src/Components/FileBrowser/FileBrowserModal.css b/frontend/src/Components/FileBrowser/FileBrowserModal.css new file mode 100644 index 000000000..59dba1397 --- /dev/null +++ b/frontend/src/Components/FileBrowser/FileBrowserModal.css @@ -0,0 +1,5 @@ +.modal { + composes: modal from '~Components/Modal/Modal.css'; + + height: 600px; +} diff --git a/frontend/src/Components/FileBrowser/FileBrowserModal.css.d.ts b/frontend/src/Components/FileBrowser/FileBrowserModal.css.d.ts new file mode 100644 index 000000000..5d00cca7e --- /dev/null +++ b/frontend/src/Components/FileBrowser/FileBrowserModal.css.d.ts @@ -0,0 +1,7 @@ +// This file is automatically generated. +// Please do not change this file! +interface CssExports { + 'modal': string; +} +export const cssExports: CssExports; +export default cssExports; diff --git a/frontend/src/Components/FileBrowser/FileBrowserModal.tsx b/frontend/src/Components/FileBrowser/FileBrowserModal.tsx new file mode 100644 index 000000000..0925890de --- /dev/null +++ b/frontend/src/Components/FileBrowser/FileBrowserModal.tsx @@ -0,0 +1,23 @@ +import React from 'react'; +import Modal from 'Components/Modal/Modal'; +import FileBrowserModalContent, { + FileBrowserModalContentProps, +} from './FileBrowserModalContent'; +import styles from './FileBrowserModal.css'; + +interface FileBrowserModalProps extends FileBrowserModalContentProps { + isOpen: boolean; + onModalClose: () => void; +} + +function FileBrowserModal(props: FileBrowserModalProps) { + const { isOpen, onModalClose, ...otherProps } = props; + + return ( + + + + ); +} + +export default FileBrowserModal; diff --git a/frontend/src/Components/FileBrowser/FileBrowserModalContent.css b/frontend/src/Components/FileBrowser/FileBrowserModalContent.css new file mode 100644 index 000000000..db31d6f86 --- /dev/null +++ b/frontend/src/Components/FileBrowser/FileBrowserModalContent.css @@ -0,0 +1,33 @@ +.modalBody { + composes: modalBody from '~Components/Modal/ModalBody.css'; + + display: flex; + flex-direction: column; +} + +.mappedDrivesWarning { + composes: alert from '~Components/Alert.css'; + + margin: 0; + margin-bottom: 20px; +} + +.faqLink { + color: var(--alertWarningColor); + font-weight: bold; +} + +.pathInput { + composes: inputWrapper from '~Components/Form/PathInput.css'; + + flex: 0 0 auto; +} + +.scroller { + margin-top: 20px; +} + +.loading { + display: inline-block; + margin-right: auto; +} diff --git a/frontend/src/Components/FileBrowser/FileBrowserModalContent.css.d.ts b/frontend/src/Components/FileBrowser/FileBrowserModalContent.css.d.ts new file mode 100644 index 000000000..e83c13075 --- /dev/null +++ b/frontend/src/Components/FileBrowser/FileBrowserModalContent.css.d.ts @@ -0,0 +1,12 @@ +// This file is automatically generated. +// Please do not change this file! +interface CssExports { + 'faqLink': string; + 'loading': string; + 'mappedDrivesWarning': string; + 'modalBody': string; + 'pathInput': string; + 'scroller': string; +} +export const cssExports: CssExports; +export default cssExports; diff --git a/frontend/src/Components/FileBrowser/FileBrowserModalContent.tsx b/frontend/src/Components/FileBrowser/FileBrowserModalContent.tsx new file mode 100644 index 000000000..41338cb39 --- /dev/null +++ b/frontend/src/Components/FileBrowser/FileBrowserModalContent.tsx @@ -0,0 +1,237 @@ +import React, { useCallback, useEffect, useRef, useState } from 'react'; +import { useDispatch, useSelector } from 'react-redux'; +import Alert from 'Components/Alert'; +import { PathInputInternal } from 'Components/Form/PathInput'; +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 Scroller from 'Components/Scroller/Scroller'; +import Column from 'Components/Table/Column'; +import Table from 'Components/Table/Table'; +import TableBody from 'Components/Table/TableBody'; +import usePrevious from 'Helpers/Hooks/usePrevious'; +import { kinds, scrollDirections } from 'Helpers/Props'; +import { clearPaths, fetchPaths } from 'Store/Actions/pathActions'; +import createSystemStatusSelector from 'Store/Selectors/createSystemStatusSelector'; +import { InputChanged } from 'typings/inputs'; +import translate from 'Utilities/String/translate'; +import createPathsSelector from './createPathsSelector'; +import FileBrowserRow from './FileBrowserRow'; +import styles from './FileBrowserModalContent.css'; + +const columns: Column[] = [ + { + name: 'type', + label: () => translate('Type'), + isVisible: true, + }, + { + name: 'name', + label: () => translate('Name'), + isVisible: true, + }, +]; + +const handleClearPaths = () => {}; + +export interface FileBrowserModalContentProps { + name: string; + value: string; + includeFiles?: boolean; + onChange: (args: InputChanged) => unknown; + onModalClose: () => void; +} + +function FileBrowserModalContent(props: FileBrowserModalContentProps) { + const { name, value, includeFiles = true, onChange, onModalClose } = props; + + const dispatch = useDispatch(); + + const { isWindows, mode } = useSelector(createSystemStatusSelector()); + const { isFetching, isPopulated, error, parent, directories, files, paths } = + useSelector(createPathsSelector()); + + const [currentPath, setCurrentPath] = useState(value); + const scrollerRef = useRef(null); + const previousValue = usePrevious(value); + + const emptyParent = parent === ''; + const isWindowsService = isWindows && mode === 'service'; + + const handlePathInputChange = useCallback( + ({ value }: InputChanged) => { + setCurrentPath(value); + }, + [] + ); + + const handleRowPress = useCallback( + (path: string) => { + setCurrentPath(path); + + dispatch( + fetchPaths({ + path, + allowFoldersWithoutTrailingSlashes: true, + includeFiles, + }) + ); + }, + [includeFiles, dispatch, setCurrentPath] + ); + + const handleOkPress = useCallback(() => { + onChange({ + name, + value: currentPath, + }); + + dispatch(clearPaths()); + onModalClose(); + }, [name, currentPath, dispatch, onChange, onModalClose]); + + const handleFetchPaths = useCallback( + (path: string) => { + dispatch( + fetchPaths({ + path, + allowFoldersWithoutTrailingSlashes: true, + includeFiles, + }) + ); + }, + [includeFiles, dispatch] + ); + + useEffect(() => { + if (value !== previousValue && value !== currentPath) { + setCurrentPath(value); + } + }, [value, previousValue, currentPath, setCurrentPath]); + + useEffect( + () => { + dispatch( + fetchPaths({ + path: currentPath, + allowFoldersWithoutTrailingSlashes: true, + includeFiles, + }) + ); + + return () => { + dispatch(clearPaths()); + }; + }, + // This should only run once when the component mounts, + // so we don't need to include the other dependencies. + // eslint-disable-next-line react-hooks/exhaustive-deps + [dispatch] + ); + + return ( + + {translate('FileBrowser')} + + + {isWindowsService ? ( + + + + ) : null} + + + + + {error ?
{translate('ErrorLoadingContents')}
: null} + + {isPopulated && !error ? ( + + + {emptyParent ? ( + + ) : null} + + {!emptyParent && parent ? ( + + ) : null} + + {directories.map((directory) => { + return ( + + ); + })} + + {files.map((file) => { + return ( + + ); + })} + +
+ ) : null} +
+
+ + + {isFetching ? ( + + ) : null} + + + + + +
+ ); +} + +export default FileBrowserModalContent; diff --git a/frontend/src/Components/FileBrowser/FileBrowserRow.css b/frontend/src/Components/FileBrowser/FileBrowserRow.css new file mode 100644 index 000000000..9f111ed5d --- /dev/null +++ b/frontend/src/Components/FileBrowser/FileBrowserRow.css @@ -0,0 +1,5 @@ +.type { + composes: cell from '~Components/Table/Cells/TableRowCell.css'; + + width: 32px; +} diff --git a/frontend/src/Components/FileBrowser/FileBrowserRow.css.d.ts b/frontend/src/Components/FileBrowser/FileBrowserRow.css.d.ts new file mode 100644 index 000000000..127d00928 --- /dev/null +++ b/frontend/src/Components/FileBrowser/FileBrowserRow.css.d.ts @@ -0,0 +1,7 @@ +// This file is automatically generated. +// Please do not change this file! +interface CssExports { + 'type': string; +} +export const cssExports: CssExports; +export default cssExports; diff --git a/frontend/src/Components/FileBrowser/FileBrowserRow.tsx b/frontend/src/Components/FileBrowser/FileBrowserRow.tsx new file mode 100644 index 000000000..fe47f1664 --- /dev/null +++ b/frontend/src/Components/FileBrowser/FileBrowserRow.tsx @@ -0,0 +1,49 @@ +import React, { useCallback } from 'react'; +import { PathType } from 'App/State/PathsAppState'; +import Icon from 'Components/Icon'; +import TableRowCell from 'Components/Table/Cells/TableRowCell'; +import TableRowButton from 'Components/Table/TableRowButton'; +import { icons } from 'Helpers/Props'; +import styles from './FileBrowserRow.css'; + +function getIconName(type: PathType) { + switch (type) { + case 'computer': + return icons.COMPUTER; + case 'drive': + return icons.DRIVE; + case 'file': + return icons.FILE; + case 'parent': + return icons.PARENT; + default: + return icons.FOLDER; + } +} + +interface FileBrowserRowProps { + type: PathType; + name: string; + path: string; + onPress: (path: string) => void; +} + +function FileBrowserRow(props: FileBrowserRowProps) { + const { type, name, path, onPress } = props; + + const handlePress = useCallback(() => { + onPress(path); + }, [path, onPress]); + + return ( + + + + + + {name} + + ); +} + +export default FileBrowserRow; diff --git a/frontend/src/Components/FileBrowser/createPathsSelector.ts b/frontend/src/Components/FileBrowser/createPathsSelector.ts new file mode 100644 index 000000000..5da830bd5 --- /dev/null +++ b/frontend/src/Components/FileBrowser/createPathsSelector.ts @@ -0,0 +1,36 @@ +import { createSelector } from 'reselect'; +import AppState from 'App/State/AppState'; + +function createPathsSelector() { + return createSelector( + (state: AppState) => state.paths, + (paths) => { + const { + isFetching, + isPopulated, + error, + parent, + currentPath, + directories, + files, + } = paths; + + const filteredPaths = [...directories, ...files].filter(({ path }) => { + return path.toLowerCase().startsWith(currentPath.toLowerCase()); + }); + + return { + isFetching, + isPopulated, + error, + parent, + currentPath, + directories, + files, + paths: filteredPaths, + }; + } + ); +} + +export default createPathsSelector; diff --git a/frontend/src/Components/Filter/Builder/BoolFilterBuilderRowValue.js b/frontend/src/Components/Filter/Builder/BoolFilterBuilderRowValue.js new file mode 100644 index 000000000..eea574dd1 --- /dev/null +++ b/frontend/src/Components/Filter/Builder/BoolFilterBuilderRowValue.js @@ -0,0 +1,18 @@ +import React from 'react'; +import FilterBuilderRowValue from './FilterBuilderRowValue'; + +const protocols = [ + { id: true, name: 'true' }, + { id: false, name: 'false' } +]; + +function BoolFilterBuilderRowValue(props) { + return ( + + ); +} + +export default BoolFilterBuilderRowValue; diff --git a/frontend/src/Components/Filter/Builder/DateFilterBuilderRowValue.css b/frontend/src/Components/Filter/Builder/DateFilterBuilderRowValue.css new file mode 100644 index 000000000..39db60700 --- /dev/null +++ b/frontend/src/Components/Filter/Builder/DateFilterBuilderRowValue.css @@ -0,0 +1,15 @@ +.container { + display: flex; +} + +.numberInput { + composes: input from '~Components/Form/TextInput.css'; + + margin-right: 3px; +} + +.selectInput { + composes: select from '~Components/Form/SelectInput.css'; + + margin-left: 3px; +} diff --git a/frontend/src/Components/Filter/Builder/DateFilterBuilderRowValue.css.d.ts b/frontend/src/Components/Filter/Builder/DateFilterBuilderRowValue.css.d.ts new file mode 100644 index 000000000..d391a1f30 --- /dev/null +++ b/frontend/src/Components/Filter/Builder/DateFilterBuilderRowValue.css.d.ts @@ -0,0 +1,9 @@ +// This file is automatically generated. +// Please do not change this file! +interface CssExports { + 'container': string; + 'numberInput': string; + 'selectInput': string; +} +export const cssExports: CssExports; +export default cssExports; diff --git a/frontend/src/Components/Filter/Builder/DateFilterBuilderRowValue.js b/frontend/src/Components/Filter/Builder/DateFilterBuilderRowValue.js new file mode 100644 index 000000000..0193cf44f --- /dev/null +++ b/frontend/src/Components/Filter/Builder/DateFilterBuilderRowValue.js @@ -0,0 +1,177 @@ +import PropTypes from 'prop-types'; +import React, { Component } from 'react'; +import NumberInput from 'Components/Form/NumberInput'; +import SelectInput from 'Components/Form/SelectInput'; +import TextInput from 'Components/Form/TextInput'; +import { IN_LAST, IN_NEXT, NOT_IN_LAST, NOT_IN_NEXT } from 'Helpers/Props/filterTypes'; +import isString from 'Utilities/String/isString'; +import { NAME } from './FilterBuilderRowValue'; +import styles from './DateFilterBuilderRowValue.css'; + +const timeOptions = [ + { key: 'seconds', value: 'seconds' }, + { key: 'minutes', value: 'minutes' }, + { key: 'hours', value: 'hours' }, + { key: 'days', value: 'days' }, + { key: 'weeks', value: 'weeks' }, + { key: 'months', value: 'months' } +]; + +function isInFilter(filterType) { + return ( + filterType === IN_LAST || + filterType === NOT_IN_LAST || + filterType === IN_NEXT || + filterType === NOT_IN_NEXT + ); +} + +class DateFilterBuilderRowValue extends Component { + + // + // Lifecycle + + componentDidMount() { + const { + filterType, + filterValue, + onChange + } = this.props; + + if (isInFilter(filterType) && isString(filterValue)) { + onChange({ + name: NAME, + value: { + time: timeOptions[0].key, + value: null + } + }); + } + } + + componentDidUpdate(prevProps) { + const { + filterType, + filterValue, + onChange + } = this.props; + + if (prevProps.filterType === filterType) { + return; + } + + if (isInFilter(filterType) && isString(filterValue)) { + onChange({ + name: NAME, + value: { + time: timeOptions[0].key, + value: null + } + }); + + return; + } + + if (!isInFilter(filterType) && !isString(filterValue)) { + onChange({ + name: NAME, + value: '' + }); + } + } + + // + // Listeners + + onValueChange = ({ value }) => { + const { + filterValue, + onChange + } = this.props; + + let newValue = value; + + if (!isString(value)) { + newValue = { + time: filterValue.time, + value + }; + } + + onChange({ + name: NAME, + value: newValue + }); + }; + + onTimeChange = ({ value }) => { + const { + filterValue, + onChange + } = this.props; + + onChange({ + name: NAME, + value: { + time: value, + value: filterValue.value + } + }); + }; + + // + // Render + + render() { + const { + filterType, + filterValue + } = this.props; + + if ( + (isInFilter(filterType) && isString(filterValue)) || + (!isInFilter(filterType) && !isString(filterValue)) + ) { + return null; + } + + if (isInFilter(filterType)) { + return ( +
+ + + +
+ ); + } + + return ( + + ); + } +} + +DateFilterBuilderRowValue.propTypes = { + filterType: PropTypes.string, + filterValue: PropTypes.oneOfType([PropTypes.string, PropTypes.object]).isRequired, + onChange: PropTypes.func.isRequired +}; + +export default DateFilterBuilderRowValue; diff --git a/frontend/src/Components/Filter/Builder/FilterBuilderModalContent.css b/frontend/src/Components/Filter/Builder/FilterBuilderModalContent.css new file mode 100644 index 000000000..6cc8fab67 --- /dev/null +++ b/frontend/src/Components/Filter/Builder/FilterBuilderModalContent.css @@ -0,0 +1,16 @@ +.labelContainer { + margin-bottom: 20px; +} + +.label { + margin-bottom: 5px; + font-weight: bold; +} + +.labelInputContainer { + width: 300px; +} + +.rows { + margin-bottom: 100px; +} diff --git a/frontend/src/Components/Filter/Builder/FilterBuilderModalContent.css.d.ts b/frontend/src/Components/Filter/Builder/FilterBuilderModalContent.css.d.ts new file mode 100644 index 000000000..033d2edca --- /dev/null +++ b/frontend/src/Components/Filter/Builder/FilterBuilderModalContent.css.d.ts @@ -0,0 +1,10 @@ +// This file is automatically generated. +// Please do not change this file! +interface CssExports { + 'label': string; + 'labelContainer': string; + 'labelInputContainer': string; + 'rows': string; +} +export const cssExports: CssExports; +export default cssExports; diff --git a/frontend/src/Components/Filter/Builder/FilterBuilderModalContent.js b/frontend/src/Components/Filter/Builder/FilterBuilderModalContent.js new file mode 100644 index 000000000..0c4a31657 --- /dev/null +++ b/frontend/src/Components/Filter/Builder/FilterBuilderModalContent.js @@ -0,0 +1,232 @@ +import { maxBy } from 'lodash'; +import PropTypes from 'prop-types'; +import React, { Component } from 'react'; +import FormInputGroup from 'Components/Form/FormInputGroup'; +import Button from 'Components/Link/Button'; +import SpinnerErrorButton from 'Components/Link/SpinnerErrorButton'; +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 { inputTypes } from 'Helpers/Props'; +import translate from 'Utilities/String/translate'; +import FilterBuilderRow from './FilterBuilderRow'; +import styles from './FilterBuilderModalContent.css'; + +class FilterBuilderModalContent extends Component { + + // + // Lifecycle + + constructor(props, context) { + super(props, context); + + const filters = [...props.filters]; + + // Push an empty filter if there aren't any filters. FilterBuilderRow + // will handle initializing the filter. + + if (!filters.length) { + filters.push({}); + } + + this.state = { + label: props.label, + filters, + labelErrors: [] + }; + } + + componentDidUpdate(prevProps) { + const { + id, + customFilters, + isSaving, + saveError, + dispatchSetFilter, + onModalClose + } = this.props; + + if (prevProps.isSaving && !isSaving && !saveError) { + if (id) { + dispatchSetFilter({ selectedFilterKey: id }); + } else { + const last = maxBy(customFilters, 'id'); + dispatchSetFilter({ selectedFilterKey: last.id }); + } + + onModalClose(); + } + } + + // + // Listeners + + onLabelChange = ({ value }) => { + this.setState({ label: value }); + }; + + onFilterChange = (index, filter) => { + const filters = [...this.state.filters]; + filters.splice(index, 1, filter); + + this.setState({ + filters + }); + }; + + onAddFilterPress = () => { + const filters = [...this.state.filters]; + filters.push({}); + + this.setState({ + filters + }); + }; + + onRemoveFilterPress = (index) => { + const filters = [...this.state.filters]; + filters.splice(index, 1); + + this.setState({ + filters + }); + }; + + onSaveFilterPress = () => { + const { + id, + customFilterType, + onSaveCustomFilterPress + } = this.props; + + const { + label, + filters + } = this.state; + + if (!label) { + this.setState({ + labelErrors: [ + { + message: translate('LabelIsRequired') + } + ] + }); + + return; + } + + onSaveCustomFilterPress({ + id, + type: customFilterType, + label, + filters + }); + }; + + // + // Render + + render() { + const { + sectionItems, + filterBuilderProps, + isSaving, + saveError, + onCancelPress, + onModalClose + } = this.props; + + const { + label, + filters, + labelErrors + } = this.state; + + return ( + + + {translate('CustomFilter')} + + + +
+
+ {translate('Label')} +
+ +
+ +
+
+ +
+ {translate('Filters')} +
+ +
+ { + filters.map((filter, index) => { + return ( + + ); + }) + } +
+
+ + + + + + {translate('Save')} + + +
+ ); + } +} + +FilterBuilderModalContent.propTypes = { + id: PropTypes.number, + label: PropTypes.string.isRequired, + customFilterType: PropTypes.string.isRequired, + sectionItems: PropTypes.arrayOf(PropTypes.object).isRequired, + filters: PropTypes.arrayOf(PropTypes.object).isRequired, + filterBuilderProps: PropTypes.arrayOf(PropTypes.object).isRequired, + customFilters: PropTypes.arrayOf(PropTypes.object).isRequired, + isSaving: PropTypes.bool.isRequired, + saveError: PropTypes.object, + dispatchDeleteCustomFilter: PropTypes.func.isRequired, + onSaveCustomFilterPress: PropTypes.func.isRequired, + dispatchSetFilter: PropTypes.func.isRequired, + onCancelPress: PropTypes.func.isRequired, + onModalClose: PropTypes.func.isRequired +}; + +export default FilterBuilderModalContent; diff --git a/frontend/src/Components/Filter/Builder/FilterBuilderModalContentConnector.js b/frontend/src/Components/Filter/Builder/FilterBuilderModalContentConnector.js new file mode 100644 index 000000000..17633172b --- /dev/null +++ b/frontend/src/Components/Filter/Builder/FilterBuilderModalContentConnector.js @@ -0,0 +1,42 @@ +import { connect } from 'react-redux'; +import { createSelector } from 'reselect'; +import { deleteCustomFilter, saveCustomFilter } from 'Store/Actions/customFilterActions'; +import FilterBuilderModalContent from './FilterBuilderModalContent'; + +function createMapStateToProps() { + return createSelector( + (state, { customFilters }) => customFilters, + (state, { id }) => id, + (state) => state.customFilters.isSaving, + (state) => state.customFilters.saveError, + (customFilters, id, isSaving, saveError) => { + if (id) { + const customFilter = customFilters.find((c) => c.id === id); + + return { + id: customFilter.id, + label: customFilter.label, + filters: customFilter.filters, + customFilters, + isSaving, + saveError + }; + } + + return { + label: '', + filters: [], + customFilters, + isSaving, + saveError + }; + } + ); +} + +const mapDispatchToProps = { + onSaveCustomFilterPress: saveCustomFilter, + dispatchDeleteCustomFilter: deleteCustomFilter +}; + +export default connect(createMapStateToProps, mapDispatchToProps)(FilterBuilderModalContent); diff --git a/frontend/src/Components/Filter/Builder/FilterBuilderRow.css b/frontend/src/Components/Filter/Builder/FilterBuilderRow.css new file mode 100644 index 000000000..bcfc3b04e --- /dev/null +++ b/frontend/src/Components/Filter/Builder/FilterBuilderRow.css @@ -0,0 +1,32 @@ +.filterRow { + display: flex; + margin-bottom: 5px; + + &:hover { + background-color: var(--tableRowHoverBackgroundColor); + } +} + +.inputContainer { + flex: 0 1 200px; + margin-right: 10px; +} + +.valueInputContainer { + flex: 0 1 300px; + margin-right: 10px; +} + +.actionsContainer { + display: flex; +} + +@media only screen and (max-width: $breakpointSmall) { + .filterRow { + display: block; + } + + .inputContainer { + margin-bottom: 10px; + } +} diff --git a/frontend/src/Components/Filter/Builder/FilterBuilderRow.css.d.ts b/frontend/src/Components/Filter/Builder/FilterBuilderRow.css.d.ts new file mode 100644 index 000000000..aba698af4 --- /dev/null +++ b/frontend/src/Components/Filter/Builder/FilterBuilderRow.css.d.ts @@ -0,0 +1,10 @@ +// This file is automatically generated. +// Please do not change this file! +interface CssExports { + 'actionsContainer': string; + 'filterRow': string; + 'inputContainer': string; + 'valueInputContainer': string; +} +export const cssExports: CssExports; +export default cssExports; diff --git a/frontend/src/Components/Filter/Builder/FilterBuilderRow.js b/frontend/src/Components/Filter/Builder/FilterBuilderRow.js new file mode 100644 index 000000000..0b00c0f03 --- /dev/null +++ b/frontend/src/Components/Filter/Builder/FilterBuilderRow.js @@ -0,0 +1,309 @@ +import PropTypes from 'prop-types'; +import React, { Component } from 'react'; +import SelectInput from 'Components/Form/SelectInput'; +import IconButton from 'Components/Link/IconButton'; +import { filterBuilderTypes, filterBuilderValueTypes, icons } from 'Helpers/Props'; +import sortByProp from 'Utilities/Array/sortByProp'; +import BoolFilterBuilderRowValue from './BoolFilterBuilderRowValue'; +import DateFilterBuilderRowValue from './DateFilterBuilderRowValue'; +import FilterBuilderRowValueConnector from './FilterBuilderRowValueConnector'; +import HistoryEventTypeFilterBuilderRowValue from './HistoryEventTypeFilterBuilderRowValue'; +import IndexerFilterBuilderRowValueConnector from './IndexerFilterBuilderRowValueConnector'; +import LanguageFilterBuilderRowValue from './LanguageFilterBuilderRowValue'; +import ProtocolFilterBuilderRowValue from './ProtocolFilterBuilderRowValue'; +import QualityFilterBuilderRowValueConnector from './QualityFilterBuilderRowValueConnector'; +import QualityProfileFilterBuilderRowValue from './QualityProfileFilterBuilderRowValue'; +import QueueStatusFilterBuilderRowValue from './QueueStatusFilterBuilderRowValue'; +import SeasonsMonitoredStatusFilterBuilderRowValue from './SeasonsMonitoredStatusFilterBuilderRowValue'; +import SeriesFilterBuilderRowValue from './SeriesFilterBuilderRowValue'; +import SeriesStatusFilterBuilderRowValue from './SeriesStatusFilterBuilderRowValue'; +import SeriesTypeFilterBuilderRowValue from './SeriesTypeFilterBuilderRowValue'; +import TagFilterBuilderRowValueConnector from './TagFilterBuilderRowValueConnector'; +import styles from './FilterBuilderRow.css'; + +function getselectedFilterBuilderProp(filterBuilderProps, name) { + return filterBuilderProps.find((a) => { + return a.name === name; + }); +} + +function getFilterTypeOptions(filterBuilderProps, filterKey) { + const selectedFilterBuilderProp = getselectedFilterBuilderProp(filterBuilderProps, filterKey); + + if (!selectedFilterBuilderProp) { + return []; + } + + return filterBuilderTypes.possibleFilterTypes[selectedFilterBuilderProp.type]; +} + +function getDefaultFilterType(selectedFilterBuilderProp) { + return filterBuilderTypes.possibleFilterTypes[selectedFilterBuilderProp.type][0].key; +} + +function getDefaultFilterValue(selectedFilterBuilderProp) { + if (selectedFilterBuilderProp.type === filterBuilderTypes.DATE) { + return ''; + } + + return []; +} + +function getRowValueConnector(selectedFilterBuilderProp) { + if (!selectedFilterBuilderProp) { + return FilterBuilderRowValueConnector; + } + + const valueType = selectedFilterBuilderProp.valueType; + + switch (valueType) { + case filterBuilderValueTypes.BOOL: + return BoolFilterBuilderRowValue; + + case filterBuilderValueTypes.DATE: + return DateFilterBuilderRowValue; + + case filterBuilderValueTypes.HISTORY_EVENT_TYPE: + return HistoryEventTypeFilterBuilderRowValue; + + case filterBuilderValueTypes.INDEXER: + return IndexerFilterBuilderRowValueConnector; + + case filterBuilderValueTypes.LANGUAGE: + return LanguageFilterBuilderRowValue; + + case filterBuilderValueTypes.PROTOCOL: + return ProtocolFilterBuilderRowValue; + + case filterBuilderValueTypes.QUALITY: + return QualityFilterBuilderRowValueConnector; + + case filterBuilderValueTypes.QUALITY_PROFILE: + return QualityProfileFilterBuilderRowValue; + + case filterBuilderValueTypes.QUEUE_STATUS: + return QueueStatusFilterBuilderRowValue; + + case filterBuilderValueTypes.SEASONS_MONITORED_STATUS: + return SeasonsMonitoredStatusFilterBuilderRowValue; + + case filterBuilderValueTypes.SERIES: + return SeriesFilterBuilderRowValue; + + case filterBuilderValueTypes.SERIES_STATUS: + return SeriesStatusFilterBuilderRowValue; + + case filterBuilderValueTypes.SERIES_TYPES: + return SeriesTypeFilterBuilderRowValue; + + case filterBuilderValueTypes.TAG: + return TagFilterBuilderRowValueConnector; + + default: + return FilterBuilderRowValueConnector; + } +} + +class FilterBuilderRow extends Component { + + // + // Lifecycle + + constructor(props, context) { + super(props, context); + + const { + filterKey, + filterBuilderProps + } = props; + + if (filterKey) { + const selectedFilterBuilderProp = filterBuilderProps.find((a) => a.name === filterKey); + this.selectedFilterBuilderProp = selectedFilterBuilderProp; + } + } + + componentDidMount() { + const { + index, + filterKey, + filterBuilderProps, + onFilterChange + } = this.props; + + if (filterKey) { + const selectedFilterBuilderProp = filterBuilderProps.find((a) => a.name === filterKey); + this.selectedFilterBuilderProp = selectedFilterBuilderProp; + + return; + } + + const selectedFilterBuilderProp = filterBuilderProps[0]; + + const filter = { + key: selectedFilterBuilderProp.name, + value: getDefaultFilterValue(selectedFilterBuilderProp), + type: getDefaultFilterType(selectedFilterBuilderProp) + }; + + this.selectedFilterBuilderProp = selectedFilterBuilderProp; + onFilterChange(index, filter); + } + + // + // Listeners + + onFilterKeyChange = ({ value: key }) => { + const { + index, + filterBuilderProps, + onFilterChange + } = this.props; + + const selectedFilterBuilderProp = getselectedFilterBuilderProp(filterBuilderProps, key); + const type = getDefaultFilterType(selectedFilterBuilderProp); + + const filter = { + key, + value: getDefaultFilterValue(selectedFilterBuilderProp), + type + }; + + this.selectedFilterBuilderProp = selectedFilterBuilderProp; + onFilterChange(index, filter); + }; + + onFilterChange = ({ name, value }) => { + const { + index, + filterKey, + filterValue, + filterType, + onFilterChange + } = this.props; + + const filter = { + key: filterKey, + value: filterValue, + type: filterType + }; + + filter[name] = value; + + onFilterChange(index, filter); + }; + + onAddPress = () => { + const { + index, + onAddPress + } = this.props; + + onAddPress(index); + }; + + onRemovePress = () => { + const { + index, + onRemovePress + } = this.props; + + onRemovePress(index); + }; + + // + // Render + + render() { + const { + filterKey, + filterType, + filterValue, + filterCount, + filterBuilderProps, + sectionItems + } = this.props; + + const selectedFilterBuilderProp = this.selectedFilterBuilderProp; + + const keyOptions = filterBuilderProps.map((availablePropFilter) => { + const { name, label } = availablePropFilter; + + return { + key: name, + value: typeof label === 'function' ? label() : label + }; + }).sort(sortByProp('value')); + + const ValueComponent = getRowValueConnector(selectedFilterBuilderProp); + + return ( +
+
+ { + filterKey && + + } +
+ +
+ { + filterType && + + } +
+ +
+ { + filterValue != null && !!selectedFilterBuilderProp && + + } +
+ +
+ + + +
+
+ ); + } +} + +FilterBuilderRow.propTypes = { + index: PropTypes.number.isRequired, + filterKey: PropTypes.string, + filterValue: PropTypes.oneOfType([PropTypes.string, PropTypes.number, PropTypes.array, PropTypes.object]), + filterType: PropTypes.string, + filterCount: PropTypes.number.isRequired, + filterBuilderProps: PropTypes.arrayOf(PropTypes.object).isRequired, + sectionItems: PropTypes.arrayOf(PropTypes.object).isRequired, + onFilterChange: PropTypes.func.isRequired, + onAddPress: PropTypes.func.isRequired, + onRemovePress: PropTypes.func.isRequired +}; + +export default FilterBuilderRow; diff --git a/frontend/src/Components/Filter/Builder/FilterBuilderRowValue.js b/frontend/src/Components/Filter/Builder/FilterBuilderRowValue.js new file mode 100644 index 000000000..217626c90 --- /dev/null +++ b/frontend/src/Components/Filter/Builder/FilterBuilderRowValue.js @@ -0,0 +1,160 @@ +import PropTypes from 'prop-types'; +import React, { Component } from 'react'; +import TagInput from 'Components/Form/Tag/TagInput'; +import { filterBuilderTypes, filterBuilderValueTypes, kinds } from 'Helpers/Props'; +import tagShape from 'Helpers/Props/Shapes/tagShape'; +import convertToBytes from 'Utilities/Number/convertToBytes'; +import formatBytes from 'Utilities/Number/formatBytes'; +import FilterBuilderRowValueTag from './FilterBuilderRowValueTag'; + +export const NAME = 'value'; + +function getTagDisplayValue(value, selectedFilterBuilderProp) { + if (selectedFilterBuilderProp.valueType === filterBuilderValueTypes.BYTES) { + return formatBytes(value); + } + + return value; +} + +function getValue(input, selectedFilterBuilderProp) { + if (selectedFilterBuilderProp.valueType === filterBuilderValueTypes.BYTES) { + const match = input.match(/^(\d+)([kmgt](i?b)?)$/i); + + if (match && match.length > 1) { + const [, value, unit] = input.match(/^(\d+)([kmgt](i?b)?)$/i); + + switch (unit.toLowerCase()) { + case 'k': + return convertToBytes(value, 1, true); + case 'm': + return convertToBytes(value, 2, true); + case 'g': + return convertToBytes(value, 3, true); + case 't': + return convertToBytes(value, 4, true); + case 'kb': + return convertToBytes(value, 1, true); + case 'mb': + return convertToBytes(value, 2, true); + case 'gb': + return convertToBytes(value, 3, true); + case 'tb': + return convertToBytes(value, 4, true); + case 'kib': + return convertToBytes(value, 1, true); + case 'mib': + return convertToBytes(value, 2, true); + case 'gib': + return convertToBytes(value, 3, true); + case 'tib': + return convertToBytes(value, 4, true); + default: + return parseInt(value); + } + } + } + + if (selectedFilterBuilderProp.type === filterBuilderTypes.NUMBER) { + return parseInt(input); + } + + return input; +} + +class FilterBuilderRowValue extends Component { + + // + // Listeners + + onTagAdd = (tag) => { + const { + filterValue, + selectedFilterBuilderProp, + onChange + } = this.props; + + let value = tag.id; + + if (value == null) { + value = getValue(tag.name, selectedFilterBuilderProp); + } + + onChange({ + name: NAME, + value: [...filterValue, value] + }); + }; + + onTagDelete = ({ index }) => { + const { + filterValue, + onChange + } = this.props; + + const value = filterValue.filter((v, i) => i !== index); + + onChange({ + name: NAME, + value + }); + }; + + // + // Render + + render() { + const { + filterValue, + selectedFilterBuilderProp, + tagList + } = this.props; + + const hasItems = !!tagList.length; + + const tags = filterValue.map((id) => { + if (hasItems) { + const tag = tagList.find((t) => t.id === id); + + return { + id, + name: tag && tag.name + }; + } + + return { + id, + name: getTagDisplayValue(id, selectedFilterBuilderProp) + }; + }); + + return ( + + ); + } +} + +FilterBuilderRowValue.propTypes = { + filterValue: PropTypes.arrayOf(PropTypes.oneOfType([PropTypes.bool, PropTypes.string, PropTypes.number])).isRequired, + selectedFilterBuilderProp: PropTypes.object.isRequired, + tagList: PropTypes.arrayOf(PropTypes.shape(tagShape)).isRequired, + onChange: PropTypes.func.isRequired +}; + +FilterBuilderRowValue.defaultProps = { + filterValue: [] +}; + +export default FilterBuilderRowValue; diff --git a/frontend/src/Components/Filter/Builder/FilterBuilderRowValueConnector.js b/frontend/src/Components/Filter/Builder/FilterBuilderRowValueConnector.js new file mode 100644 index 000000000..d1419327a --- /dev/null +++ b/frontend/src/Components/Filter/Builder/FilterBuilderRowValueConnector.js @@ -0,0 +1,60 @@ +import _ from 'lodash'; +import { connect } from 'react-redux'; +import { createSelector } from 'reselect'; +import { filterBuilderTypes } from 'Helpers/Props'; +import * as filterTypes from 'Helpers/Props/filterTypes'; +import sortByProp from 'Utilities/Array/sortByProp'; +import FilterBuilderRowValue from './FilterBuilderRowValue'; + +function createTagListSelector() { + return createSelector( + (state, { filterType }) => filterType, + (state, { sectionItems }) => sectionItems, + (state, { selectedFilterBuilderProp }) => selectedFilterBuilderProp, + (filterType, sectionItems, selectedFilterBuilderProp) => { + if ( + (selectedFilterBuilderProp.type === filterBuilderTypes.NUMBER || + selectedFilterBuilderProp.type === filterBuilderTypes.STRING) && + filterType !== filterTypes.EQUAL && + filterType !== filterTypes.NOT_EQUAL || + !selectedFilterBuilderProp.optionsSelector + ) { + return []; + } + + let items = []; + + if (selectedFilterBuilderProp.optionsSelector) { + items = selectedFilterBuilderProp.optionsSelector(sectionItems); + } else { + items = sectionItems.reduce((acc, item) => { + const name = item[selectedFilterBuilderProp.name]; + + if (name) { + acc.push({ + id: name, + name + }); + } + + return acc; + }, []).sort(sortByProp('name')); + } + + return _.uniqBy(items, 'id'); + } + ); +} + +function createMapStateToProps() { + return createSelector( + createTagListSelector(), + (tagList) => { + return { + tagList + }; + } + ); +} + +export default connect(createMapStateToProps)(FilterBuilderRowValue); diff --git a/frontend/src/Components/Filter/Builder/FilterBuilderRowValueProps.ts b/frontend/src/Components/Filter/Builder/FilterBuilderRowValueProps.ts new file mode 100644 index 000000000..5bf9e5785 --- /dev/null +++ b/frontend/src/Components/Filter/Builder/FilterBuilderRowValueProps.ts @@ -0,0 +1,16 @@ +import { FilterBuilderProp } from 'App/State/AppState'; + +interface FilterBuilderRowOnChangeProps { + name: string; + value: unknown[]; +} + +interface FilterBuilderRowValueProps { + filterType?: string; + filterValue: string | number | object | string[] | number[] | object[]; + selectedFilterBuilderProp: FilterBuilderProp; + sectionItem: unknown[]; + onChange: (payload: FilterBuilderRowOnChangeProps) => void; +} + +export default FilterBuilderRowValueProps; diff --git a/frontend/src/Components/Filter/Builder/FilterBuilderRowValueTag.css b/frontend/src/Components/Filter/Builder/FilterBuilderRowValueTag.css new file mode 100644 index 000000000..807f383dd --- /dev/null +++ b/frontend/src/Components/Filter/Builder/FilterBuilderRowValueTag.css @@ -0,0 +1,22 @@ +.tag { + display: flex; + + &.isLastTag { + .or { + display: none; + } + } +} + +.label { + composes: label from '~Components/Label.css'; + + border-style: none; + font-size: 13px; +} + +.or { + margin: 0 3px; + color: var(--themeDarkColor); + line-height: 31px; +} diff --git a/frontend/src/Components/Filter/Builder/FilterBuilderRowValueTag.css.d.ts b/frontend/src/Components/Filter/Builder/FilterBuilderRowValueTag.css.d.ts new file mode 100644 index 000000000..80bcf1464 --- /dev/null +++ b/frontend/src/Components/Filter/Builder/FilterBuilderRowValueTag.css.d.ts @@ -0,0 +1,10 @@ +// This file is automatically generated. +// Please do not change this file! +interface CssExports { + 'isLastTag': string; + 'label': string; + 'or': string; + 'tag': string; +} +export const cssExports: CssExports; +export default cssExports; diff --git a/frontend/src/Components/Filter/Builder/FilterBuilderRowValueTag.js b/frontend/src/Components/Filter/Builder/FilterBuilderRowValueTag.js new file mode 100644 index 000000000..063a97346 --- /dev/null +++ b/frontend/src/Components/Filter/Builder/FilterBuilderRowValueTag.js @@ -0,0 +1,33 @@ +import PropTypes from 'prop-types'; +import React from 'react'; +import TagInputTag from 'Components/Form/Tag/TagInputTag'; +import { kinds } from 'Helpers/Props'; +import translate from 'Utilities/String/translate'; +import styles from './FilterBuilderRowValueTag.css'; + +function FilterBuilderRowValueTag(props) { + return ( +
+ + + { + props.isLastTag ? + null : +
+ {translate('Or')} +
+ } +
+ ); +} + +FilterBuilderRowValueTag.propTypes = { + isLastTag: PropTypes.bool.isRequired +}; + +export default FilterBuilderRowValueTag; diff --git a/frontend/src/Components/Filter/Builder/HistoryEventTypeFilterBuilderRowValue.tsx b/frontend/src/Components/Filter/Builder/HistoryEventTypeFilterBuilderRowValue.tsx new file mode 100644 index 000000000..4ecddf646 --- /dev/null +++ b/frontend/src/Components/Filter/Builder/HistoryEventTypeFilterBuilderRowValue.tsx @@ -0,0 +1,51 @@ +import React from 'react'; +import translate from 'Utilities/String/translate'; +import FilterBuilderRowValue from './FilterBuilderRowValue'; +import FilterBuilderRowValueProps from './FilterBuilderRowValueProps'; + +const EVENT_TYPE_OPTIONS = [ + { + id: 1, + get name() { + return translate('Grabbed'); + }, + }, + { + id: 3, + get name() { + return translate('Imported'); + }, + }, + { + id: 4, + get name() { + return translate('Failed'); + }, + }, + { + id: 5, + get name() { + return translate('Deleted'); + }, + }, + { + id: 6, + get name() { + return translate('Renamed'); + }, + }, + { + id: 7, + get name() { + return translate('Ignored'); + }, + }, +]; + +function HistoryEventTypeFilterBuilderRowValue( + props: FilterBuilderRowValueProps +) { + return ; +} + +export default HistoryEventTypeFilterBuilderRowValue; diff --git a/frontend/src/Components/Filter/Builder/IndexerFilterBuilderRowValueConnector.js b/frontend/src/Components/Filter/Builder/IndexerFilterBuilderRowValueConnector.js new file mode 100644 index 000000000..e834b79a3 --- /dev/null +++ b/frontend/src/Components/Filter/Builder/IndexerFilterBuilderRowValueConnector.js @@ -0,0 +1,79 @@ +import PropTypes from 'prop-types'; +import React, { Component } from 'react'; +import { connect } from 'react-redux'; +import { createSelector } from 'reselect'; +import tagShape from 'Helpers/Props/Shapes/tagShape'; +import { fetchIndexers } from 'Store/Actions/settingsActions'; +import FilterBuilderRowValue from './FilterBuilderRowValue'; + +function createMapStateToProps() { + return createSelector( + (state) => state.settings.indexers, + (qualityProfiles) => { + const { + isFetching, + isPopulated, + error, + items + } = qualityProfiles; + + const tagList = items.map((item) => { + return { + id: item.id, + name: item.name + }; + }); + + return { + isFetching, + isPopulated, + error, + tagList + }; + } + ); +} + +const mapDispatchToProps = { + dispatchFetchIndexers: fetchIndexers +}; + +class IndexerFilterBuilderRowValueConnector extends Component { + + // + // Lifecycle + + componentDidMount = () => { + if (!this.props.isPopulated) { + this.props.dispatchFetchIndexers(); + } + }; + + // + // Render + + render() { + const { + isFetching, + isPopulated, + error, + ...otherProps + } = this.props; + + return ( + + ); + } +} + +IndexerFilterBuilderRowValueConnector.propTypes = { + tagList: PropTypes.arrayOf(PropTypes.shape(tagShape)).isRequired, + isFetching: PropTypes.bool.isRequired, + isPopulated: PropTypes.bool.isRequired, + error: PropTypes.object, + dispatchFetchIndexers: PropTypes.func.isRequired +}; + +export default connect(createMapStateToProps, mapDispatchToProps)(IndexerFilterBuilderRowValueConnector); diff --git a/frontend/src/Components/Filter/Builder/LanguageFilterBuilderRowValue.tsx b/frontend/src/Components/Filter/Builder/LanguageFilterBuilderRowValue.tsx new file mode 100644 index 000000000..e828fd848 --- /dev/null +++ b/frontend/src/Components/Filter/Builder/LanguageFilterBuilderRowValue.tsx @@ -0,0 +1,13 @@ +import React from 'react'; +import { useSelector } from 'react-redux'; +import createLanguagesSelector from 'Store/Selectors/createLanguagesSelector'; +import FilterBuilderRowValue from './FilterBuilderRowValue'; +import FilterBuilderRowValueProps from './FilterBuilderRowValueProps'; + +function LanguageFilterBuilderRowValue(props: FilterBuilderRowValueProps) { + const { items } = useSelector(createLanguagesSelector()); + + return ; +} + +export default LanguageFilterBuilderRowValue; diff --git a/frontend/src/Components/Filter/Builder/ProtocolFilterBuilderRowValue.js b/frontend/src/Components/Filter/Builder/ProtocolFilterBuilderRowValue.js new file mode 100644 index 000000000..ae63ae0eb --- /dev/null +++ b/frontend/src/Components/Filter/Builder/ProtocolFilterBuilderRowValue.js @@ -0,0 +1,18 @@ +import React from 'react'; +import FilterBuilderRowValue from './FilterBuilderRowValue'; + +const protocols = [ + { id: 'torrent', name: 'Torrent' }, + { id: 'usenet', name: 'Usenet' } +]; + +function ProtocolFilterBuilderRowValue(props) { + return ( + + ); +} + +export default ProtocolFilterBuilderRowValue; diff --git a/frontend/src/Components/Filter/Builder/QualityFilterBuilderRowValueConnector.js b/frontend/src/Components/Filter/Builder/QualityFilterBuilderRowValueConnector.js new file mode 100644 index 000000000..fd6e466d4 --- /dev/null +++ b/frontend/src/Components/Filter/Builder/QualityFilterBuilderRowValueConnector.js @@ -0,0 +1,75 @@ +import PropTypes from 'prop-types'; +import React, { Component } from 'react'; +import { connect } from 'react-redux'; +import { createSelector } from 'reselect'; +import tagShape from 'Helpers/Props/Shapes/tagShape'; +import { fetchQualityProfileSchema } from 'Store/Actions/settingsActions'; +import getQualities from 'Utilities/Quality/getQualities'; +import FilterBuilderRowValue from './FilterBuilderRowValue'; + +function createMapStateToProps() { + return createSelector( + (state) => state.settings.qualityProfiles, + (qualityProfiles) => { + const { + isSchemaFetching: isFetching, + isSchemaPopulated: isPopulated, + schemaError: error, + schema + } = qualityProfiles; + + const tagList = getQualities(schema.items); + + return { + isFetching, + isPopulated, + error, + tagList + }; + } + ); +} + +const mapDispatchToProps = { + dispatchFetchQualityProfileSchema: fetchQualityProfileSchema +}; + +class QualityFilterBuilderRowValueConnector extends Component { + + // + // Lifecycle + + componentDidMount = () => { + if (!this.props.isPopulated) { + this.props.dispatchFetchQualityProfileSchema(); + } + }; + + // + // Render + + render() { + const { + isFetching, + isPopulated, + error, + ...otherProps + } = this.props; + + return ( + + ); + } +} + +QualityFilterBuilderRowValueConnector.propTypes = { + tagList: PropTypes.arrayOf(PropTypes.shape(tagShape)).isRequired, + isFetching: PropTypes.bool.isRequired, + isPopulated: PropTypes.bool.isRequired, + error: PropTypes.object, + dispatchFetchQualityProfileSchema: PropTypes.func.isRequired +}; + +export default connect(createMapStateToProps, mapDispatchToProps)(QualityFilterBuilderRowValueConnector); diff --git a/frontend/src/Components/Filter/Builder/QualityProfileFilterBuilderRowValue.tsx b/frontend/src/Components/Filter/Builder/QualityProfileFilterBuilderRowValue.tsx new file mode 100644 index 000000000..50036cb90 --- /dev/null +++ b/frontend/src/Components/Filter/Builder/QualityProfileFilterBuilderRowValue.tsx @@ -0,0 +1,30 @@ +import React from 'react'; +import { useSelector } from 'react-redux'; +import { createSelector } from 'reselect'; +import AppState from 'App/State/AppState'; +import FilterBuilderRowValueProps from 'Components/Filter/Builder/FilterBuilderRowValueProps'; +import sortByProp from 'Utilities/Array/sortByProp'; +import FilterBuilderRowValue from './FilterBuilderRowValue'; + +function createQualityProfilesSelector() { + return createSelector( + (state: AppState) => state.settings.qualityProfiles.items, + (qualityProfiles) => { + return qualityProfiles; + } + ); +} + +function QualityProfileFilterBuilderRowValue( + props: FilterBuilderRowValueProps +) { + const qualityProfiles = useSelector(createQualityProfilesSelector()); + + const tagList = qualityProfiles + .map(({ id, name }) => ({ id, name })) + .sort(sortByProp('name')); + + return ; +} + +export default QualityProfileFilterBuilderRowValue; diff --git a/frontend/src/Components/Filter/Builder/QueueStatusFilterBuilderRowValue.tsx b/frontend/src/Components/Filter/Builder/QueueStatusFilterBuilderRowValue.tsx new file mode 100644 index 000000000..1127493a5 --- /dev/null +++ b/frontend/src/Components/Filter/Builder/QueueStatusFilterBuilderRowValue.tsx @@ -0,0 +1,67 @@ +import React from 'react'; +import translate from 'Utilities/String/translate'; +import FilterBuilderRowValue from './FilterBuilderRowValue'; +import FilterBuilderRowValueProps from './FilterBuilderRowValueProps'; + +const statusTagList = [ + { + id: 'queued', + get name() { + return translate('Queued'); + }, + }, + { + id: 'paused', + get name() { + return translate('Paused'); + }, + }, + { + id: 'downloading', + get name() { + return translate('Downloading'); + }, + }, + { + id: 'completed', + get name() { + return translate('Completed'); + }, + }, + { + id: 'failed', + get name() { + return translate('Failed'); + }, + }, + { + id: 'warning', + get name() { + return translate('Warning'); + }, + }, + { + id: 'delay', + get name() { + return translate('Delay'); + }, + }, + { + id: 'downloadClientUnavailable', + get name() { + return translate('DownloadClientUnavailable'); + }, + }, + { + id: 'fallback', + get name() { + return translate('Fallback'); + }, + }, +]; + +function QueueStatusFilterBuilderRowValue(props: FilterBuilderRowValueProps) { + return ; +} + +export default QueueStatusFilterBuilderRowValue; diff --git a/frontend/src/Components/Filter/Builder/SeasonsMonitoredStatusFilterBuilderRowValue.js b/frontend/src/Components/Filter/Builder/SeasonsMonitoredStatusFilterBuilderRowValue.js new file mode 100644 index 000000000..b84260e3c --- /dev/null +++ b/frontend/src/Components/Filter/Builder/SeasonsMonitoredStatusFilterBuilderRowValue.js @@ -0,0 +1,35 @@ +import React from 'react'; +import translate from 'Utilities/String/translate'; +import FilterBuilderRowValue from './FilterBuilderRowValue'; + +const seasonsMonitoredStatusList = [ + { + id: 'all', + get name() { + return translate('SeasonsMonitoredAll'); + } + }, + { + id: 'partial', + get name() { + return translate('SeasonsMonitoredPartial'); + } + }, + { + id: 'none', + get name() { + return translate('SeasonsMonitoredNone'); + } + } +]; + +function SeasonsMonitoredStatusFilterBuilderRowValue(props) { + return ( + + ); +} + +export default SeasonsMonitoredStatusFilterBuilderRowValue; diff --git a/frontend/src/Components/Filter/Builder/SeriesFilterBuilderRowValue.tsx b/frontend/src/Components/Filter/Builder/SeriesFilterBuilderRowValue.tsx new file mode 100644 index 000000000..88b34509a --- /dev/null +++ b/frontend/src/Components/Filter/Builder/SeriesFilterBuilderRowValue.tsx @@ -0,0 +1,19 @@ +import React from 'react'; +import { useSelector } from 'react-redux'; +import Series from 'Series/Series'; +import createAllSeriesSelector from 'Store/Selectors/createAllSeriesSelector'; +import sortByProp from 'Utilities/Array/sortByProp'; +import FilterBuilderRowValue from './FilterBuilderRowValue'; +import FilterBuilderRowValueProps from './FilterBuilderRowValueProps'; + +function SeriesFilterBuilderRowValue(props: FilterBuilderRowValueProps) { + const allSeries: Series[] = useSelector(createAllSeriesSelector()); + + const tagList = allSeries + .map((series) => ({ id: series.id, name: series.title })) + .sort(sortByProp('name')); + + return ; +} + +export default SeriesFilterBuilderRowValue; diff --git a/frontend/src/Components/Filter/Builder/SeriesStatusFilterBuilderRowValue.js b/frontend/src/Components/Filter/Builder/SeriesStatusFilterBuilderRowValue.js new file mode 100644 index 000000000..e017f72e7 --- /dev/null +++ b/frontend/src/Components/Filter/Builder/SeriesStatusFilterBuilderRowValue.js @@ -0,0 +1,41 @@ +import React from 'react'; +import translate from 'Utilities/String/translate'; +import FilterBuilderRowValue from './FilterBuilderRowValue'; + +const statusTagList = [ + { + id: 'continuing', + get name() { + return translate('Continuing'); + } + }, + { + id: 'upcoming', + get name() { + return translate('Upcoming'); + } + }, + { + id: 'ended', + get name() { + return translate('Ended'); + } + }, + { + id: 'deleted', + get name() { + return translate('Deleted'); + } + } +]; + +function SeriesStatusFilterBuilderRowValue(props) { + return ( + + ); +} + +export default SeriesStatusFilterBuilderRowValue; diff --git a/frontend/src/Components/Filter/Builder/SeriesTypeFilterBuilderRowValue.js b/frontend/src/Components/Filter/Builder/SeriesTypeFilterBuilderRowValue.js new file mode 100644 index 000000000..2e62e558d --- /dev/null +++ b/frontend/src/Components/Filter/Builder/SeriesTypeFilterBuilderRowValue.js @@ -0,0 +1,35 @@ +import React from 'react'; +import translate from 'Utilities/String/translate'; +import FilterBuilderRowValue from './FilterBuilderRowValue'; + +const seriesTypeList = [ + { + id: 'anime', + get name() { + return translate('Anime'); + } + }, + { + id: 'daily', + get name() { + return translate('Daily'); + } + }, + { + id: 'standard', + get name() { + return translate('Standard'); + } + } +]; + +function SeriesTypeFilterBuilderRowValue(props) { + return ( + + ); +} + +export default SeriesTypeFilterBuilderRowValue; diff --git a/frontend/src/Components/Filter/Builder/TagFilterBuilderRowValueConnector.js b/frontend/src/Components/Filter/Builder/TagFilterBuilderRowValueConnector.js new file mode 100644 index 000000000..60e04c446 --- /dev/null +++ b/frontend/src/Components/Filter/Builder/TagFilterBuilderRowValueConnector.js @@ -0,0 +1,27 @@ +import { connect } from 'react-redux'; +import { createSelector } from 'reselect'; +import createTagsSelector from 'Store/Selectors/createTagsSelector'; +import FilterBuilderRowValue from './FilterBuilderRowValue'; + +function createMapStateToProps() { + return createSelector( + createTagsSelector(), + (tagList) => { + return { + tagList: tagList.map((tag) => { + const { + id, + label: name + } = tag; + + return { + id, + name + }; + }) + }; + } + ); +} + +export default connect(createMapStateToProps)(FilterBuilderRowValue); diff --git a/frontend/src/Components/Filter/CustomFilters/CustomFilter.css b/frontend/src/Components/Filter/CustomFilters/CustomFilter.css new file mode 100644 index 000000000..e2b8c72bf --- /dev/null +++ b/frontend/src/Components/Filter/CustomFilters/CustomFilter.css @@ -0,0 +1,17 @@ +.customFilter { + display: flex; + margin-bottom: 5px; + padding: 5px; + + &:hover { + background-color: var(--tableRowHoverBackgroundColor); + } +} + +.label { + flex: 0 1 300px; +} + +.actions { + flex: 0 0 60px; +} diff --git a/frontend/src/Components/Filter/CustomFilters/CustomFilter.css.d.ts b/frontend/src/Components/Filter/CustomFilters/CustomFilter.css.d.ts new file mode 100644 index 000000000..af5bfa967 --- /dev/null +++ b/frontend/src/Components/Filter/CustomFilters/CustomFilter.css.d.ts @@ -0,0 +1,9 @@ +// This file is automatically generated. +// Please do not change this file! +interface CssExports { + 'actions': string; + 'customFilter': string; + 'label': string; +} +export const cssExports: CssExports; +export default cssExports; diff --git a/frontend/src/Components/Filter/CustomFilters/CustomFilter.js b/frontend/src/Components/Filter/CustomFilters/CustomFilter.js new file mode 100644 index 000000000..9f378d5a2 --- /dev/null +++ b/frontend/src/Components/Filter/CustomFilters/CustomFilter.js @@ -0,0 +1,115 @@ +import PropTypes from 'prop-types'; +import React, { Component } from 'react'; +import IconButton from 'Components/Link/IconButton'; +import SpinnerIconButton from 'Components/Link/SpinnerIconButton'; +import { icons } from 'Helpers/Props'; +import translate from 'Utilities/String/translate'; +import styles from './CustomFilter.css'; + +class CustomFilter extends Component { + + // + // Lifecycle + + constructor(props, context) { + super(props, context); + + this.state = { + isDeleting: false + }; + } + + componentDidUpdate(prevProps) { + const { + isDeleting, + deleteError + } = this.props; + + if (prevProps.isDeleting && !isDeleting && this.state.isDeleting && deleteError) { + this.setState({ isDeleting: false }); + } + } + + componentWillUnmount() { + const { + id, + selectedFilterKey, + dispatchSetFilter + } = this.props; + + // Assume that delete and then unmounting means the deletion was successful. + // Moving this check to an ancestor would be more accurate, but would have + // more boilerplate. + if (this.state.isDeleting && id === selectedFilterKey) { + dispatchSetFilter({ selectedFilterKey: 'all' }); + } + } + + // + // Listeners + + onEditPress = () => { + const { + id, + onEditPress + } = this.props; + + onEditPress(id); + }; + + onRemovePress = () => { + const { + id, + dispatchDeleteCustomFilter + } = this.props; + + this.setState({ isDeleting: true }, () => { + dispatchDeleteCustomFilter({ id }); + }); + + }; + + // + // Render + + render() { + const { + label + } = this.props; + + return ( +
+
+ {label} +
+ +
+ + + +
+
+ ); + } +} + +CustomFilter.propTypes = { + id: PropTypes.number.isRequired, + label: PropTypes.string.isRequired, + selectedFilterKey: PropTypes.oneOfType([PropTypes.string, PropTypes.number]).isRequired, + isDeleting: PropTypes.bool.isRequired, + deleteError: PropTypes.object, + dispatchSetFilter: PropTypes.func.isRequired, + onEditPress: PropTypes.func.isRequired, + dispatchDeleteCustomFilter: PropTypes.func.isRequired +}; + +export default CustomFilter; diff --git a/frontend/src/Components/Filter/CustomFilters/CustomFiltersModalContent.css b/frontend/src/Components/Filter/CustomFilters/CustomFiltersModalContent.css new file mode 100644 index 000000000..c391764dc --- /dev/null +++ b/frontend/src/Components/Filter/CustomFilters/CustomFiltersModalContent.css @@ -0,0 +1,3 @@ +.addButtonContainer { + margin-top: 15px; +} diff --git a/frontend/src/Components/Filter/CustomFilters/CustomFiltersModalContent.css.d.ts b/frontend/src/Components/Filter/CustomFilters/CustomFiltersModalContent.css.d.ts new file mode 100644 index 000000000..b505d0767 --- /dev/null +++ b/frontend/src/Components/Filter/CustomFilters/CustomFiltersModalContent.css.d.ts @@ -0,0 +1,7 @@ +// This file is automatically generated. +// Please do not change this file! +interface CssExports { + 'addButtonContainer': string; +} +export const cssExports: CssExports; +export default cssExports; diff --git a/frontend/src/Components/Filter/CustomFilters/CustomFiltersModalContent.js b/frontend/src/Components/Filter/CustomFilters/CustomFiltersModalContent.js new file mode 100644 index 000000000..99cb6ec5c --- /dev/null +++ b/frontend/src/Components/Filter/CustomFilters/CustomFiltersModalContent.js @@ -0,0 +1,84 @@ +import PropTypes from 'prop-types'; +import React from 'react'; +import Button from 'Components/Link/Button'; +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 sortByProp from 'Utilities/Array/sortByProp'; +import translate from 'Utilities/String/translate'; +import CustomFilter from './CustomFilter'; +import styles from './CustomFiltersModalContent.css'; + +function CustomFiltersModalContent(props) { + const { + selectedFilterKey, + customFilters, + isDeleting, + deleteError, + dispatchDeleteCustomFilter, + dispatchSetFilter, + onAddCustomFilter, + onEditCustomFilter, + onModalClose + } = props; + + return ( + + + {translate('CustomFilters')} + + + + { + customFilters + .sort((a, b) => sortByProp(a, b, 'label')) + .map((customFilter) => { + return ( + + ); + }) + } + +
+ +
+
+ + + + +
+ ); +} + +CustomFiltersModalContent.propTypes = { + selectedFilterKey: PropTypes.oneOfType([PropTypes.string, PropTypes.number]).isRequired, + customFilters: PropTypes.arrayOf(PropTypes.object).isRequired, + isDeleting: PropTypes.bool.isRequired, + deleteError: PropTypes.object, + dispatchDeleteCustomFilter: PropTypes.func.isRequired, + dispatchSetFilter: PropTypes.func.isRequired, + onAddCustomFilter: PropTypes.func.isRequired, + onEditCustomFilter: PropTypes.func.isRequired, + onModalClose: PropTypes.func.isRequired +}; + +export default CustomFiltersModalContent; diff --git a/frontend/src/Components/Filter/CustomFilters/CustomFiltersModalContentConnector.js b/frontend/src/Components/Filter/CustomFilters/CustomFiltersModalContentConnector.js new file mode 100644 index 000000000..32425d766 --- /dev/null +++ b/frontend/src/Components/Filter/CustomFilters/CustomFiltersModalContentConnector.js @@ -0,0 +1,23 @@ +import { connect } from 'react-redux'; +import { createSelector } from 'reselect'; +import { deleteCustomFilter } from 'Store/Actions/customFilterActions'; +import CustomFiltersModalContent from './CustomFiltersModalContent'; + +function createMapStateToProps() { + return createSelector( + (state) => state.customFilters.isDeleting, + (state) => state.customFilters.deleteError, + (isDeleting, deleteError) => { + return { + isDeleting, + deleteError + }; + } + ); +} + +const mapDispatchToProps = { + dispatchDeleteCustomFilter: deleteCustomFilter +}; + +export default connect(createMapStateToProps, mapDispatchToProps)(CustomFiltersModalContent); diff --git a/frontend/src/Components/Filter/FilterModal.js b/frontend/src/Components/Filter/FilterModal.js new file mode 100644 index 000000000..d52362d7b --- /dev/null +++ b/frontend/src/Components/Filter/FilterModal.js @@ -0,0 +1,102 @@ +import PropTypes from 'prop-types'; +import React, { Component } from 'react'; +import Modal from 'Components/Modal/Modal'; +import FilterBuilderModalContentConnector from './Builder/FilterBuilderModalContentConnector'; +import CustomFiltersModalContentConnector from './CustomFilters/CustomFiltersModalContentConnector'; + +class FilterModal extends Component { + + // + // Lifecycle + + constructor(props, context) { + super(props, context); + + this.state = { + filterBuilder: !props.customFilters.length, + id: null + }; + } + + // + // Listeners + + onAddCustomFilter = () => { + this.setState({ + filterBuilder: true + }); + }; + + onEditCustomFilter = (id) => { + this.setState({ + filterBuilder: true, + id + }); + }; + + onCancelPress = () => { + if (this.state.filterBuilder) { + this.setState({ + filterBuilder: false, + id: null + }); + } else { + this.onModalClose(); + } + }; + + onModalClose = () => { + this.setState({ + filterBuilder: false, + id: null + }, () => { + this.props.onModalClose(); + }); + }; + + // + // Render + + render() { + const { + isOpen, + ...otherProps + } = this.props; + + const { + filterBuilder, + id + } = this.state; + + return ( + + { + filterBuilder ? + : + + } + + ); + } +} + +FilterModal.propTypes = { + isOpen: PropTypes.bool.isRequired, + customFilters: PropTypes.arrayOf(PropTypes.object).isRequired, + onModalClose: PropTypes.func.isRequired +}; + +export default FilterModal; diff --git a/frontend/src/Components/Form/AutoCompleteInput.tsx b/frontend/src/Components/Form/AutoCompleteInput.tsx new file mode 100644 index 000000000..7ba114125 --- /dev/null +++ b/frontend/src/Components/Form/AutoCompleteInput.tsx @@ -0,0 +1,81 @@ +import jdu from 'jdu'; +import React, { SyntheticEvent, useCallback, useState } from 'react'; +import { + ChangeEvent, + SuggestionsFetchRequestedParams, +} from 'react-autosuggest'; +import { InputChanged } from 'typings/inputs'; +import AutoSuggestInput from './AutoSuggestInput'; + +interface AutoCompleteInputProps { + name: string; + value?: string; + values: string[]; + onChange: (change: InputChanged) => unknown; +} + +function AutoCompleteInput({ + name, + value = '', + values, + onChange, + ...otherProps +}: AutoCompleteInputProps) { + const [suggestions, setSuggestions] = useState([]); + + const getSuggestionValue = useCallback((item: string) => { + return item; + }, []); + + const renderSuggestion = useCallback((item: string) => { + return item; + }, []); + + const handleInputChange = useCallback( + (_event: SyntheticEvent, { newValue }: ChangeEvent) => { + onChange({ + name, + value: newValue, + }); + }, + [name, onChange] + ); + + const handleInputBlur = useCallback(() => { + setSuggestions([]); + }, [setSuggestions]); + + const handleSuggestionsFetchRequested = useCallback( + ({ value: newValue }: SuggestionsFetchRequestedParams) => { + const lowerCaseValue = jdu.replace(newValue).toLowerCase(); + + const filteredValues = values.filter((v) => { + return jdu.replace(v).toLowerCase().includes(lowerCaseValue); + }); + + setSuggestions(filteredValues); + }, + [values, setSuggestions] + ); + + const handleSuggestionsClearRequested = useCallback(() => { + setSuggestions([]); + }, [setSuggestions]); + + return ( + + ); +} + +export default AutoCompleteInput; diff --git a/frontend/src/Components/Form/AutoSuggestInput.css b/frontend/src/Components/Form/AutoSuggestInput.css new file mode 100644 index 000000000..7dc416960 --- /dev/null +++ b/frontend/src/Components/Form/AutoSuggestInput.css @@ -0,0 +1,50 @@ +.input { + composes: input from '~Components/Form/Input.css'; +} + +.hasError { + composes: hasError from '~Components/Form/Input.css'; +} + +.hasWarning { + composes: hasWarning from '~Components/Form/Input.css'; +} + +.inputContainer { + flex-grow: 1; +} + +.suggestionsContainer { + @add-mixin scrollbar; + @add-mixin scrollbarTrack; + @add-mixin scrollbarThumb; +} + +.suggestionsContainerOpen { + z-index: $popperZIndex; + + .suggestionsContainer { + overflow-y: auto; + max-height: 200px; + width: 100%; + border: 1px solid var(--inputBorderColor); + border-radius: 4px; + background-color: var(--inputBackgroundColor); + box-shadow: inset 0 1px 1px var(--inputBoxShadowColor); + } +} + +.suggestionsList { + margin: 5px 0; + padding-left: 0; + max-height: 200px; + list-style-type: none; +} + +.suggestion { + padding: 0 16px; +} + +.suggestionHighlighted { + background-color: var(--menuItemHoverBackgroundColor); +} diff --git a/frontend/src/Components/Form/AutoSuggestInput.css.d.ts b/frontend/src/Components/Form/AutoSuggestInput.css.d.ts new file mode 100644 index 000000000..2b8f51924 --- /dev/null +++ b/frontend/src/Components/Form/AutoSuggestInput.css.d.ts @@ -0,0 +1,15 @@ +// This file is automatically generated. +// Please do not change this file! +interface CssExports { + 'hasError': string; + 'hasWarning': string; + 'input': string; + 'inputContainer': string; + 'suggestion': string; + 'suggestionHighlighted': string; + 'suggestionsContainer': string; + 'suggestionsContainerOpen': string; + 'suggestionsList': string; +} +export const cssExports: CssExports; +export default cssExports; diff --git a/frontend/src/Components/Form/AutoSuggestInput.tsx b/frontend/src/Components/Form/AutoSuggestInput.tsx new file mode 100644 index 000000000..b3a7c31b0 --- /dev/null +++ b/frontend/src/Components/Form/AutoSuggestInput.tsx @@ -0,0 +1,259 @@ +import classNames from 'classnames'; +import React, { + FocusEvent, + FormEvent, + KeyboardEvent, + KeyboardEventHandler, + MutableRefObject, + ReactNode, + Ref, + SyntheticEvent, + useCallback, + useEffect, + useRef, +} from 'react'; +import Autosuggest, { + AutosuggestPropsBase, + BlurEvent, + ChangeEvent, + RenderInputComponentProps, + RenderSuggestionsContainerParams, +} from 'react-autosuggest'; +import { Manager, Popper, Reference } from 'react-popper'; +import Portal from 'Components/Portal'; +import usePrevious from 'Helpers/Hooks/usePrevious'; +import { InputChanged } from 'typings/inputs'; +import styles from './AutoSuggestInput.css'; + +interface AutoSuggestInputProps + extends Omit, 'renderInputComponent' | 'inputProps'> { + forwardedRef?: MutableRefObject | null>; + className?: string; + inputContainerClassName?: string; + name: string; + value?: string; + placeholder?: string; + suggestions: T[]; + hasError?: boolean; + hasWarning?: boolean; + enforceMaxHeight?: boolean; + minHeight?: number; + maxHeight?: number; + renderInputComponent?: ( + inputProps: RenderInputComponentProps, + ref: Ref + ) => ReactNode; + onInputChange: ( + event: FormEvent, + params: ChangeEvent + ) => unknown; + onInputKeyDown?: KeyboardEventHandler; + onInputFocus?: (event: SyntheticEvent) => unknown; + onInputBlur: ( + event: FocusEvent, + params?: BlurEvent + ) => unknown; + onChange?: (change: InputChanged) => unknown; +} + +// eslint-disable-next-line @typescript-eslint/no-explicit-any +function AutoSuggestInput(props: AutoSuggestInputProps) { + const { + // TODO: forwaredRef should be replaces with React.forwardRef + forwardedRef, + className = styles.input, + inputContainerClassName = styles.inputContainer, + name, + value = '', + placeholder, + suggestions, + enforceMaxHeight = true, + hasError, + hasWarning, + minHeight = 50, + maxHeight = 200, + getSuggestionValue, + renderSuggestion, + renderInputComponent, + onInputChange, + onInputKeyDown, + onInputFocus, + onInputBlur, + onSuggestionsFetchRequested, + onSuggestionsClearRequested, + onSuggestionSelected, + onChange, + ...otherProps + } = props; + + const updater = useRef<(() => void) | null>(null); + const previousSuggestions = usePrevious(suggestions); + + const handleComputeMaxHeight = useCallback( + // eslint-disable-next-line @typescript-eslint/no-explicit-any + (data: any) => { + const { top, bottom, width } = data.offsets.reference; + + if (enforceMaxHeight) { + data.styles.maxHeight = maxHeight; + } else { + const windowHeight = window.innerHeight; + + if (/^botton/.test(data.placement)) { + data.styles.maxHeight = windowHeight - bottom; + } else { + data.styles.maxHeight = top; + } + } + + data.styles.width = width; + + return data; + }, + [enforceMaxHeight, maxHeight] + ); + + const createRenderInputComponent = useCallback( + (inputProps: RenderInputComponentProps) => { + return ( + + {({ ref }) => { + if (renderInputComponent) { + return renderInputComponent(inputProps, ref); + } + + return ( +
+ +
+ ); + }} +
+ ); + }, + [renderInputComponent] + ); + + const renderSuggestionsContainer = useCallback( + ({ containerProps, children }: RenderSuggestionsContainerParams) => { + return ( + + + {({ ref: popperRef, style, scheduleUpdate }) => { + updater.current = scheduleUpdate; + + return ( +
+
+ {children} +
+
+ ); + }} +
+
+ ); + }, + [minHeight, handleComputeMaxHeight] + ); + + const handleInputKeyDown = useCallback( + (event: KeyboardEvent) => { + if ( + event.key === 'Tab' && + suggestions.length && + suggestions[0] !== value + ) { + event.preventDefault(); + + if (value) { + onSuggestionSelected?.(event, { + suggestion: suggestions[0], + suggestionValue: value, + suggestionIndex: 0, + sectionIndex: null, + method: 'enter', + }); + } + } + }, + [value, suggestions, onSuggestionSelected] + ); + + const inputProps = { + className: classNames( + className, + hasError && styles.hasError, + hasWarning && styles.hasWarning + ), + name, + value, + placeholder, + autoComplete: 'off', + spellCheck: false, + onChange: onInputChange, + onKeyDown: onInputKeyDown || handleInputKeyDown, + onFocus: onInputFocus, + onBlur: onInputBlur, + }; + + const theme = { + container: inputContainerClassName, + containerOpen: styles.suggestionsContainerOpen, + suggestionsContainer: styles.suggestionsContainer, + suggestionsList: styles.suggestionsList, + suggestion: styles.suggestion, + suggestionHighlighted: styles.suggestionHighlighted, + }; + + useEffect(() => { + if (updater.current && suggestions !== previousSuggestions) { + updater.current(); + } + }, [suggestions, previousSuggestions]); + + return ( + + + + ); +} + +export default AutoSuggestInput; diff --git a/frontend/src/Components/Form/CaptchaInput.css b/frontend/src/Components/Form/CaptchaInput.css new file mode 100644 index 000000000..76c076834 --- /dev/null +++ b/frontend/src/Components/Form/CaptchaInput.css @@ -0,0 +1,23 @@ +.captchaInputWrapper { + display: flex; +} + +.input { + composes: input from '~Components/Form/Input.css'; +} + +.hasError { + composes: hasError from '~Components/Form/Input.css'; +} + +.hasWarning { + composes: hasWarning from '~Components/Form/Input.css'; +} + +.hasButton { + composes: hasButton from '~Components/Form/Input.css'; +} + +.recaptchaWrapper { + margin-top: 10px; +} diff --git a/frontend/src/Components/Form/CaptchaInput.css.d.ts b/frontend/src/Components/Form/CaptchaInput.css.d.ts new file mode 100644 index 000000000..b6844144e --- /dev/null +++ b/frontend/src/Components/Form/CaptchaInput.css.d.ts @@ -0,0 +1,12 @@ +// This file is automatically generated. +// Please do not change this file! +interface CssExports { + 'captchaInputWrapper': string; + 'hasButton': string; + 'hasError': string; + 'hasWarning': string; + 'input': string; + 'recaptchaWrapper': string; +} +export const cssExports: CssExports; +export default cssExports; diff --git a/frontend/src/Components/Form/CaptchaInput.tsx b/frontend/src/Components/Form/CaptchaInput.tsx new file mode 100644 index 000000000..d5a3f11f7 --- /dev/null +++ b/frontend/src/Components/Form/CaptchaInput.tsx @@ -0,0 +1,118 @@ +import classNames from 'classnames'; +import React, { useCallback, useEffect } from 'react'; +import ReCAPTCHA from 'react-google-recaptcha'; +import { useDispatch, useSelector } from 'react-redux'; +import AppState from 'App/State/AppState'; +import Icon from 'Components/Icon'; +import usePrevious from 'Helpers/Hooks/usePrevious'; +import { icons } from 'Helpers/Props'; +import { + getCaptchaCookie, + refreshCaptcha, + resetCaptcha, +} from 'Store/Actions/captchaActions'; +import { InputChanged } from 'typings/inputs'; +import FormInputButton from './FormInputButton'; +import TextInput from './TextInput'; +import styles from './CaptchaInput.css'; + +interface CaptchaInputProps { + className?: string; + name: string; + value?: string; + provider: string; + providerData: object; + hasError?: boolean; + hasWarning?: boolean; + refreshing: boolean; + siteKey?: string; + secretToken?: string; + onChange: (change: InputChanged) => unknown; +} + +function CaptchaInput({ + className = styles.input, + name, + value = '', + provider, + providerData, + hasError, + hasWarning, + refreshing, + siteKey, + secretToken, + onChange, +}: CaptchaInputProps) { + const { token } = useSelector((state: AppState) => state.captcha); + const dispatch = useDispatch(); + const previousToken = usePrevious(token); + + const handleCaptchaChange = useCallback( + (token: string | null) => { + // If the captcha has expired `captchaResponse` will be null. + // In the event it's null don't try to get the captchaCookie. + // TODO: Should we clear the cookie? or reset the captcha? + + if (!token) { + return; + } + + dispatch( + getCaptchaCookie({ + provider, + providerData, + captchaResponse: token, + }) + ); + }, + [provider, providerData, dispatch] + ); + + const handleRefreshPress = useCallback(() => { + dispatch(refreshCaptcha({ provider, providerData })); + }, [provider, providerData, dispatch]); + + useEffect(() => { + if (token && token !== previousToken) { + onChange({ name, value: token }); + } + }, [name, token, previousToken, onChange]); + + useEffect(() => { + dispatch(resetCaptcha()); + }, [dispatch]); + + return ( +
+
+ + + + + +
+ + {siteKey && secretToken ? ( +
+ +
+ ) : null} +
+ ); +} + +export default CaptchaInput; diff --git a/frontend/src/Components/Form/CheckInput.css b/frontend/src/Components/Form/CheckInput.css new file mode 100644 index 000000000..171121482 --- /dev/null +++ b/frontend/src/Components/Form/CheckInput.css @@ -0,0 +1,105 @@ +.container { + position: relative; + display: flex; + flex: 1 1 65%; + user-select: none; +} + +.label { + display: flex; + margin-bottom: 0; + min-height: 21px; + font-weight: normal; + cursor: pointer; +} + +.checkbox { + position: absolute; + opacity: 0; + cursor: pointer; + pointer-events: none; + + &:global(.isDisabled) { + cursor: not-allowed; + } +} + +.input { + flex: 1 0 auto; + margin-top: 7px; + margin-right: 5px; + width: 20px; + height: 20px; + border: 1px solid #ccc; + border-radius: 2px; + background-color: var(--white); + color: var(--white); + text-align: center; + line-height: 20px; +} + +.checkbox:focus + .input { + outline: 0; + border-color: var(--inputFocusBorderColor); + box-shadow: inset 0 1px 1px var(--inputBoxShadowColor), 0 0 8px var(--inputFocusBoxShadowColor); +} + +.dangerIsChecked { + border-color: var(--dangerColor); + background-color: var(--dangerColor); + + &.isDisabled { + opacity: 0.7; + } +} + +.primaryIsChecked { + border-color: var(--primaryColor); + background-color: var(--primaryColor); + + &.isDisabled { + opacity: 0.7; + } +} + +.successIsChecked { + border-color: var(--successColor); + background-color: var(--successColor); + + &.isDisabled { + opacity: 0.7; + } +} + +.warningIsChecked { + border-color: var(--warningColor); + background-color: var(--warningColor); + + &.isDisabled { + opacity: 0.7; + } +} + +.isNotChecked { + &.isDisabled { + border-color: var(--disabledCheckInputColor); + background-color: var(--disabledCheckInputColor); + opacity: 0.7; + } +} + +.isIndeterminate { + border-color: var(--gray); + background-color: var(--gray); +} + +.helpText { + composes: helpText from '~Components/Form/FormInputHelpText.css'; + + margin-top: 8px; + margin-left: 5px; +} + +.isDisabled { + cursor: not-allowed; +} diff --git a/frontend/src/Components/Form/CheckInput.css.d.ts b/frontend/src/Components/Form/CheckInput.css.d.ts new file mode 100644 index 000000000..bba6b63bb --- /dev/null +++ b/frontend/src/Components/Form/CheckInput.css.d.ts @@ -0,0 +1,18 @@ +// This file is automatically generated. +// Please do not change this file! +interface CssExports { + 'checkbox': string; + 'container': string; + 'dangerIsChecked': string; + 'helpText': string; + 'input': string; + 'isDisabled': string; + 'isIndeterminate': string; + 'isNotChecked': string; + 'label': string; + 'primaryIsChecked': string; + 'successIsChecked': string; + 'warningIsChecked': string; +} +export const cssExports: CssExports; +export default cssExports; diff --git a/frontend/src/Components/Form/CheckInput.tsx b/frontend/src/Components/Form/CheckInput.tsx new file mode 100644 index 000000000..b7080cfdd --- /dev/null +++ b/frontend/src/Components/Form/CheckInput.tsx @@ -0,0 +1,141 @@ +import classNames from 'classnames'; +import React, { SyntheticEvent, useCallback, useEffect, useRef } from 'react'; +import Icon from 'Components/Icon'; +import { icons } from 'Helpers/Props'; +import { Kind } from 'Helpers/Props/kinds'; +import { CheckInputChanged } from 'typings/inputs'; +import FormInputHelpText from './FormInputHelpText'; +import styles from './CheckInput.css'; + +interface ChangeEvent extends SyntheticEvent { + target: EventTarget & T; +} + +interface CheckInputProps { + className?: string; + containerClassName?: string; + name: string; + checkedValue?: boolean; + uncheckedValue?: boolean; + value?: string | boolean; + helpText?: string; + helpTextWarning?: string; + isDisabled?: boolean; + kind?: Extract; + onChange: (changes: CheckInputChanged) => void; +} + +function CheckInput(props: CheckInputProps) { + const { + className = styles.input, + containerClassName = styles.container, + name, + value, + checkedValue = true, + uncheckedValue = false, + helpText, + helpTextWarning, + isDisabled, + kind = 'primary', + onChange, + } = props; + + const inputRef = useRef(null); + + const isChecked = value === checkedValue; + const isUnchecked = value === uncheckedValue; + const isIndeterminate = !isChecked && !isUnchecked; + const isCheckClass: keyof typeof styles = `${kind}IsChecked`; + + const toggleChecked = useCallback( + (checked: boolean, shiftKey: boolean) => { + const newValue = checked ? checkedValue : uncheckedValue; + + if (value !== newValue) { + onChange({ + name, + value: newValue, + shiftKey, + }); + } + }, + [name, value, checkedValue, uncheckedValue, onChange] + ); + + const handleClick = useCallback( + (event: SyntheticEvent) => { + if (isDisabled) { + return; + } + + const shiftKey = event.nativeEvent.shiftKey; + const checked = !(inputRef.current?.checked ?? false); + + event.preventDefault(); + toggleChecked(checked, shiftKey); + }, + [isDisabled, toggleChecked] + ); + + const handleChange = useCallback( + (event: ChangeEvent) => { + const checked = event.target.checked; + const shiftKey = event.nativeEvent.shiftKey; + + toggleChecked(checked, shiftKey); + }, + [toggleChecked] + ); + + useEffect(() => { + if (!inputRef.current) { + return; + } + + inputRef.current.indeterminate = + value !== uncheckedValue && value !== checkedValue; + }, [value, uncheckedValue, checkedValue]); + + return ( +
+ +
+ ); +} + +export default CheckInput; diff --git a/frontend/src/Components/Form/Form.css b/frontend/src/Components/Form/Form.css new file mode 100644 index 000000000..52e79aec4 --- /dev/null +++ b/frontend/src/Components/Form/Form.css @@ -0,0 +1,3 @@ +.validationFailures { + margin-bottom: 20px; +} diff --git a/frontend/src/Components/Form/Form.css.d.ts b/frontend/src/Components/Form/Form.css.d.ts new file mode 100644 index 000000000..178f2fec1 --- /dev/null +++ b/frontend/src/Components/Form/Form.css.d.ts @@ -0,0 +1,7 @@ +// This file is automatically generated. +// Please do not change this file! +interface CssExports { + 'validationFailures': string; +} +export const cssExports: CssExports; +export default cssExports; diff --git a/frontend/src/Components/Form/Form.tsx b/frontend/src/Components/Form/Form.tsx new file mode 100644 index 000000000..d522019e7 --- /dev/null +++ b/frontend/src/Components/Form/Form.tsx @@ -0,0 +1,45 @@ +import React, { ReactNode } from 'react'; +import Alert from 'Components/Alert'; +import { kinds } from 'Helpers/Props'; +import { ValidationError, ValidationWarning } from 'typings/pending'; +import styles from './Form.css'; + +export interface FormProps { + children: ReactNode; + validationErrors?: ValidationError[]; + validationWarnings?: ValidationWarning[]; +} + +function Form({ + children, + validationErrors = [], + validationWarnings = [], +}: FormProps) { + return ( +
+ {validationErrors.length || validationWarnings.length ? ( +
+ {validationErrors.map((error, index) => { + return ( + + {error.errorMessage} + + ); + })} + + {validationWarnings.map((warning, index) => { + return ( + + {warning.errorMessage} + + ); + })} +
+ ) : null} + + {children} +
+ ); +} + +export default Form; diff --git a/frontend/src/Components/Form/FormGroup.css b/frontend/src/Components/Form/FormGroup.css new file mode 100644 index 000000000..ddce8863b --- /dev/null +++ b/frontend/src/Components/Form/FormGroup.css @@ -0,0 +1,28 @@ +.group { + display: flex; + margin-bottom: 20px; +} + +/* Sizes */ + +.extraSmall { + max-width: $formGroupExtraSmallWidth; +} + +.small { + max-width: $formGroupSmallWidth; +} + +.medium { + max-width: $formGroupMediumWidth; +} + +.large { + max-width: $formGroupLargeWidth; +} + +@media only screen and (max-width: $breakpointLarge) { + .group { + display: block; + } +} diff --git a/frontend/src/Components/Form/FormGroup.css.d.ts b/frontend/src/Components/Form/FormGroup.css.d.ts new file mode 100644 index 000000000..86145f643 --- /dev/null +++ b/frontend/src/Components/Form/FormGroup.css.d.ts @@ -0,0 +1,11 @@ +// This file is automatically generated. +// Please do not change this file! +interface CssExports { + 'extraSmall': string; + 'group': string; + 'large': string; + 'medium': string; + 'small': string; +} +export const cssExports: CssExports; +export default cssExports; diff --git a/frontend/src/Components/Form/FormGroup.tsx b/frontend/src/Components/Form/FormGroup.tsx new file mode 100644 index 000000000..1dd879897 --- /dev/null +++ b/frontend/src/Components/Form/FormGroup.tsx @@ -0,0 +1,43 @@ +import classNames from 'classnames'; +import React, { Children, ComponentPropsWithoutRef, ReactNode } from 'react'; +import { Size } from 'Helpers/Props/sizes'; +import styles from './FormGroup.css'; + +interface FormGroupProps extends ComponentPropsWithoutRef<'div'> { + className?: string; + children: ReactNode; + size?: Extract; + advancedSettings?: boolean; + isAdvanced?: boolean; +} + +function FormGroup(props: FormGroupProps) { + const { + className = styles.group, + children, + size = 'small', + advancedSettings = false, + isAdvanced = false, + ...otherProps + } = props; + + if (!advancedSettings && isAdvanced) { + return null; + } + + const childProps = isAdvanced ? { isAdvanced } : {}; + + return ( +
+ {Children.map(children, (child) => { + if (!React.isValidElement(child)) { + return child; + } + + return React.cloneElement(child, childProps); + })} +
+ ); +} + +export default FormGroup; diff --git a/frontend/src/Components/Form/FormInputButton.css b/frontend/src/Components/Form/FormInputButton.css new file mode 100644 index 000000000..da4888f09 --- /dev/null +++ b/frontend/src/Components/Form/FormInputButton.css @@ -0,0 +1,12 @@ +.button { + composes: button from '~Components/Link/Button.css'; + + border-left: none; + border-top-left-radius: 0; + border-bottom-left-radius: 0; +} + +.middleButton { + border-top-right-radius: 0; + border-bottom-right-radius: 0; +} diff --git a/frontend/src/Components/Form/FormInputButton.css.d.ts b/frontend/src/Components/Form/FormInputButton.css.d.ts new file mode 100644 index 000000000..d469cdfe3 --- /dev/null +++ b/frontend/src/Components/Form/FormInputButton.css.d.ts @@ -0,0 +1,8 @@ +// This file is automatically generated. +// Please do not change this file! +interface CssExports { + 'button': string; + 'middleButton': string; +} +export const cssExports: CssExports; +export default cssExports; diff --git a/frontend/src/Components/Form/FormInputButton.tsx b/frontend/src/Components/Form/FormInputButton.tsx new file mode 100644 index 000000000..e5149ab14 --- /dev/null +++ b/frontend/src/Components/Form/FormInputButton.tsx @@ -0,0 +1,39 @@ +import classNames from 'classnames'; +import React from 'react'; +import Button, { ButtonProps } from 'Components/Link/Button'; +import SpinnerButton from 'Components/Link/SpinnerButton'; +import { kinds } from 'Helpers/Props'; +import styles from './FormInputButton.css'; + +export interface FormInputButtonProps extends ButtonProps { + canSpin?: boolean; + isLastButton?: boolean; +} + +function FormInputButton({ + className = styles.button, + canSpin = false, + isLastButton = true, + kind = kinds.PRIMARY, + ...otherProps +}: FormInputButtonProps) { + if (canSpin) { + return ( + + ); + } + + return ( +