├── .dockerignore ├── .gitattributes ├── .github ├── ISSUE_TEMPLATE │ ├── bug_report.md │ └── feature_request.md └── workflows │ ├── docker-develop-publish.yml │ ├── docker-image.yml │ └── docker-latest-publish.yml ├── .gitignore ├── .vscode └── settings.json ├── CONFIGURATION.md ├── Dockerfile ├── LICENSE ├── README.md ├── config.example.json ├── eraserr.py ├── renovate.json ├── requirements.txt └── src ├── clients ├── overseerr.py ├── plex.py ├── radarr.py └── sonarr.py ├── config.py ├── jobs.py ├── logger.py ├── main.py ├── models └── dynamicmedia.py └── util.py /.dockerignore: -------------------------------------------------------------------------------- 1 | .env 2 | config.json -------------------------------------------------------------------------------- /.gitattributes: -------------------------------------------------------------------------------- 1 | # Auto detect text files and perform LF normalization 2 | * text=auto 3 | -------------------------------------------------------------------------------- /.github/ISSUE_TEMPLATE/bug_report.md: -------------------------------------------------------------------------------- 1 | --- 2 | name: Bug report 3 | about: Create a report to help us improve 4 | title: '' 5 | labels: '' 6 | assignees: '' 7 | 8 | --- 9 | 10 | **Describe the bug** 11 | A clear and concise description of what the bug is. 12 | 13 | **To Reproduce** 14 | Steps to reproduce the behavior: 15 | 1. Go to '...' 16 | 2. Click on '....' 17 | 3. Scroll down to '....' 18 | 4. See error 19 | 20 | **Expected behavior** 21 | A clear and concise description of what you expected to happen. 22 | 23 | **Screenshots** 24 | If applicable, add screenshots to help explain your problem. 25 | 26 | **Desktop (please complete the following information):** 27 | - OS: [e.g. iOS] 28 | - Browser [e.g. chrome, safari] 29 | - Version [e.g. 22] 30 | 31 | **Smartphone (please complete the following information):** 32 | - Device: [e.g. iPhone6] 33 | - OS: [e.g. iOS8.1] 34 | - Browser [e.g. stock browser, safari] 35 | - Version [e.g. 22] 36 | 37 | **Additional context** 38 | Add any other context about the problem here. 39 | -------------------------------------------------------------------------------- /.github/ISSUE_TEMPLATE/feature_request.md: -------------------------------------------------------------------------------- 1 | --- 2 | name: Feature request 3 | about: Suggest an idea for this project 4 | title: '' 5 | labels: '' 6 | assignees: '' 7 | 8 | --- 9 | 10 | **Is your feature request related to a problem? Please describe.** 11 | A clear and concise description of what the problem is. Ex. I'm always frustrated when [...] 12 | 13 | **Describe the solution you'd like** 14 | A clear and concise description of what you want to happen. 15 | 16 | **Describe alternatives you've considered** 17 | A clear and concise description of any alternative solutions or features you've considered. 18 | 19 | **Additional context** 20 | Add any other context or screenshots about the feature request here. 21 | -------------------------------------------------------------------------------- /.github/workflows/docker-develop-publish.yml: -------------------------------------------------------------------------------- 1 | name: Publish Develop Docker Image 2 | 3 | on: 4 | push: 5 | branches: [ "develop" ] 6 | 7 | jobs: 8 | push_to_registry: 9 | name: Push Docker image to Docker Hub 10 | runs-on: ubuntu-latest 11 | steps: 12 | - name: Check out the repo 13 | uses: actions/checkout@v4 14 | 15 | - name: Log in to Docker Hub 16 | uses: docker/login-action@v3 17 | with: 18 | username: ${{ secrets.DOCKER_USERNAME }} 19 | password: ${{ secrets.DOCKER_PASSWORD }} 20 | 21 | - name: Extract metadata (tags, labels) for Docker 22 | id: meta 23 | uses: docker/metadata-action@v5 24 | with: 25 | images: ecsouthwick/eraserr 26 | 27 | - name: Build and push Docker image 28 | uses: docker/build-push-action@v5 29 | with: 30 | context: . 31 | push: true 32 | tags: ${{ steps.meta.outputs.tags }} 33 | labels: ${{ steps.meta.outputs.labels }} 34 | -------------------------------------------------------------------------------- /.github/workflows/docker-image.yml: -------------------------------------------------------------------------------- 1 | name: Build Docker Image 2 | 3 | on: 4 | push: 5 | branches: [ "main", "develop" ] 6 | pull_request: 7 | branches: [ "main", "develop" ] 8 | 9 | jobs: 10 | 11 | build: 12 | 13 | runs-on: ubuntu-latest 14 | 15 | steps: 16 | - uses: actions/checkout@v4 17 | - name: Build the Docker image 18 | run: docker build . --file Dockerfile --tag ecsouthwick/eraserr 19 | -------------------------------------------------------------------------------- /.github/workflows/docker-latest-publish.yml: -------------------------------------------------------------------------------- 1 | # This workflow uses actions that are not certified by GitHub. 2 | # They are provided by a third-party and are governed by 3 | # separate terms of service, privacy policy, and support 4 | # documentation. 5 | 6 | # GitHub recommends pinning actions to a commit SHA. 7 | # To get a newer version, you will need to update the SHA. 8 | # You can also reference a tag or branch, but the action may change without warning. 9 | 10 | name: Publish Latest Docker Image 11 | 12 | on: 13 | push: 14 | branches: [ "main" ] 15 | 16 | jobs: 17 | push_to_registry: 18 | name: Push Docker image to Docker Hub 19 | runs-on: ubuntu-latest 20 | steps: 21 | - name: Check out the repo 22 | uses: actions/checkout@v4 23 | 24 | - name: Log in to Docker Hub 25 | uses: docker/login-action@v3 26 | with: 27 | username: ${{ secrets.DOCKER_USERNAME }} 28 | password: ${{ secrets.DOCKER_PASSWORD }} 29 | 30 | - name: Extract metadata (tags, labels) for Docker 31 | id: meta 32 | uses: docker/metadata-action@v5 33 | with: 34 | images: ecsouthwick/eraserr 35 | 36 | - name: Build and push Docker image 37 | uses: docker/build-push-action@v5 38 | with: 39 | context: . 40 | push: true 41 | tags: ecsouthwick/eraserr:latest 42 | labels: ${{ steps.meta.outputs.labels }} 43 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # Byte-compiled / optimized / DLL files 2 | __pycache__/ 3 | *.py[cod] 4 | *$py.class 5 | 6 | # C extensions 7 | *.so 8 | 9 | # Distribution / packaging 10 | .Python 11 | build/ 12 | develop-eggs/ 13 | dist/ 14 | downloads/ 15 | eggs/ 16 | .eggs/ 17 | lib/ 18 | lib64/ 19 | parts/ 20 | sdist/ 21 | var/ 22 | wheels/ 23 | share/python-wheels/ 24 | *.egg-info/ 25 | .installed.cfg 26 | *.egg 27 | MANIFEST 28 | 29 | # PyInstaller 30 | # Usually these files are written by a python script from a template 31 | # before PyInstaller builds the exe, so as to inject date/other infos into it. 32 | *.manifest 33 | *.spec 34 | 35 | # Installer logs 36 | pip-log.txt 37 | pip-delete-this-directory.txt 38 | 39 | # Unit test / coverage reports 40 | htmlcov/ 41 | .tox/ 42 | .nox/ 43 | .coverage 44 | .coverage.* 45 | .cache 46 | nosetests.xml 47 | coverage.xml 48 | *.cover 49 | *.py,cover 50 | .hypothesis/ 51 | .pytest_cache/ 52 | cover/ 53 | 54 | # Translations 55 | *.mo 56 | *.pot 57 | 58 | # Django stuff: 59 | *.log 60 | *.log.* 61 | local_settings.py 62 | db.sqlite3 63 | db.sqlite3-journal 64 | 65 | # Flask stuff: 66 | instance/ 67 | .webassets-cache 68 | 69 | # Scrapy stuff: 70 | .scrapy 71 | 72 | # Sphinx documentation 73 | docs/_build/ 74 | 75 | # PyBuilder 76 | .pybuilder/ 77 | target/ 78 | 79 | # Jupyter Notebook 80 | .ipynb_checkpoints 81 | 82 | # IPython 83 | profile_default/ 84 | ipython_config.py 85 | 86 | # pyenv 87 | # For a library or package, you might want to ignore these files since the code is 88 | # intended to run in multiple environments; otherwise, check them in: 89 | # .python-version 90 | 91 | # pipenv 92 | # According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control. 93 | # However, in case of collaboration, if having platform-specific dependencies or dependencies 94 | # having no cross-platform support, pipenv may install dependencies that don't work, or not 95 | # install all needed dependencies. 96 | #Pipfile.lock 97 | 98 | # poetry 99 | # Similar to Pipfile.lock, it is generally recommended to include poetry.lock in version control. 100 | # This is especially recommended for binary packages to ensure reproducibility, and is more 101 | # commonly ignored for libraries. 102 | # https://python-poetry.org/docs/basic-usage/#commit-your-poetrylock-file-to-version-control 103 | #poetry.lock 104 | 105 | # PEP 582; used by e.g. github.com/David-OConnor/pyflow 106 | __pypackages__/ 107 | 108 | # Celery stuff 109 | celerybeat-schedule 110 | celerybeat.pid 111 | 112 | # SageMath parsed files 113 | *.sage.py 114 | 115 | # Environments 116 | .env 117 | .venv 118 | env/ 119 | venv/ 120 | ENV/ 121 | env.bak/ 122 | venv.bak/ 123 | 124 | # Spyder project settings 125 | .spyderproject 126 | .spyproject 127 | 128 | # Rope project settings 129 | .ropeproject 130 | 131 | # mkdocs documentation 132 | /site 133 | 134 | # mypy 135 | .mypy_cache/ 136 | .dmypy.json 137 | dmypy.json 138 | 139 | # Pyre type checker 140 | .pyre/ 141 | 142 | # pytype static type analyzer 143 | .pytype/ 144 | 145 | # Cython debug symbols 146 | cython_debug/ 147 | 148 | # PyCharm 149 | # JetBrains specific template is maintainted in a separate JetBrains.gitignore that can 150 | # be found at https://github.com/github/gitignore/blob/main/Global/JetBrains.gitignore 151 | # and can be added to the global gitignore or merged into this file. For a more nuclear 152 | # option (not recommended) you can uncomment the following to ignore the entire idea folder. 153 | #.idea/ 154 | config.json 155 | -------------------------------------------------------------------------------- /.vscode/settings.json: -------------------------------------------------------------------------------- 1 | { 2 | "[python]": { 3 | "editor.defaultFormatter": "ms-python.black-formatter" 4 | }, 5 | "python.formatting.provider": "black" 6 | } -------------------------------------------------------------------------------- /CONFIGURATION.md: -------------------------------------------------------------------------------- 1 | # Configuration 2 | This guide contains all the information you need to configure `Eraserr` using a `config.json` file. An example file of the configuration can be found at [config.json.example](config.example.json). 3 | 4 | ## Table of Contents 5 | - [General Settings](#general-settings) 6 | - [Dry Run](#dry-run) 7 | - [Log Level](#log-level) 8 | - [Schedule Interval](#schedule-interval) 9 | - [Plex](#plex) 10 | - [Base URL](#base-url) 11 | - [Token](#token) 12 | - [Radarr](#radarr) 13 | - [Enabled](#enabled) 14 | - [API Key](#api-key) 15 | - [Base URL](#base-url-1) 16 | - [Exempt Tag Names](#exempt-tag-names) 17 | - [Watched Deletion Threshold](#watched-deletion-threshold) 18 | - [Unwatched Deletion Threshold](#unwatched-deletion-threshold) 19 | - [Sonarr](#sonarr) 20 | - [Enabled](#enabled-1) 21 | - [API Key](#api-key-1) 22 | - [Base URL](#base-url-2) 23 | - [Monitor Continuing Series](#monitor-continuing-series) 24 | - [Dynamic Load](#dynamic-load) 25 | - [Enabled](#enabled-2) 26 | - [Episodes to Load](#episodes-to-load) 27 | - [Episodes to Keep](#episodes-to-keep) 28 | - [Watched Deletion Threshold](#watched-deletion-threshold-1) 29 | - [Schedule Interval](#schedule-interval) 30 | - [Exempt Tag Names](#exempt-tag-names-1) 31 | - [Watched Deletion Threshold](#watched-deletion-threshold-2) 32 | - [Unwatched Deletion Threshold](#unwatched-deletion-threshold-1) 33 | - [Overseerr](#overseerr) 34 | - [Enabled](#enabled-3) 35 | - [API Key](#api-key-2) 36 | - [Base URL](#base-url-3) 37 | - [Fetch Limit](#fetch-limit) 38 | - [Experimental](#experimental) 39 | - [Free Space](#free-space) 40 | - [Enabled](#enabled-4) 41 | - [Minimum Free Space Percentage](#minimum-free-space-percentage) 42 | - [Path](#path) 43 | - [Prevent Age-Based Deletion](#prevent-age-based-deletion) 44 | - [Prevent Dynamic Load](#prevent-dynamic-load) 45 | - [Progressive Deletion](#progressive-deletion) 46 | - [Enabled](#enabled-5) 47 | - [Maximum Deletion Cycles](#maximum-deletion-cycles) 48 | - [Threshold Reduction Per Cycle](#threshold-reduction-per-cycle) 49 | 50 | ## General Settings 51 | 52 | ### Dry Run 53 | 54 | ```json 55 | "dry_run": true 56 | ``` 57 | 58 | Set to `true` for a dry run. The program will log the actions it would take without making changes. Set to `false` to enable live mode where changes will be made. Update the `dry_run` value as per your requirements. 59 | 60 | ### Log Level 61 | 62 | ```json 63 | "log_level": "INFO" 64 | ``` 65 | 66 | Set the log level for the application. Valid values are "INFO", "DEBUG", "WARN", "ERROR". Update the `log_level` value as per your requirements. 67 | 68 | ### Schedule Interval 69 | 70 | ```json 71 | "schedule_interval": "1d" 72 | ``` 73 | 74 | Set the interval at which the script runs by replacing the `schedule_interval` value. The value should be in the format `` (days, hours, minutes, seconds). 75 | 76 | ## Plex 77 | 78 | ```json 79 | "plex": { 80 | "base_url": "https://plex.domain.com", 81 | "token": "" 82 | } 83 | ``` 84 | 85 | ### Base URL 86 | Update the `base_url` with your Plex base URL. 87 | 88 | ### Token 89 | Replace the empty `token` value with your Plex token. 90 | 91 | ## Radarr 92 | 93 | ```json 94 | "radarr": { 95 | "enabled": true, 96 | "api_key": "", 97 | "base_url": "https://radarr.domain.com/api/v3", 98 | "exempt_tag_names": [ 99 | "exempt-from-auto-delete", 100 | "some-other-tag" 101 | ], 102 | "watched_deletion_threshold": "180d", 103 | "unwatched_deletion_threshold": "30d" 104 | } 105 | ``` 106 | 107 | ### Enabled 108 | Set to `true` to enable Radarr integration. Set to `false` to disable it. 109 | 110 | ### API Key 111 | Replace the empty `api_key` value with your Radarr API Key. 112 | 113 | ### Base URL 114 | Update the `base_url` with your Radarr base URL. 115 | 116 | ### Exempt Tag Names 117 | Set tag names to exempt from automatic deletion by updating the `exempt_tag_names` array. 118 | 119 | ### Watched Deletion Threshold 120 | Set the threshold for watched media deletion by replacing the `watched_deletion_threshold` value. The value should be in the format `` (days, hours, minutes, seconds). 121 | 122 | ### Unwatched Deletion Threshold 123 | Set the threshold for unwatched media deletion by replacing the `unwatched_deletion_threshold` value. The value should be in the format `` (days, hours, minutes, seconds). 124 | 125 | ## Sonarr 126 | 127 | ```json 128 | "sonarr": { 129 | "enabled": true, 130 | "api_key": "", 131 | "base_url": "https://sonarr.domain.com/api/v3", 132 | "monitor_continuing_series": true, 133 | "dynamic_load": { 134 | "enabled": false, 135 | "episodes_to_load": 3, 136 | "episodes_to_keep": 3, 137 | "watched_deletion_threshold": "30d", 138 | "schedule_interval": "5m" 139 | }, 140 | "exempt_tag_names": [ 141 | "exempt-from-auto-delete", 142 | "some-other-tag" 143 | ], 144 | "watched_deletion_threshold": "180d", 145 | "unwatched_deletion_threshold": "30d" 146 | } 147 | ``` 148 | 149 | ### Enabled 150 | Set to `true` to enable Sonarr integration. Set to `false` to disable it. 151 | 152 | ### API Key 153 | Replace the empty `api_key` value with your Sonarr API Key. 154 | 155 | ### Base URL 156 | Update the `base_url` with your Sonarr base URL. 157 | 158 | ### Monitor Continuing Series 159 | Set to `true` if you want to monitor continuing series instead of deleting it from Sonarr so that new seasons are fetched. 160 | 161 | ### Dynamic Load 162 | 163 | Configure the dynamic load settings to efficiently manage your media storage on the Plex server. This feature preloads episodes ahead of the current viewing point and deletes watched episodes, saving substantial storage space. It considers the viewing patterns of multiple users to prevent premature deletion of episodes being watched concurrently. 164 | 165 | Here is an example of `episodes_to_load` = 3 and `episodes_to_keep` = 2 and you are viewing the first season. The first number of `episodes_to_keep` of a series (Season 1) will _always_ be kept. This means that deletion will only kick in when you reach E6 because E1 and E2 are protected, and E4 and E5 are the 2 episodes prior to E6, so only E3 is eligible for deletion in that scenario. 166 | 167 | ![image](https://github.com/everettsouthwick/Eraserr/assets/8216991/2e6f972c-de55-48a6-afb0-be1a49499f66) 168 | 169 | #### Enabled 170 | Toggle this setting to activate or deactivate the dynamic load feature. 171 | 172 | #### Episodes to Load 173 | Specify the number of future episodes to preload. When a user starts watching a TV show, it will download the specified number of episodes ahead of where they are currently watching. 174 | 175 | #### Episodes to Keep 176 | Specify the minimum number of episodes to retain. When a user starts watching a TV show, it will delete the specified number of episodes behind of where they are currently watching. 177 | 178 | #### Watched Deletion Threshold 179 | Set the timeframe to consider multiple users' viewing patterns before deleting any episodes, preventing the removal of episodes being watched by different users within the specified period. The value should be in the format `` (days, hours, minutes, seconds). 180 | 181 | #### Schedule Interval 182 | Set the interval at which dynamic load runs by replacing the `schedule_interval` value. The value should be in the format `` (days, hours, minutes, seconds). 183 | 184 | #### Additional Information 185 | Utilize the exempt tags to exclude specific series from dynamic loading, ensuring they remain available for repeated viewing. 186 | 187 | ### Exempt Tag Names 188 | Set tag names to exempt from automatic deletion by updating the `exempt_tag_names` array. 189 | 190 | ### Watched Deletion Threshold 191 | Set the threshold for watched media deletion by replacing the `watched_deletion_threshold` value. The value should be in the format `` (days, hours, minutes, seconds). 192 | 193 | ### Unwatched Deletion Threshold 194 | Set the threshold for unwatched media deletion by replacing the `unwatched_deletion_threshold` value. The value should be in the format `` (days, hours, minutes, seconds). 195 | 196 | ## Overseerr 197 | 198 | ```json 199 | "overseerr": { 200 | "enabled": true, 201 | "api_key": "", 202 | "base_url": "https://overseerr.domain.com/api/v1", 203 | "fetch_limit": 20 204 | } 205 | ``` 206 | 207 | ### Enabled 208 | Set to `true` to enable Overseerr integration. Set to `false` to disable it. 209 | 210 | ### API Key 211 | Replace the empty `api_key` value with your Overseerr API Key. 212 | 213 | ### Base URL 214 | Update the `base_url` with your Overseerr base URL. 215 | 216 | ### Fetch Limit 217 | Set the number of results to fetch from Overseerr by replacing the `fetch_limit` value. 218 | 219 | ## Experimental 220 | 221 | The experimental section contains configurations that are in the testing phase. These settings may be subject to changes and updates. Use them at your own risk. 222 | 223 | ### Free Space 224 | 225 | ```json 226 | "experimental": { 227 | "free_space": { 228 | "enabled": false, 229 | "minimum_free_space_percentage": 20, 230 | "path": "/mnt/local/Media", 231 | "prevent_age_based_deletion": true, 232 | "prevent_dynamic_load": true, 233 | "progressive_deletion": { 234 | "enabled": false, 235 | "maximum_deletion_cycles": 0, 236 | "threshold_reduction_per_cycle": "1d" 237 | } 238 | } 239 | } 240 | ``` 241 | 242 | #### Enabled 243 | 244 | ```json 245 | "enabled": false 246 | ``` 247 | 248 | Toggle this setting to enable or disable the free space feature. When enabled, the program will monitor the specified path to ensure that the minimum free space threshold is maintained. 249 | 250 | **Note**: This feature is experimental and might not work as expected in all scenarios. It is recommended to use it with caution and monitor its behavior closely to prevent any unintended data loss. 251 | 252 | #### Minimum Free Space Percentage 253 | 254 | ```json 255 | "minimum_free_space_percentage": 20 256 | ``` 257 | 258 | Define the minimum free space as a percentage of the total space that should be maintained in the specified path. The program will attempt to free up space if the available space falls below this threshold. The value should be between 0 and 100, representing the percentage of free space to maintain. 259 | 260 | #### Path 261 | 262 | ```json 263 | "path": "/mnt/local/Media" 264 | ``` 265 | 266 | Specify the path that should be monitored for free space. Ensure to update this with the correct path where your media files are stored. 267 | 268 | #### Prevent Age-Based Deletion 269 | 270 | ```json 271 | "prevent_age_based_deletion": true 272 | ``` 273 | 274 | When enabled, this setting prevents the deletion of files based on their age, overriding the traditional age-based deletion mechanism. This is to ensure that the free space feature does not delete files that have surpassed a certain age threshold, helping to maintain the minimum free space requirement without compromising older files. 275 | 276 | #### Prevent Dynamic Load 277 | 278 | ```json 279 | "prevent_dynamic_load": true 280 | ``` 281 | 282 | This setting, when enabled, prevents the dynamic load feature from functioning if the free space is above the minimum threshold. This is to avoid unnecessary loading and deletion of files, ensuring that the system maintains a healthy free space level without overloading the storage with new files. 283 | 284 | #### Progressive Deletion 285 | 286 | Progressive deletion initiates a systematic process that lowers the deletion thresholds in each cycle, either until the free space exceeds the minimum threshold or until the maximum number of cycles (defined by `maximum_deletion_cycles`) is reached. 287 | 288 | ##### Enabled 289 | 290 | ```json 291 | "enabled": true 292 | ``` 293 | 294 | By setting this to true, you activate the progressive deletion process. This methodical approach to file deletion helps maintain the minimum free space threshold by recursively deleting files, reducing the deletion thresholds step by step in each cycle. It's a potent feature that can potentially remove a significant number of files in a short period, so it should be used with caution. Users are advised to monitor its behavior closely to prevent unintended data loss. 295 | 296 | **Note**: This feature is powerful and can potentially delete a large number of files in a short period. It is recommended to use this feature judiciously and to monitor its behavior closely to prevent unintended data loss. 297 | 298 | ##### Maximum Deletion Cycles 299 | 300 | ```json 301 | "maximum_deletion_cycles": 14 302 | ``` 303 | 304 | This parameter sets a limit on the number of recursive deletion cycles the system can execute during a progressive deletion operation. It serves as a protective measure to prevent excessive deletions, halting the operation after the specified number of cycles, even if the minimum free space threshold hasn't been achieved. The value should be an integer representing the maximum number of deletion cycles permitted. 305 | 306 | ##### Threshold Reduction Per Cycle 307 | 308 | ```json 309 | "threshold_reduction_per_cycle": "1d" 310 | ``` 311 | 312 | This parameter specifies the amount by which the deletion threshold is reduced in each cycle. By lowering the deletion thresholds by the specified time interval (in this case, 1 day) during each cycle, the system can progressively free up more space. The value should be formatted as `` (days, hours, minutes, seconds), representing the time interval for threshold reduction. 313 | -------------------------------------------------------------------------------- /Dockerfile: -------------------------------------------------------------------------------- 1 | FROM python:alpine 2 | 3 | WORKDIR /app 4 | 5 | ENV PYTHONUNBUFFERED 1 6 | 7 | COPY . . 8 | RUN pip3 install --no-cache-dir -r requirements.txt 9 | 10 | CMD ["python3", "eraserr.py"] -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | GNU GENERAL PUBLIC LICENSE 2 | Version 3, 29 June 2007 3 | 4 | Copyright (C) 2007 Free Software Foundation, Inc. 5 | Everyone is permitted to copy and distribute verbatim copies 6 | of this license document, but changing it is not allowed. 7 | 8 | Preamble 9 | 10 | The GNU General Public License is a free, copyleft license for 11 | software and other kinds of works. 12 | 13 | The licenses for most software and other practical works are designed 14 | to take away your freedom to share and change the works. By contrast, 15 | the GNU General Public License is intended to guarantee your freedom to 16 | share and change all versions of a program--to make sure it remains free 17 | software for all its users. We, the Free Software Foundation, use the 18 | GNU General Public License for most of our software; it applies also to 19 | any other work released this way by its authors. You can apply it to 20 | your programs, too. 21 | 22 | When we speak of free software, we are referring to freedom, not 23 | price. Our General Public Licenses are designed to make sure that you 24 | have the freedom to distribute copies of free software (and charge for 25 | them if you wish), that you receive source code or can get it if you 26 | want it, that you can change the software or use pieces of it in new 27 | free programs, and that you know you can do these things. 28 | 29 | To protect your rights, we need to prevent others from denying you 30 | these rights or asking you to surrender the rights. Therefore, you have 31 | certain responsibilities if you distribute copies of the software, or if 32 | you modify it: responsibilities to respect the freedom of others. 33 | 34 | For example, if you distribute copies of such a program, whether 35 | gratis or for a fee, you must pass on to the recipients the same 36 | freedoms that you received. You must make sure that they, too, receive 37 | or can get the source code. And you must show them these terms so they 38 | know their rights. 39 | 40 | Developers that use the GNU GPL protect your rights with two steps: 41 | (1) assert copyright on the software, and (2) offer you this License 42 | giving you legal permission to copy, distribute and/or modify it. 43 | 44 | For the developers' and authors' protection, the GPL clearly explains 45 | that there is no warranty for this free software. For both users' and 46 | authors' sake, the GPL requires that modified versions be marked as 47 | changed, so that their problems will not be attributed erroneously to 48 | authors of previous versions. 49 | 50 | Some devices are designed to deny users access to install or run 51 | modified versions of the software inside them, although the manufacturer 52 | can do so. This is fundamentally incompatible with the aim of 53 | protecting users' freedom to change the software. The systematic 54 | pattern of such abuse occurs in the area of products for individuals to 55 | use, which is precisely where it is most unacceptable. Therefore, we 56 | have designed this version of the GPL to prohibit the practice for those 57 | products. If such problems arise substantially in other domains, we 58 | stand ready to extend this provision to those domains in future versions 59 | of the GPL, as needed to protect the freedom of users. 60 | 61 | Finally, every program is threatened constantly by software patents. 62 | States should not allow patents to restrict development and use of 63 | software on general-purpose computers, but in those that do, we wish to 64 | avoid the special danger that patents applied to a free program could 65 | make it effectively proprietary. To prevent this, the GPL assures that 66 | patents cannot be used to render the program non-free. 67 | 68 | The precise terms and conditions for copying, distribution and 69 | modification follow. 70 | 71 | TERMS AND CONDITIONS 72 | 73 | 0. Definitions. 74 | 75 | "This License" refers to version 3 of the GNU General Public License. 76 | 77 | "Copyright" also means copyright-like laws that apply to other kinds of 78 | works, such as semiconductor masks. 79 | 80 | "The Program" refers to any copyrightable work licensed under this 81 | License. Each licensee is addressed as "you". "Licensees" and 82 | "recipients" may be individuals or organizations. 83 | 84 | To "modify" a work means to copy from or adapt all or part of the work 85 | in a fashion requiring copyright permission, other than the making of an 86 | exact copy. The resulting work is called a "modified version" of the 87 | earlier work or a work "based on" the earlier work. 88 | 89 | A "covered work" means either the unmodified Program or a work based 90 | on the Program. 91 | 92 | To "propagate" a work means to do anything with it that, without 93 | permission, would make you directly or secondarily liable for 94 | infringement under applicable copyright law, except executing it on a 95 | computer or modifying a private copy. Propagation includes copying, 96 | distribution (with or without modification), making available to the 97 | public, and in some countries other activities as well. 98 | 99 | To "convey" a work means any kind of propagation that enables other 100 | parties to make or receive copies. Mere interaction with a user through 101 | a computer network, with no transfer of a copy, is not conveying. 102 | 103 | An interactive user interface displays "Appropriate Legal Notices" 104 | to the extent that it includes a convenient and prominently visible 105 | feature that (1) displays an appropriate copyright notice, and (2) 106 | tells the user that there is no warranty for the work (except to the 107 | extent that warranties are provided), that licensees may convey the 108 | work under this License, and how to view a copy of this License. If 109 | the interface presents a list of user commands or options, such as a 110 | menu, a prominent item in the list meets this criterion. 111 | 112 | 1. Source Code. 113 | 114 | The "source code" for a work means the preferred form of the work 115 | for making modifications to it. "Object code" means any non-source 116 | form of a work. 117 | 118 | A "Standard Interface" means an interface that either is an official 119 | standard defined by a recognized standards body, or, in the case of 120 | interfaces specified for a particular programming language, one that 121 | is widely used among developers working in that language. 122 | 123 | The "System Libraries" of an executable work include anything, other 124 | than the work as a whole, that (a) is included in the normal form of 125 | packaging a Major Component, but which is not part of that Major 126 | Component, and (b) serves only to enable use of the work with that 127 | Major Component, or to implement a Standard Interface for which an 128 | implementation is available to the public in source code form. A 129 | "Major Component", in this context, means a major essential component 130 | (kernel, window system, and so on) of the specific operating system 131 | (if any) on which the executable work runs, or a compiler used to 132 | produce the work, or an object code interpreter used to run it. 133 | 134 | The "Corresponding Source" for a work in object code form means all 135 | the source code needed to generate, install, and (for an executable 136 | work) run the object code and to modify the work, including scripts to 137 | control those activities. However, it does not include the work's 138 | System Libraries, or general-purpose tools or generally available free 139 | programs which are used unmodified in performing those activities but 140 | which are not part of the work. For example, Corresponding Source 141 | includes interface definition files associated with source files for 142 | the work, and the source code for shared libraries and dynamically 143 | linked subprograms that the work is specifically designed to require, 144 | such as by intimate data communication or control flow between those 145 | subprograms and other parts of the work. 146 | 147 | The Corresponding Source need not include anything that users 148 | can regenerate automatically from other parts of the Corresponding 149 | Source. 150 | 151 | The Corresponding Source for a work in source code form is that 152 | same work. 153 | 154 | 2. Basic Permissions. 155 | 156 | All rights granted under this License are granted for the term of 157 | copyright on the Program, and are irrevocable provided the stated 158 | conditions are met. This License explicitly affirms your unlimited 159 | permission to run the unmodified Program. The output from running a 160 | covered work is covered by this License only if the output, given its 161 | content, constitutes a covered work. This License acknowledges your 162 | rights of fair use or other equivalent, as provided by copyright law. 163 | 164 | You may make, run and propagate covered works that you do not 165 | convey, without conditions so long as your license otherwise remains 166 | in force. You may convey covered works to others for the sole purpose 167 | of having them make modifications exclusively for you, or provide you 168 | with facilities for running those works, provided that you comply with 169 | the terms of this License in conveying all material for which you do 170 | not control copyright. Those thus making or running the covered works 171 | for you must do so exclusively on your behalf, under your direction 172 | and control, on terms that prohibit them from making any copies of 173 | your copyrighted material outside their relationship with you. 174 | 175 | Conveying under any other circumstances is permitted solely under 176 | the conditions stated below. Sublicensing is not allowed; section 10 177 | makes it unnecessary. 178 | 179 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law. 180 | 181 | No covered work shall be deemed part of an effective technological 182 | measure under any applicable law fulfilling obligations under article 183 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or 184 | similar laws prohibiting or restricting circumvention of such 185 | measures. 186 | 187 | When you convey a covered work, you waive any legal power to forbid 188 | circumvention of technological measures to the extent such circumvention 189 | is effected by exercising rights under this License with respect to 190 | the covered work, and you disclaim any intention to limit operation or 191 | modification of the work as a means of enforcing, against the work's 192 | users, your or third parties' legal rights to forbid circumvention of 193 | technological measures. 194 | 195 | 4. Conveying Verbatim Copies. 196 | 197 | You may convey verbatim copies of the Program's source code as you 198 | receive it, in any medium, provided that you conspicuously and 199 | appropriately publish on each copy an appropriate copyright notice; 200 | keep intact all notices stating that this License and any 201 | non-permissive terms added in accord with section 7 apply to the code; 202 | keep intact all notices of the absence of any warranty; and give all 203 | recipients a copy of this License along with the Program. 204 | 205 | You may charge any price or no price for each copy that you convey, 206 | and you may offer support or warranty protection for a fee. 207 | 208 | 5. Conveying Modified Source Versions. 209 | 210 | You may convey a work based on the Program, or the modifications to 211 | produce it from the Program, in the form of source code under the 212 | terms of section 4, provided that you also meet all of these conditions: 213 | 214 | a) The work must carry prominent notices stating that you modified 215 | it, and giving a relevant date. 216 | 217 | b) The work must carry prominent notices stating that it is 218 | released under this License and any conditions added under section 219 | 7. This requirement modifies the requirement in section 4 to 220 | "keep intact all notices". 221 | 222 | c) You must license the entire work, as a whole, under this 223 | License to anyone who comes into possession of a copy. This 224 | License will therefore apply, along with any applicable section 7 225 | additional terms, to the whole of the work, and all its parts, 226 | regardless of how they are packaged. This License gives no 227 | permission to license the work in any other way, but it does not 228 | invalidate such permission if you have separately received it. 229 | 230 | d) If the work has interactive user interfaces, each must display 231 | Appropriate Legal Notices; however, if the Program has interactive 232 | interfaces that do not display Appropriate Legal Notices, your 233 | work need not make them do so. 234 | 235 | A compilation of a covered work with other separate and independent 236 | works, which are not by their nature extensions of the covered work, 237 | and which are not combined with it such as to form a larger program, 238 | in or on a volume of a storage or distribution medium, is called an 239 | "aggregate" if the compilation and its resulting copyright are not 240 | used to limit the access or legal rights of the compilation's users 241 | beyond what the individual works permit. Inclusion of a covered work 242 | in an aggregate does not cause this License to apply to the other 243 | parts of the aggregate. 244 | 245 | 6. Conveying Non-Source Forms. 246 | 247 | You may convey a covered work in object code form under the terms 248 | of sections 4 and 5, provided that you also convey the 249 | machine-readable Corresponding Source under the terms of this License, 250 | in one of these ways: 251 | 252 | a) Convey the object code in, or embodied in, a physical product 253 | (including a physical distribution medium), accompanied by the 254 | Corresponding Source fixed on a durable physical medium 255 | customarily used for software interchange. 256 | 257 | b) Convey the object code in, or embodied in, a physical product 258 | (including a physical distribution medium), accompanied by a 259 | written offer, valid for at least three years and valid for as 260 | long as you offer spare parts or customer support for that product 261 | model, to give anyone who possesses the object code either (1) a 262 | copy of the Corresponding Source for all the software in the 263 | product that is covered by this License, on a durable physical 264 | medium customarily used for software interchange, for a price no 265 | more than your reasonable cost of physically performing this 266 | conveying of source, or (2) access to copy the 267 | Corresponding Source from a network server at no charge. 268 | 269 | c) Convey individual copies of the object code with a copy of the 270 | written offer to provide the Corresponding Source. This 271 | alternative is allowed only occasionally and noncommercially, and 272 | only if you received the object code with such an offer, in accord 273 | with subsection 6b. 274 | 275 | d) Convey the object code by offering access from a designated 276 | place (gratis or for a charge), and offer equivalent access to the 277 | Corresponding Source in the same way through the same place at no 278 | further charge. You need not require recipients to copy the 279 | Corresponding Source along with the object code. If the place to 280 | copy the object code is a network server, the Corresponding Source 281 | may be on a different server (operated by you or a third party) 282 | that supports equivalent copying facilities, provided you maintain 283 | clear directions next to the object code saying where to find the 284 | Corresponding Source. Regardless of what server hosts the 285 | Corresponding Source, you remain obligated to ensure that it is 286 | available for as long as needed to satisfy these requirements. 287 | 288 | e) Convey the object code using peer-to-peer transmission, provided 289 | you inform other peers where the object code and Corresponding 290 | Source of the work are being offered to the general public at no 291 | charge under subsection 6d. 292 | 293 | A separable portion of the object code, whose source code is excluded 294 | from the Corresponding Source as a System Library, need not be 295 | included in conveying the object code work. 296 | 297 | A "User Product" is either (1) a "consumer product", which means any 298 | tangible personal property which is normally used for personal, family, 299 | or household purposes, or (2) anything designed or sold for incorporation 300 | into a dwelling. In determining whether a product is a consumer product, 301 | doubtful cases shall be resolved in favor of coverage. For a particular 302 | product received by a particular user, "normally used" refers to a 303 | typical or common use of that class of product, regardless of the status 304 | of the particular user or of the way in which the particular user 305 | actually uses, or expects or is expected to use, the product. A product 306 | is a consumer product regardless of whether the product has substantial 307 | commercial, industrial or non-consumer uses, unless such uses represent 308 | the only significant mode of use of the product. 309 | 310 | "Installation Information" for a User Product means any methods, 311 | procedures, authorization keys, or other information required to install 312 | and execute modified versions of a covered work in that User Product from 313 | a modified version of its Corresponding Source. The information must 314 | suffice to ensure that the continued functioning of the modified object 315 | code is in no case prevented or interfered with solely because 316 | modification has been made. 317 | 318 | If you convey an object code work under this section in, or with, or 319 | specifically for use in, a User Product, and the conveying occurs as 320 | part of a transaction in which the right of possession and use of the 321 | User Product is transferred to the recipient in perpetuity or for a 322 | fixed term (regardless of how the transaction is characterized), the 323 | Corresponding Source conveyed under this section must be accompanied 324 | by the Installation Information. But this requirement does not apply 325 | if neither you nor any third party retains the ability to install 326 | modified object code on the User Product (for example, the work has 327 | been installed in ROM). 328 | 329 | The requirement to provide Installation Information does not include a 330 | requirement to continue to provide support service, warranty, or updates 331 | for a work that has been modified or installed by the recipient, or for 332 | the User Product in which it has been modified or installed. Access to a 333 | network may be denied when the modification itself materially and 334 | adversely affects the operation of the network or violates the rules and 335 | protocols for communication across the network. 336 | 337 | Corresponding Source conveyed, and Installation Information provided, 338 | in accord with this section must be in a format that is publicly 339 | documented (and with an implementation available to the public in 340 | source code form), and must require no special password or key for 341 | unpacking, reading or copying. 342 | 343 | 7. Additional Terms. 344 | 345 | "Additional permissions" are terms that supplement the terms of this 346 | License by making exceptions from one or more of its conditions. 347 | Additional permissions that are applicable to the entire Program shall 348 | be treated as though they were included in this License, to the extent 349 | that they are valid under applicable law. If additional permissions 350 | apply only to part of the Program, that part may be used separately 351 | under those permissions, but the entire Program remains governed by 352 | this License without regard to the additional permissions. 353 | 354 | When you convey a copy of a covered work, you may at your option 355 | remove any additional permissions from that copy, or from any part of 356 | it. (Additional permissions may be written to require their own 357 | removal in certain cases when you modify the work.) You may place 358 | additional permissions on material, added by you to a covered work, 359 | for which you have or can give appropriate copyright permission. 360 | 361 | Notwithstanding any other provision of this License, for material you 362 | add to a covered work, you may (if authorized by the copyright holders of 363 | that material) supplement the terms of this License with terms: 364 | 365 | a) Disclaiming warranty or limiting liability differently from the 366 | terms of sections 15 and 16 of this License; or 367 | 368 | b) Requiring preservation of specified reasonable legal notices or 369 | author attributions in that material or in the Appropriate Legal 370 | Notices displayed by works containing it; or 371 | 372 | c) Prohibiting misrepresentation of the origin of that material, or 373 | requiring that modified versions of such material be marked in 374 | reasonable ways as different from the original version; or 375 | 376 | d) Limiting the use for publicity purposes of names of licensors or 377 | authors of the material; or 378 | 379 | e) Declining to grant rights under trademark law for use of some 380 | trade names, trademarks, or service marks; or 381 | 382 | f) Requiring indemnification of licensors and authors of that 383 | material by anyone who conveys the material (or modified versions of 384 | it) with contractual assumptions of liability to the recipient, for 385 | any liability that these contractual assumptions directly impose on 386 | those licensors and authors. 387 | 388 | All other non-permissive additional terms are considered "further 389 | restrictions" within the meaning of section 10. If the Program as you 390 | received it, or any part of it, contains a notice stating that it is 391 | governed by this License along with a term that is a further 392 | restriction, you may remove that term. If a license document contains 393 | a further restriction but permits relicensing or conveying under this 394 | License, you may add to a covered work material governed by the terms 395 | of that license document, provided that the further restriction does 396 | not survive such relicensing or conveying. 397 | 398 | If you add terms to a covered work in accord with this section, you 399 | must place, in the relevant source files, a statement of the 400 | additional terms that apply to those files, or a notice indicating 401 | where to find the applicable terms. 402 | 403 | Additional terms, permissive or non-permissive, may be stated in the 404 | form of a separately written license, or stated as exceptions; 405 | the above requirements apply either way. 406 | 407 | 8. Termination. 408 | 409 | You may not propagate or modify a covered work except as expressly 410 | provided under this License. Any attempt otherwise to propagate or 411 | modify it is void, and will automatically terminate your rights under 412 | this License (including any patent licenses granted under the third 413 | paragraph of section 11). 414 | 415 | However, if you cease all violation of this License, then your 416 | license from a particular copyright holder is reinstated (a) 417 | provisionally, unless and until the copyright holder explicitly and 418 | finally terminates your license, and (b) permanently, if the copyright 419 | holder fails to notify you of the violation by some reasonable means 420 | prior to 60 days after the cessation. 421 | 422 | Moreover, your license from a particular copyright holder is 423 | reinstated permanently if the copyright holder notifies you of the 424 | violation by some reasonable means, this is the first time you have 425 | received notice of violation of this License (for any work) from that 426 | copyright holder, and you cure the violation prior to 30 days after 427 | your receipt of the notice. 428 | 429 | Termination of your rights under this section does not terminate the 430 | licenses of parties who have received copies or rights from you under 431 | this License. If your rights have been terminated and not permanently 432 | reinstated, you do not qualify to receive new licenses for the same 433 | material under section 10. 434 | 435 | 9. Acceptance Not Required for Having Copies. 436 | 437 | You are not required to accept this License in order to receive or 438 | run a copy of the Program. Ancillary propagation of a covered work 439 | occurring solely as a consequence of using peer-to-peer transmission 440 | to receive a copy likewise does not require acceptance. However, 441 | nothing other than this License grants you permission to propagate or 442 | modify any covered work. These actions infringe copyright if you do 443 | not accept this License. Therefore, by modifying or propagating a 444 | covered work, you indicate your acceptance of this License to do so. 445 | 446 | 10. Automatic Licensing of Downstream Recipients. 447 | 448 | Each time you convey a covered work, the recipient automatically 449 | receives a license from the original licensors, to run, modify and 450 | propagate that work, subject to this License. You are not responsible 451 | for enforcing compliance by third parties with this License. 452 | 453 | An "entity transaction" is a transaction transferring control of an 454 | organization, or substantially all assets of one, or subdividing an 455 | organization, or merging organizations. If propagation of a covered 456 | work results from an entity transaction, each party to that 457 | transaction who receives a copy of the work also receives whatever 458 | licenses to the work the party's predecessor in interest had or could 459 | give under the previous paragraph, plus a right to possession of the 460 | Corresponding Source of the work from the predecessor in interest, if 461 | the predecessor has it or can get it with reasonable efforts. 462 | 463 | You may not impose any further restrictions on the exercise of the 464 | rights granted or affirmed under this License. For example, you may 465 | not impose a license fee, royalty, or other charge for exercise of 466 | rights granted under this License, and you may not initiate litigation 467 | (including a cross-claim or counterclaim in a lawsuit) alleging that 468 | any patent claim is infringed by making, using, selling, offering for 469 | sale, or importing the Program or any portion of it. 470 | 471 | 11. Patents. 472 | 473 | A "contributor" is a copyright holder who authorizes use under this 474 | License of the Program or a work on which the Program is based. The 475 | work thus licensed is called the contributor's "contributor version". 476 | 477 | A contributor's "essential patent claims" are all patent claims 478 | owned or controlled by the contributor, whether already acquired or 479 | hereafter acquired, that would be infringed by some manner, permitted 480 | by this License, of making, using, or selling its contributor version, 481 | but do not include claims that would be infringed only as a 482 | consequence of further modification of the contributor version. For 483 | purposes of this definition, "control" includes the right to grant 484 | patent sublicenses in a manner consistent with the requirements of 485 | this License. 486 | 487 | Each contributor grants you a non-exclusive, worldwide, royalty-free 488 | patent license under the contributor's essential patent claims, to 489 | make, use, sell, offer for sale, import and otherwise run, modify and 490 | propagate the contents of its contributor version. 491 | 492 | In the following three paragraphs, a "patent license" is any express 493 | agreement or commitment, however denominated, not to enforce a patent 494 | (such as an express permission to practice a patent or covenant not to 495 | sue for patent infringement). To "grant" such a patent license to a 496 | party means to make such an agreement or commitment not to enforce a 497 | patent against the party. 498 | 499 | If you convey a covered work, knowingly relying on a patent license, 500 | and the Corresponding Source of the work is not available for anyone 501 | to copy, free of charge and under the terms of this License, through a 502 | publicly available network server or other readily accessible means, 503 | then you must either (1) cause the Corresponding Source to be so 504 | available, or (2) arrange to deprive yourself of the benefit of the 505 | patent license for this particular work, or (3) arrange, in a manner 506 | consistent with the requirements of this License, to extend the patent 507 | license to downstream recipients. "Knowingly relying" means you have 508 | actual knowledge that, but for the patent license, your conveying the 509 | covered work in a country, or your recipient's use of the covered work 510 | in a country, would infringe one or more identifiable patents in that 511 | country that you have reason to believe are valid. 512 | 513 | If, pursuant to or in connection with a single transaction or 514 | arrangement, you convey, or propagate by procuring conveyance of, a 515 | covered work, and grant a patent license to some of the parties 516 | receiving the covered work authorizing them to use, propagate, modify 517 | or convey a specific copy of the covered work, then the patent license 518 | you grant is automatically extended to all recipients of the covered 519 | work and works based on it. 520 | 521 | A patent license is "discriminatory" if it does not include within 522 | the scope of its coverage, prohibits the exercise of, or is 523 | conditioned on the non-exercise of one or more of the rights that are 524 | specifically granted under this License. You may not convey a covered 525 | work if you are a party to an arrangement with a third party that is 526 | in the business of distributing software, under which you make payment 527 | to the third party based on the extent of your activity of conveying 528 | the work, and under which the third party grants, to any of the 529 | parties who would receive the covered work from you, a discriminatory 530 | patent license (a) in connection with copies of the covered work 531 | conveyed by you (or copies made from those copies), or (b) primarily 532 | for and in connection with specific products or compilations that 533 | contain the covered work, unless you entered into that arrangement, 534 | or that patent license was granted, prior to 28 March 2007. 535 | 536 | Nothing in this License shall be construed as excluding or limiting 537 | any implied license or other defenses to infringement that may 538 | otherwise be available to you under applicable patent law. 539 | 540 | 12. No Surrender of Others' Freedom. 541 | 542 | If conditions are imposed on you (whether by court order, agreement or 543 | otherwise) that contradict the conditions of this License, they do not 544 | excuse you from the conditions of this License. If you cannot convey a 545 | covered work so as to satisfy simultaneously your obligations under this 546 | License and any other pertinent obligations, then as a consequence you may 547 | not convey it at all. For example, if you agree to terms that obligate you 548 | to collect a royalty for further conveying from those to whom you convey 549 | the Program, the only way you could satisfy both those terms and this 550 | License would be to refrain entirely from conveying the Program. 551 | 552 | 13. Use with the GNU Affero General Public License. 553 | 554 | Notwithstanding any other provision of this License, you have 555 | permission to link or combine any covered work with a work licensed 556 | under version 3 of the GNU Affero General Public License into a single 557 | combined work, and to convey the resulting work. The terms of this 558 | License will continue to apply to the part which is the covered work, 559 | but the special requirements of the GNU Affero General Public License, 560 | section 13, concerning interaction through a network will apply to the 561 | combination as such. 562 | 563 | 14. Revised Versions of this License. 564 | 565 | The Free Software Foundation may publish revised and/or new versions of 566 | the GNU General Public License from time to time. Such new versions will 567 | be similar in spirit to the present version, but may differ in detail to 568 | address new problems or concerns. 569 | 570 | Each version is given a distinguishing version number. If the 571 | Program specifies that a certain numbered version of the GNU General 572 | Public License "or any later version" applies to it, you have the 573 | option of following the terms and conditions either of that numbered 574 | version or of any later version published by the Free Software 575 | Foundation. If the Program does not specify a version number of the 576 | GNU General Public License, you may choose any version ever published 577 | by the Free Software Foundation. 578 | 579 | If the Program specifies that a proxy can decide which future 580 | versions of the GNU General Public License can be used, that proxy's 581 | public statement of acceptance of a version permanently authorizes you 582 | to choose that version for the Program. 583 | 584 | Later license versions may give you additional or different 585 | permissions. However, no additional obligations are imposed on any 586 | author or copyright holder as a result of your choosing to follow a 587 | later version. 588 | 589 | 15. Disclaimer of Warranty. 590 | 591 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY 592 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT 593 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY 594 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, 595 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR 596 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM 597 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF 598 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 599 | 600 | 16. Limitation of Liability. 601 | 602 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING 603 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS 604 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY 605 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE 606 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF 607 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD 608 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), 609 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF 610 | SUCH DAMAGES. 611 | 612 | 17. Interpretation of Sections 15 and 16. 613 | 614 | If the disclaimer of warranty and limitation of liability provided 615 | above cannot be given local legal effect according to their terms, 616 | reviewing courts shall apply local law that most closely approximates 617 | an absolute waiver of all civil liability in connection with the 618 | Program, unless a warranty or assumption of liability accompanies a 619 | copy of the Program in return for a fee. 620 | 621 | END OF TERMS AND CONDITIONS 622 | 623 | How to Apply These Terms to Your New Programs 624 | 625 | If you develop a new program, and you want it to be of the greatest 626 | possible use to the public, the best way to achieve this is to make it 627 | free software which everyone can redistribute and change under these terms. 628 | 629 | To do so, attach the following notices to the program. It is safest 630 | to attach them to the start of each source file to most effectively 631 | state the exclusion of warranty; and each file should have at least 632 | the "copyright" line and a pointer to where the full notice is found. 633 | 634 | 635 | Copyright (C) 636 | 637 | This program is free software: you can redistribute it and/or modify 638 | it under the terms of the GNU General Public License as published by 639 | the Free Software Foundation, either version 3 of the License, or 640 | (at your option) any later version. 641 | 642 | This program is distributed in the hope that it will be useful, 643 | but WITHOUT ANY WARRANTY; without even the implied warranty of 644 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 645 | GNU General Public License for more details. 646 | 647 | You should have received a copy of the GNU General Public License 648 | along with this program. If not, see . 649 | 650 | Also add information on how to contact you by electronic and paper mail. 651 | 652 | If the program does terminal interaction, make it output a short 653 | notice like this when it starts in an interactive mode: 654 | 655 | Copyright (C) 656 | This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. 657 | This is free software, and you are welcome to redistribute it 658 | under certain conditions; type `show c' for details. 659 | 660 | The hypothetical commands `show w' and `show c' should show the appropriate 661 | parts of the General Public License. Of course, your program's commands 662 | might be different; for a GUI interface, you would use an "about box". 663 | 664 | You should also get your employer (if you work as a programmer) or school, 665 | if any, to sign a "copyright disclaimer" for the program, if necessary. 666 | For more information on this, and how to apply and follow the GNU GPL, see 667 | . 668 | 669 | The GNU General Public License does not permit incorporating your program 670 | into proprietary programs. If your program is a subroutine library, you 671 | may consider it more useful to permit linking proprietary applications with 672 | the library. If this is what you want to do, use the GNU Lesser General 673 | Public License instead of this License. But first, please read 674 | . 675 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Eraserr 2 | 3 | ![Image](https://github.com/user-attachments/assets/811c84a5-c82d-4d36-88d4-fcb09005886c) 4 | 5 | 6 | 👋 **Check out my AI project [Seren](https://getseren.com)!** 7 | 8 | Eraserr is a Python script designed to help keep your Plex servers clean. It deletes unwatched or stale media by leveraging the functionality of Radarr, Sonarr, and Overseerr. 9 | 10 | ## Table of Contents 11 | * [Installation](#installation) 12 | * [Prerequisites](#prerequisites) 13 | * [Usage](#usage) 14 | * [Docker](#docker) 15 | * [Pulling the image](#pulling-the-image) 16 | * [Running the Container](#running-the-container) 17 | * [Configuration](#configuration) 18 | 19 | ## Installation 20 | 21 | ### Prerequisites 22 | 23 | - [Python 3.7+][0] 24 | - [Pip][1] 25 | 26 | 1. First, clone the script to your machine and navigate to the resulting directory: 27 | 28 | ```shell 29 | git clone https://github.com/everettsouthwick/Eraserr.git 30 | cd Eraserr 31 | ``` 32 | 2. Then, install the required packages to run the script: 33 | 34 | ```shell 35 | pip install -r requirements.txt 36 | ``` 37 | 38 | ## Usage 39 | 40 | To use the script, run the following command: 41 | ```shell 42 | python eraserr.py 43 | ``` 44 | 45 | ### Docker 46 | 47 | #### Pulling the image 48 | 49 | You can pull the latest container image from the [Docker repository][2] by running the following command: 50 | 51 | ```shell 52 | docker pull ecsouthwick/eraserr 53 | ``` 54 | To pull the develop branch from the Docker repository, add the `:develop` tag to the above command: 55 | 56 | ```shell 57 | docker pull ecsouthwick/eraserr:develop 58 | ``` 59 | 60 | #### Running the Container 61 | 62 | Once you have pulled the image from docker, you may use the following command to run the container: 63 | 64 | ```shell 65 | docker run -d --name eraserr --volume /path/to/config.json:/app/config.json ecsouthwick/eraserr 66 | ``` 67 | 68 | **Note**: The recommended restart policy for the container is `on-failure` or `no`. 69 | 70 | ## Configuration 71 | 72 | 1. Copy `config.example.json` to `config.json`. 73 | 2. See [CONFIGURATION.md](CONFIGURATION.md) for detailed instructions on setting up `config.json`. 74 | 75 | [0]: https://www.python.org/downloads/ "Python 3.7+" 76 | [1]: https://pip.pypa.io/en/stable/installation/ "Pip" 77 | [2]: https://hub.docker.com/r/ecsouthwick/eraserr "Docker repository" 78 | -------------------------------------------------------------------------------- /config.example.json: -------------------------------------------------------------------------------- 1 | { 2 | "dry_run": true, 3 | "log_level": "INFO", 4 | "schedule_interval": "1d", 5 | "plex": { 6 | "base_url": "https://plex.domain.com", 7 | "token": "" 8 | }, 9 | "radarr": { 10 | "enabled": true, 11 | "api_key": "", 12 | "base_url": "https://radarr.domain.com/api/v3", 13 | "exempt_tag_names": [ 14 | "exempt-from-auto-delete", 15 | "some-other-tag" 16 | ], 17 | "watched_deletion_threshold": "180d", 18 | "unwatched_deletion_threshold": "30d" 19 | }, 20 | "sonarr": { 21 | "enabled": true, 22 | "api_key": "", 23 | "base_url": "https://sonarr.domain.com/api/v3", 24 | "monitor_continuing_series": true, 25 | "exempt_tag_names": [ 26 | "exempt-from-auto-delete", 27 | "some-other-tag" 28 | ], 29 | "dynamic_load": { 30 | "enabled": false, 31 | "episodes_to_load": 3, 32 | "episodes_to_keep": 3, 33 | "watched_deletion_threshold": "30d", 34 | "schedule_interval": "5m" 35 | }, 36 | "watched_deletion_threshold": "180d", 37 | "unwatched_deletion_threshold": "30d" 38 | }, 39 | "overseerr": { 40 | "enabled": true, 41 | "api_key": "", 42 | "base_url": "https://overseerr.domain.com/api/v1", 43 | "fetch_limit": 20 44 | }, 45 | "experimental": { 46 | "free_space": { 47 | "enabled": false, 48 | "minimum_free_space_percentage": 20, 49 | "path": "/mnt/local/Media", 50 | "prevent_age_based_deletion": true, 51 | "prevent_dynamic_load": true, 52 | "progressive_deletion": { 53 | "enabled": false, 54 | "maximum_deletion_cycles": 0, 55 | "threshold_reduction_per_cycle": "1d" 56 | } 57 | } 58 | } 59 | } -------------------------------------------------------------------------------- /eraserr.py: -------------------------------------------------------------------------------- 1 | """eraserr.py: A script to remove expired media from Plex, Radarr, Sonarr, and Overseerr.""" 2 | import argparse 3 | from src.main import main 4 | 5 | __version__ = "2.2.2" 6 | 7 | def add_arguments(arg_parser: argparse.ArgumentParser): 8 | ''' 9 | Adds arguments to the given ArgumentParser object. 10 | 11 | Args: 12 | arg_parser (argparse.ArgumentParser): The ArgumentParser object to add arguments to. 13 | 14 | Returns: 15 | None 16 | ''' 17 | arg_parser.add_argument( 18 | "-v", "--version", action="version", version=f"%(prog)s {__version__}", help="show the current version and exit" 19 | ) 20 | 21 | arg_parser.add_argument("-d", "--dry-run", action="store_true", help="perform a trial run without any changes made") 22 | 23 | 24 | if __name__ == "__main__": 25 | parser = argparse.ArgumentParser(description="Parse command line arguments") 26 | add_arguments(parser) 27 | args = parser.parse_args() 28 | 29 | try: 30 | main(args) 31 | except KeyboardInterrupt: 32 | print("\nCtrl+C pressed. Stopping all checks") 33 | -------------------------------------------------------------------------------- /renovate.json: -------------------------------------------------------------------------------- 1 | { 2 | "$schema": "https://docs.renovatebot.com/renovate-schema.json", 3 | "extends": [ 4 | "config:recommended", 5 | ":automergeStableNonMajor", 6 | "schedule:nonOfficeHours" 7 | ], 8 | "baseBranches": [ 9 | "develop" 10 | ] 11 | } 12 | -------------------------------------------------------------------------------- /requirements.txt: -------------------------------------------------------------------------------- 1 | PlexAPI==4.15.4 2 | Requests==2.32.0 3 | retry==0.9.2 4 | schedule==1.2.1 -------------------------------------------------------------------------------- /src/clients/overseerr.py: -------------------------------------------------------------------------------- 1 | """Module for interacting with the Overseerr API.""" 2 | import requests 3 | from retry import retry 4 | from src.logger import logger 5 | 6 | class OverseerrClient: 7 | """ 8 | Class for interacting with the Overseerr API. 9 | """ 10 | def __init__(self, config): 11 | self.config = config 12 | self.api_key = config.overseerr.api_key 13 | self.base_url = config.overseerr.base_url 14 | self.fetch_limit = config.overseerr.fetch_limit 15 | 16 | def __get_media(self): 17 | url = f"{self.base_url}/media" 18 | headers = {"X-API-KEY": self.api_key} 19 | params = {"take": self.fetch_limit, "skip": 0} 20 | 21 | media_list = [] 22 | 23 | for _ in range(1000): 24 | response = requests.get(url, headers=headers, params=params, timeout=30) 25 | if response.status_code != 200: 26 | raise requests.exceptions.RequestException(f"{response.url} : {response.status_code} - {response.text}") 27 | 28 | if not response.json().get("results", []): 29 | break 30 | 31 | media_list.extend(response.json().get("results", [])) 32 | 33 | params["skip"] += self.fetch_limit 34 | 35 | return media_list 36 | 37 | def __delete_media(self, media_id: int): 38 | url = f"{self.base_url}/media/{media_id}" 39 | headers = {"X-API-KEY": self.api_key} 40 | 41 | response = requests.delete(url, headers=headers, timeout=30) 42 | if response.status_code != 204: 43 | raise requests.exceptions.RequestException(f"{response.url} : {response.status_code} - {response.text}") 44 | 45 | @retry(tries=3, delay=5) 46 | def get_and_delete_media(self, media_to_delete: dict, dry_run: bool = False): 47 | """ 48 | Gets and deletes media with the given IDs from the Overseerr API. 49 | 50 | Args: 51 | media_to_delete: A dictionary where the key is the ID of the media to delete 52 | and the value is the title of the media. 53 | 54 | Raises: 55 | requests.exceptions.RequestException: If the API request fails. 56 | """ 57 | media = self.__get_media() 58 | 59 | if media is None: 60 | return 61 | 62 | media_type_id_map = {"movie": "tmdbId", "tv": "tvdbId"} 63 | 64 | for media_id, media_title in media_to_delete.items(): 65 | for item in media: 66 | media_type = item.get("mediaType") 67 | if media_type is None: 68 | continue 69 | 70 | media_id_key = media_type_id_map.get(media_type) 71 | if media_id_key and item.get(media_id_key) == int(media_id): 72 | if dry_run: 73 | logger.info("[OVERSEERR][DRY RUN] Would have deleted %s.", media_title) 74 | continue 75 | 76 | try: 77 | self.__delete_media(item.get("id")) 78 | logger.info("[OVERSEERR] Deleted %s.", media_title) 79 | except requests.exceptions.RequestException as err: 80 | logger.error("[OVERSEERR] Failed to delete %s. Error: %s", media_title, err) 81 | continue 82 | -------------------------------------------------------------------------------- /src/clients/plex.py: -------------------------------------------------------------------------------- 1 | """Module for interacting with Plex.""" 2 | import time 3 | from datetime import datetime, timedelta 4 | from plexapi.server import PlexServer 5 | from plexapi.exceptions import NotFound 6 | from retry import retry 7 | from src.logger import logger 8 | from src.models.dynamicmedia import DynamicMedia 9 | 10 | 11 | class PlexClient: 12 | """Client for interacting with Plex.""" 13 | 14 | def __init__(self, config): 15 | self.config = config 16 | self.base_url = config.plex.base_url 17 | self.token = config.plex.token 18 | self.plex = PlexServer(self.base_url, self.token, timeout=60) 19 | 20 | def __get_media(self, section_type): 21 | sections = self.__get_sections_by_type(section_type) 22 | 23 | media_list = [] 24 | for section in sections: 25 | for media in section.all(): 26 | media_list.append(media) 27 | 28 | return media_list 29 | 30 | def __get_sections_by_type(self, section_type): 31 | return [section for section in self.plex.library.sections() if section.type == section_type] 32 | 33 | def __get_episode_sessions(self): 34 | return [session for session in self.plex.sessions() if session.type == "episode"] 35 | 36 | def __get_series_by_guid(self, series_guid): 37 | sections = self.__get_sections_by_type("show") 38 | for section in sections: 39 | try: 40 | series = section.getGuid(series_guid) 41 | if series: 42 | return series 43 | except NotFound: 44 | continue 45 | 46 | return None 47 | 48 | def __get_episodes_prior_to_session(self, session): 49 | series = self.__get_series_by_guid(session.grandparentGuid) 50 | if not series: 51 | return False 52 | 53 | all_episodes = series.episodes() 54 | episodes_to_check = [] 55 | 56 | for episode in all_episodes: 57 | if episode.parentIndex < session.parentIndex or (episode.parentIndex == session.parentIndex and episode.index < session.index): 58 | logger.debug("[PLEX] S%sE%s is before S%sE%s. It should be checked to be unloaded.", episode.parentIndex, episode.index, session.parentIndex, session.index) 59 | episodes_to_check.append(episode) 60 | else: 61 | logger.debug("[PLEX] S%sE%s is after S%sE%s. It should not checked to be unloaded.", episode.parentIndex, episode.index, session.parentIndex, session.index) 62 | 63 | return episodes_to_check 64 | 65 | def __media_is_expired(self, media, watched_media_expiry_seconds, unwatched_media_expiry_seconds, schedule_interval): 66 | current_time = time.time() 67 | watched_media_expiry_date = datetime.fromtimestamp(current_time - watched_media_expiry_seconds) 68 | unwatched_media_expiry_date = datetime.fromtimestamp(current_time - unwatched_media_expiry_seconds) 69 | min_date = datetime.now() - timedelta(seconds=max(watched_media_expiry_seconds, unwatched_media_expiry_seconds)) - timedelta(seconds=schedule_interval * 3) 70 | 71 | added_at = media.addedAt if media.addedAt else datetime.fromtimestamp(0) 72 | if media.type == "show": 73 | added_at = max(episode.addedAt for episode in media.episodes()) if media.episodes() else added_at 74 | history = media.history(mindate=min_date) 75 | watched_date = max(entry.viewedAt for entry in history) if history else None 76 | 77 | if watched_date is None and added_at < unwatched_media_expiry_date: 78 | logger.info("[PLEX] %s is unwatched and expired. Added at %s. Expired at %s.", media.title, added_at, datetime.fromtimestamp(added_at.timestamp() + unwatched_media_expiry_seconds)) 79 | return True 80 | 81 | if watched_date is not None and watched_date < watched_media_expiry_date: 82 | logger.info("[PLEX] %s is watched and expired. Added at %s. Watched at %s. Expired at %s.", media.title, added_at, watched_date, datetime.fromtimestamp(watched_date.timestamp() + watched_media_expiry_seconds)) 83 | return True 84 | 85 | return False 86 | 87 | def __media_is_unloadable(self, media, session, watched_media_expiry_seconds): 88 | min_date = datetime.now() - timedelta(seconds=watched_media_expiry_seconds) 89 | history = media.history(mindate=min_date) 90 | for entry in history: 91 | if entry.accountID != session.user.id: 92 | logger.debug("[PLEX][DYNAMIC LOAD] %s has been watched by a different user. It should not be unloaded.", media.grandparentTitle) 93 | return False 94 | 95 | return True 96 | 97 | @retry(tries=3, delay=5) 98 | def get_expired_media(self, section_type, watched_media_expiry_seconds, unwatched_media_expiry_seconds, schedule_interval): 99 | """ 100 | Retrieves a list of expired media. 101 | 102 | Args: 103 | section_type: The type of media to retrieve. 104 | watched_media_expiry_seconds: The number of seconds after which watched media is considered expired. 105 | unwatched_media_expiry_seconds: The number of seconds after which unwatched media is considered expired. 106 | 107 | Returns: 108 | List[PlexMedia]: A list of PlexMedia objects representing the expired media. 109 | """ 110 | media = self.__get_media(section_type) 111 | expired_media = [] 112 | 113 | for item in media: 114 | if self.__media_is_expired(item, watched_media_expiry_seconds, unwatched_media_expiry_seconds, schedule_interval): 115 | item.reload() 116 | expired_media.append(item) 117 | 118 | return expired_media 119 | 120 | @retry(tries=3, delay=5) 121 | def get_dynamic_load_media(self, watched_media_expiry_seconds): 122 | """ 123 | Retrieves a list of media that should be dynamically loaded. 124 | 125 | Args: 126 | watched_media_expiry_seconds: The number of seconds after which watched media is considered expired. 127 | 128 | Returns: 129 | List[DynamicMedia]: A list of DynamicMedia objects representing the media that should be dynamically loaded. 130 | """ 131 | sessions = self.__get_episode_sessions() 132 | media_to_load = [] 133 | 134 | for session in sessions: 135 | series = self.__get_series_by_guid(session.grandparentGuid) 136 | if not series: 137 | continue 138 | 139 | unload_media = True 140 | current_season = session.parentIndex 141 | current_episode = session.index 142 | for episode in self.__get_episodes_prior_to_session(session): 143 | if not self.__media_is_unloadable(episode, session, watched_media_expiry_seconds): 144 | unload_media = False 145 | break 146 | 147 | series.reload() 148 | media_to_load.append(DynamicMedia(series, unload_media, current_season, current_episode)) 149 | 150 | return media_to_load 151 | -------------------------------------------------------------------------------- /src/clients/radarr.py: -------------------------------------------------------------------------------- 1 | """Radarr API client.""" 2 | import requests 3 | from retry import retry 4 | from src.logger import logger 5 | from src.util import convert_bytes 6 | 7 | class RadarrClient: 8 | """Class for interacting with the Radarr API.""" 9 | def __init__(self, config): 10 | self.config = config 11 | self.api_key = config.radarr.api_key 12 | self.base_url = config.radarr.base_url 13 | self.exempt_tag_names = config.radarr.exempt_tag_names 14 | 15 | def __get_media(self): 16 | url = f"{self.base_url}/movie" 17 | headers = {"X-Api-Key": self.api_key} 18 | 19 | response = requests.get(url, headers=headers, timeout=30) 20 | if response.status_code != 200: 21 | raise requests.exceptions.RequestException(f"{response.url} : {response.status_code} - {response.text}") 22 | 23 | return response.json() 24 | 25 | def __get_exempt_tag_ids(self, tag_names: list): 26 | url = f"{self.base_url}/tag" 27 | headers = {"X-Api-Key": self.api_key} 28 | 29 | response = requests.get(url, headers=headers, timeout=30) 30 | if response.status_code != 200: 31 | raise requests.exceptions.RequestException(f"{response.url} : {response.status_code} - {response.text}") 32 | 33 | tags = response.json() 34 | tag_ids = [tag["id"] for tag in tags if tag["label"] in tag_names] 35 | 36 | return tag_ids 37 | 38 | def __delete_media(self, media_id: int): 39 | url = f"{self.base_url}/movie/{media_id}" 40 | headers = {"X-Api-Key": self.api_key} 41 | params = {"deleteFiles": True, "addImportExclusion": False} 42 | 43 | response = requests.delete(url, headers=headers, params=params, timeout=30) 44 | if response.status_code != 200: 45 | raise requests.exceptions.RequestException(f"{response.url} : {response.status_code} - {response.text}") 46 | 47 | @retry(tries=3, delay=5) 48 | def get_and_delete_media(self, media_to_delete: dict, dry_run: bool = False): 49 | """ 50 | Gets and deletes media with the given ID from the Radarr API. 51 | 52 | Args: 53 | media_to_delete: A dictionary where the key is the ID of the media to delete and the value is the title of the media. 54 | dry_run: Whether to perform a dry run. 55 | 56 | Returns: 57 | None. 58 | 59 | Raises: 60 | requests.exceptions.RequestException: If the API request fails. 61 | """ 62 | media = self.__get_media() 63 | exempt_tag_ids = self.__get_exempt_tag_ids(self.exempt_tag_names) 64 | original_deletion_count = len(media_to_delete) 65 | exempt_count = 0 66 | 67 | total_size = 0 68 | 69 | for movie in media: 70 | if str(movie.get("tmdbId")) not in media_to_delete.keys(): 71 | continue 72 | 73 | if any(tag in exempt_tag_ids for tag in movie.get("tags", [])): 74 | media_to_delete.pop(str(movie.get("tmdbId"))) 75 | exempt_count += 1 76 | logger.info("[RADARR] Skipping %s because it is exempt.", movie.get("title")) 77 | continue 78 | 79 | if movie.get("id") is not None: 80 | total_size += movie.get("sizeOnDisk", 0) 81 | if dry_run: 82 | logger.info("[RADARR][DRY RUN] Would have deleted %s. Space freed: %s.", movie.get("title"), convert_bytes(movie.get("sizeOnDisk", 0))) 83 | continue 84 | 85 | try: 86 | self.__delete_media(movie.get("id")) 87 | logger.info("[RADARR] Deleted %s. Space freed: %s.", movie.get("title"), convert_bytes(movie.get("sizeOnDisk", 0))) 88 | except requests.exceptions.RequestException as err: 89 | logger.error("[RADARR] Failed to delete %s. Error: %s", movie.get("title"), err) 90 | continue 91 | 92 | if dry_run: 93 | logger.info("[RADARR][DRY RUN] Total movies: %s. Movies eligible for deletion: %s. Movies deleted: %s. Movies exempt: %s. Total space freed: %s.", len(media), original_deletion_count, len(media_to_delete), exempt_count, convert_bytes(total_size)) 94 | else: 95 | logger.info("[RADARR] Total movies: %s. Movies eligible for deletion: %s. Movies deleted: %s. Movies exempt: %s. Total space freed: %s.\n", len(media), original_deletion_count, len(media_to_delete), exempt_count, convert_bytes(total_size)) 96 | 97 | return media_to_delete 98 | -------------------------------------------------------------------------------- /src/clients/sonarr.py: -------------------------------------------------------------------------------- 1 | """Sonarr API client.""" 2 | import time 3 | from datetime import datetime 4 | import requests 5 | from retry import retry 6 | from src.logger import logger 7 | from src.util import convert_bytes 8 | 9 | class SonarrClient: 10 | """Class for interacting with the Sonarr API.""" 11 | def __init__(self, config): 12 | self.config = config 13 | self.api_key = config.sonarr.api_key 14 | self.base_url = config.sonarr.base_url 15 | self.monitor_continuing_series = config.sonarr.monitor_continuing_series 16 | self.exempt_tag_names = config.sonarr.exempt_tag_names 17 | self.dynamic_load = config.sonarr.dynamic_load 18 | 19 | def __get_media(self): 20 | url = f"{self.base_url}/series" 21 | headers = {"X-Api-Key": self.api_key} 22 | 23 | response = requests.get(url, headers=headers, timeout=30) 24 | if response.status_code != 200: 25 | raise requests.exceptions.RequestException(f"{response.url} : {response.status_code} - {response.text}") 26 | 27 | return response.json() 28 | 29 | def __get_media_by_id(self, media_id: int): 30 | url = f"{self.base_url}/series/{media_id}" 31 | headers = {"X-Api-Key": self.api_key} 32 | 33 | response = requests.get(url, headers=headers, timeout=30) 34 | if response.status_code != 200: 35 | raise requests.exceptions.RequestException(f"{response.url} : {response.status_code} - {response.text}") 36 | 37 | return response.json() 38 | 39 | def __get_exempt_tag_ids(self, tag_names: list): 40 | url = f"{self.base_url}/tag" 41 | headers = {"X-Api-Key": self.api_key} 42 | 43 | response = requests.get(url, headers=headers, timeout=30) 44 | if response.status_code != 200: 45 | raise requests.exceptions.RequestException(f"{response.url} : {response.status_code} - {response.text}") 46 | 47 | tags = response.json() 48 | tag_ids = [tag["id"] for tag in tags if tag["label"] in tag_names] 49 | 50 | return tag_ids 51 | 52 | def __get_media_episodes(self, media_id: int): 53 | url = f"{self.base_url}/episode" 54 | headers = {"X-Api-Key": self.api_key} 55 | params = {"seriesId": media_id} 56 | 57 | response = requests.get(url, headers=headers, params=params, timeout=30) 58 | if response.status_code != 200: 59 | raise requests.exceptions.RequestException(f"{response.url} : {response.status_code} - {response.text}") 60 | 61 | return response.json() 62 | 63 | def __search_media_episodes(self, episode_ids: list): 64 | url = f"{self.base_url}/command" 65 | headers = {"X-Api-Key": self.api_key} 66 | body = {"name": "EpisodeSearch", "episodeIds": episode_ids} 67 | 68 | response = requests.post(url, headers=headers, json=body, timeout=30) 69 | if response.status_code != 201: 70 | raise requests.exceptions.RequestException(f"{response.url} : {response.status_code} - {response.text}") 71 | 72 | return response.json() 73 | 74 | def __put_media(self, series): 75 | url = f"{self.base_url}/series/{series.get('id')}" 76 | headers = {"X-Api-Key": self.api_key} 77 | 78 | response = requests.put(url, headers=headers, json=series, timeout=30) 79 | if response.status_code != 202: 80 | raise requests.exceptions.RequestException(f"{response.url} : {response.status_code} - {response.text}") 81 | 82 | return response.json() 83 | 84 | def __monitor_media_episodes(self, episode_ids: list, monitored: bool = False): 85 | url = f"{self.base_url}/episode/monitor" 86 | headers = {"X-Api-Key": self.api_key} 87 | body = {"episodeIds": episode_ids, "monitored": monitored} 88 | 89 | response = requests.put(url, headers=headers, json=body, timeout=30) 90 | if response.status_code != 202: 91 | raise requests.exceptions.RequestException(f"{response.url} : {response.status_code} - {response.text}") 92 | 93 | def __unmonitor_empty_seasons(self, series): 94 | for season in series.get("seasons", []): 95 | if season.get("statistics", {}).get("episodeCount", 0) > 0: 96 | continue 97 | 98 | if season.get("monitored", False): 99 | season["monitored"] = False 100 | 101 | return series 102 | 103 | def __delete_media(self, media_id: int): 104 | url = f"{self.base_url}/series/{media_id}" 105 | headers = {"X-Api-Key": self.api_key} 106 | params = {"deleteFiles": True, "addImportListExclusion": False} 107 | 108 | response = requests.delete(url, headers=headers, params=params, timeout=30) 109 | if response.status_code != 200: 110 | raise requests.exceptions.RequestException(f"{response.url} : {response.status_code} - {response.text}") 111 | 112 | def __delete_media_episodes(self, episode_file_ids: list): 113 | url = f"{self.base_url}/episodefile/bulk" 114 | headers = {"X-Api-Key": self.api_key} 115 | body = {"episodeFileIds": episode_file_ids} 116 | 117 | response = requests.delete(url, headers=headers, json=body, timeout=60) 118 | if response.status_code != 200: 119 | raise requests.exceptions.RequestException(f"{response.url} : {response.status_code} - {response.text}") 120 | 121 | def __handle_ended_series(self, series, dry_run: bool = False): 122 | size_on_disk = series.get("statistics", {}).get("sizeOnDisk", 0) 123 | if dry_run: 124 | logger.info("[SONARR][DRY RUN] Would have deleted %s. Space freed: %s.", series.get("title"), convert_bytes(size_on_disk)) 125 | return size_on_disk 126 | 127 | try: 128 | self.__delete_media(series.get("id")) 129 | logger.info("[SONARR] Deleted %s. Space freed: %s.", series.get("title"), convert_bytes(size_on_disk)) 130 | except requests.exceptions.RequestException as err: 131 | logger.error("[SONARR] Failed to delete %s. Error: %s", series.get("title"), err) 132 | 133 | return series.get("statistics", {}).get("sizeOnDisk", 0) 134 | 135 | def __handle_continuing_series(self, series, dry_run: bool = False): 136 | episodes = self.__get_media_episodes(series.get("id")) 137 | filtered_episodes = [episode for episode in episodes if episode['seasonNumber'] != 0] 138 | sorted_episodes = sorted(filtered_episodes, key=lambda x: (x['seasonNumber'], x['episodeNumber'])) 139 | episodes_to_load = sorted_episodes[:self.dynamic_load.episodes_to_load] 140 | episodes_to_unload = sorted_episodes[self.dynamic_load.episodes_to_load:] 141 | 142 | monitor_episode_ids = [] 143 | search_episode_ids = [] 144 | 145 | for episode in episodes_to_load: 146 | if not episode.get("monitored", False): 147 | monitor_episode_ids.append(episode["id"]) 148 | if not episode.get("hasFile", False): 149 | search_episode_ids.append(episode["id"]) 150 | 151 | try: 152 | if monitor_episode_ids: 153 | self.__monitor_media_episodes(monitor_episode_ids, True) 154 | if search_episode_ids: 155 | self.__search_media_episodes(search_episode_ids) 156 | except requests.exceptions.RequestException as err: 157 | logger.error("[SONARR] Failed to monitor %s. Error: %s", series.get("title"), err) 158 | return 0 159 | 160 | unmonitor_episode_ids = [] 161 | delete_episode_file_ids = [] 162 | 163 | for episode in episodes_to_unload: 164 | if episode.get("monitored", False): 165 | unmonitor_episode_ids.append(episode.get("id")) 166 | if episode.get("hasFile", False) and episode.get("episodeFileId") not in delete_episode_file_ids: 167 | delete_episode_file_ids.append(episode.get("episodeFileId")) 168 | 169 | size_on_disk = 0 170 | 171 | if dry_run: 172 | logger.info("[SONARR][DRY RUN] Would have unmonitored %s. Episodes unmonitored: %s", series.get("title"), len(unmonitor_episode_ids)) 173 | return size_on_disk 174 | 175 | try: 176 | if unmonitor_episode_ids: 177 | self.__monitor_media_episodes(unmonitor_episode_ids, False) 178 | logger.info("[SONARR] Unmonitored %s. Episodes unmonitored: %s", series.get("title"), len(unmonitor_episode_ids)) 179 | if delete_episode_file_ids: 180 | self.__delete_media_episodes(delete_episode_file_ids) 181 | original_size_on_disk = series.get("statistics", {}).get("sizeOnDisk", 0) 182 | series = self.__get_media_by_id(series.get("id")) 183 | series = self.__unmonitor_empty_seasons(series) 184 | series = self.__put_media(series) 185 | size_on_disk = original_size_on_disk - series.get("statistics", {}).get("sizeOnDisk", 0) 186 | 187 | except requests.exceptions.RequestException as err: 188 | logger.error("[SONARR] Failed to unmonitor %s. Error: %s", series.get("title"), err) 189 | return size_on_disk 190 | 191 | return size_on_disk 192 | 193 | def __get_episodes_to_load_and_unload(self, series, dynamic_media): 194 | episodes = self.__get_media_episodes(series.get("id")) 195 | filtered_episodes = [episode for episode in episodes if episode.get("seasonNumber", -1) != 0 and episode.get("airDate") < datetime.now().isoformat() and episode.get("airDate") > datetime.fromtimestamp(time.time() - self.dynamic_load.watched_deletion_threshold).isoformat()] 196 | sorted_episodes = sorted(filtered_episodes, key=lambda x: (x['seasonNumber'], x['episodeNumber'])) 197 | episode_index = next((index for (index, episode) in enumerate(sorted_episodes) if episode.get("seasonNumber", 0) == dynamic_media.season and episode.get("episodeNumber", 0) == dynamic_media.episode), None) 198 | 199 | episodes_to_load = [] 200 | episodes_to_unload = [] 201 | if episode_index is not None: 202 | load_index_start = episode_index + 1 203 | load_index_end = episode_index + self.dynamic_load.episodes_to_keep + 1 204 | 205 | episodes_to_load = sorted_episodes[load_index_start:load_index_end] if load_index_end >= load_index_start else [] 206 | 207 | unload_index_start = self.dynamic_load.episodes_to_keep 208 | unload_index_end = episode_index - self.dynamic_load.episodes_to_keep 209 | 210 | episodes_to_unload = sorted_episodes[unload_index_start:unload_index_end] if unload_index_end >= unload_index_start else [] 211 | return episodes_to_load, episodes_to_unload 212 | 213 | def __handle_episode_loading(self, episodes_to_load, series, dry_run): 214 | if not episodes_to_load: 215 | return 216 | 217 | monitor_episode_ids = [] 218 | search_episode_ids = [] 219 | for episode in episodes_to_load: 220 | if not episode.get("monitored", False): 221 | monitor_episode_ids.append(episode["id"]) 222 | if not episode.get("hasFile", False): 223 | self.__log_episode_loading(episode, series, dry_run) 224 | search_episode_ids.append(episode["id"]) 225 | if not dry_run: 226 | if monitor_episode_ids: 227 | self.__monitor_media_episodes(monitor_episode_ids, True) 228 | if search_episode_ids: 229 | self.__search_media_episodes(search_episode_ids) 230 | 231 | def __log_episode_loading(self, episode, series, dry_run): 232 | if dry_run: 233 | logger.info("[SONARR][DYNAMIC LOAD][DRY RUN] Would have loaded S%sE%s of %s", episode.get("seasonNumber"), episode.get("episodeNumber"), series.get("title")) 234 | else: 235 | logger.info("[SONARR][DYNAMIC LOAD] Loading S%sE%s of %s", episode.get("seasonNumber"), episode.get("episodeNumber"), series.get("title")) 236 | 237 | def __handle_episode_unloading(self, episodes_to_unload, series, dry_run): 238 | if not episodes_to_unload: 239 | return 0 240 | 241 | unmonitor_episode_ids = [] 242 | delete_episode_file_ids = [] 243 | for episode in episodes_to_unload: 244 | if episode.get("monitored", True): 245 | unmonitor_episode_ids.append(episode.get("id")) 246 | if episode.get("hasFile", True): 247 | self.__log_episode_unloading(episode, series, dry_run) 248 | if episode.get("episodeFileId") not in delete_episode_file_ids: 249 | delete_episode_file_ids.append(episode.get("episodeFileId")) 250 | size_on_disk = 0 251 | if not dry_run: 252 | if unmonitor_episode_ids: 253 | self.__monitor_media_episodes(unmonitor_episode_ids, False) 254 | if delete_episode_file_ids: 255 | self.__delete_media_episodes(delete_episode_file_ids) 256 | original_size_on_disk = series.get("statistics", {}).get("sizeOnDisk", 0) 257 | series = self.__get_media_by_id(series.get("id")) 258 | series = self.__unmonitor_empty_seasons(series) 259 | series = self.__put_media(series) 260 | size_on_disk = original_size_on_disk - series.get("statistics", {}).get("sizeOnDisk", 0) 261 | return size_on_disk 262 | 263 | def __log_episode_unloading(self, episode, series, dry_run): 264 | if dry_run: 265 | logger.info("[SONARR][DYNAMIC LOAD][DRY RUN] Would have unloaded S%sE%s of %s", episode.get("seasonNumber"), episode.get("episodeNumber"), series.get("title")) 266 | else: 267 | logger.info("[SONARR][DYNAMIC LOAD] Unloading S%sE%s of %s", episode.get("seasonNumber"), episode.get("episodeNumber"), series.get("title")) 268 | 269 | def __handle_dynamic_load(self, series, dynamic_media, dry_run: bool = False): 270 | episodes_to_load, episodes_to_unload = self.__get_episodes_to_load_and_unload(series, dynamic_media) 271 | size_on_disk = 0 272 | self.__handle_episode_loading(episodes_to_load, series, dry_run) 273 | if not dynamic_media.unload: 274 | return size_on_disk 275 | size_on_disk = self.__handle_episode_unloading(episodes_to_unload, series, dry_run) 276 | return size_on_disk 277 | 278 | @retry(tries=3, delay=5) 279 | def get_and_delete_media(self, media_to_delete: dict, dry_run: bool = False): 280 | """ 281 | Gets and deletes media with the given ID from the Sonarr API. 282 | 283 | Args: 284 | media_to_delete: A dictionary where the key is the ID of the media to delete and the value is the title of the media. 285 | dry_run: Whether to perform a dry run. 286 | 287 | Returns: 288 | None. 289 | 290 | Raises: 291 | requests.exceptions.RequestException: If the API request fails. 292 | """ 293 | media = self.__get_media() 294 | exempt_tag_ids = self.__get_exempt_tag_ids(self.exempt_tag_names) 295 | original_deletion_count = len(media_to_delete) 296 | exempt_count = 0 297 | 298 | total_size = 0 299 | 300 | for series in media: 301 | if str(series.get("tvdbId")) not in media_to_delete.keys(): 302 | continue 303 | 304 | if any(tag in exempt_tag_ids for tag in series.get("tags", [])): 305 | media_to_delete.pop(str(series.get("tvdbId"))) 306 | exempt_count += 1 307 | logger.info("[SONARR] Skipping %s because it is exempt.", series.get("title")) 308 | continue 309 | 310 | if series.get("id") is not None: 311 | ended = series.get("ended", False) 312 | if self.dynamic_load.enabled: 313 | total_size += self.__handle_continuing_series(series, dry_run) 314 | elif not self.monitor_continuing_series or ended: 315 | total_size += self.__handle_ended_series(series, dry_run) 316 | else: 317 | total_size += self.__handle_continuing_series(series, dry_run) 318 | 319 | if dry_run: 320 | logger.info("[SONARR][DRY RUN] Total series: %s. Series eligible for deletion: %s. Series deleted: %s. Series exempt: %s. Total space freed: %s.", len(media), original_deletion_count, len(media_to_delete), exempt_count, convert_bytes(total_size)) 321 | else: 322 | logger.info("[SONARR] Total series: %s. Series eligible for deletion: %s. Series deleted: %s. Series exempt: %s. Total space freed: %s.", len(media), original_deletion_count, len(media_to_delete), exempt_count, convert_bytes(total_size)) 323 | 324 | return media_to_delete 325 | 326 | @retry(tries=3, delay=5) 327 | def get_dynamic_load_media(self, media_to_load: dict, dry_run: bool = False): 328 | """ 329 | Gets and deletes media with the given ID from the Sonarr API. 330 | 331 | Args: 332 | media_to_load: A dictionary where the key is the ID of the media to load and the value is the title of the media. 333 | dry_run: Whether to perform a dry run. 334 | 335 | Returns: 336 | None. 337 | 338 | Raises: 339 | requests.exceptions.RequestException: If the API request fails. 340 | """ 341 | media = self.__get_media() 342 | exempt_tag_ids = self.__get_exempt_tag_ids(self.exempt_tag_names) 343 | 344 | total_size = 0 345 | 346 | for series in media: 347 | if str(series.get("tvdbId")) not in media_to_load.keys(): 348 | continue 349 | 350 | if any(tag in exempt_tag_ids for tag in series.get("tags", [])): 351 | media_to_load.pop(str(series.get("tvdbId"))) 352 | logger.info("[SONARR][DYNAMIC LOAD] Skipping %s because it is exempt.", series.get("title")) 353 | continue 354 | 355 | if series.get("id") is not None: 356 | dynamic_media = media_to_load.get(str(series.get("tvdbId"))) 357 | if dynamic_media is not None: 358 | total_size += self.__handle_dynamic_load(series, dynamic_media, dry_run) 359 | 360 | if dry_run and total_size > 0: 361 | logger.info("[SONARR][DYNAMIC LOAD][DRY RUN] Would have total space freed: %s.", convert_bytes(total_size)) 362 | elif total_size > 0: 363 | logger.info("[SONARR][DYNAMIC LOAD] Total space freed: %s.", convert_bytes(total_size)) 364 | 365 | return media_to_load 366 | -------------------------------------------------------------------------------- /src/config.py: -------------------------------------------------------------------------------- 1 | """This module contains the Config class which is used to store the configuration values for the application.""" 2 | import json 3 | import sys 4 | import re 5 | from typing import Any, Dict, List 6 | from dataclasses import dataclass, field 7 | 8 | CONFIG_FILE_NAME = "config.json" 9 | 10 | @dataclass 11 | class PlexConfig: 12 | """This class is used to store the configuration values for the Plex client.""" 13 | base_url: str 14 | token: str 15 | 16 | @dataclass 17 | class RadarrConfig: 18 | """This class is used to store the configuration values for the Radarr client.""" 19 | enabled: bool 20 | api_key: str 21 | base_url: str 22 | exempt_tag_names: List[str] = field(default_factory=list) 23 | watched_deletion_threshold: int = 7776000 24 | unwatched_deletion_threshold: int = 2592000 25 | 26 | @dataclass 27 | class DynamicLoad: 28 | """This class is used to store the configuration values for the dynamic load feature.""" 29 | enabled: bool 30 | episodes_to_load: int 31 | episodes_to_keep: int 32 | watched_deletion_threshold: int = 7776000 33 | schedule_interval: int = 600 34 | 35 | @dataclass 36 | class SonarrConfig: 37 | """This class is used to store the configuration values for the Sonarr client.""" 38 | enabled: bool 39 | api_key: str 40 | base_url: str 41 | monitor_continuing_series: bool 42 | exempt_tag_names: List[str] = field(default_factory=list) 43 | dynamic_load: DynamicLoad = field(default_factory=DynamicLoad) 44 | watched_deletion_threshold: int = 7776000 45 | unwatched_deletion_threshold: int = 2592000 46 | 47 | @dataclass 48 | class OverseerrConfig: 49 | """This class is used to store the configuration values for the Overseerr client.""" 50 | enabled: bool 51 | api_key: str 52 | base_url: str 53 | fetch_limit: int 54 | 55 | @dataclass 56 | class ProgressiveDeletion: 57 | """This class is used to store the configuration values for the progressive deletion feature.""" 58 | enabled: bool 59 | maximum_deletion_cycles: int 60 | threshold_reduction_per_cycle: int 61 | 62 | @dataclass 63 | class FreeSpace: 64 | """This class is used to store the configuration values for the free space feature.""" 65 | enabled: bool 66 | minimum_free_space_percentage: int 67 | path: str 68 | prevent_age_based_deletion: bool 69 | prevent_dynamic_load: bool 70 | progressive_deletion: field(default_factory=ProgressiveDeletion) 71 | 72 | 73 | @dataclass 74 | class Experimental: 75 | """This class is used to store the configuration values for the experimental features.""" 76 | free_space: FreeSpace = field(default_factory=FreeSpace) 77 | 78 | @dataclass 79 | class Config: 80 | """This class is used to store the configuration values for the application.""" 81 | plex: PlexConfig 82 | radarr: RadarrConfig 83 | sonarr: SonarrConfig 84 | overseerr: OverseerrConfig 85 | dry_run: bool 86 | log_level: str 87 | schedule_interval: int = 86400 88 | 89 | 90 | def __init__(self): 91 | self.dry_run = True 92 | self.log_level = "INFO" 93 | self.schedule_interval = 86400 94 | self.plex = PlexConfig("https://plex.domain.com", "") 95 | self.radarr = RadarrConfig(False, "", "https://radarr.domain.com/api/v3", [], 7776000, 2592000) 96 | self.sonarr = SonarrConfig(False, "", "https://sonarr.domain.com/api/v3", True, [], DynamicLoad(False, 3, 3, 7776000, 600), 7776000, 2592000) 97 | self.overseerr = OverseerrConfig(False, "", "https://overseerr.domain.com/api/v1", 10) 98 | self.experimental = Experimental(FreeSpace(False, 0, "", False, False, ProgressiveDeletion(False, 0, 86400))) 99 | 100 | config = self._get_config() 101 | 102 | try: 103 | self._parse_config(config) 104 | except TypeError as err: 105 | print("Error in configuration file:") 106 | print(err) 107 | sys.exit() 108 | 109 | def _get_config(self) -> Dict[str, Any]: 110 | config = {} 111 | try: 112 | with open(CONFIG_FILE_NAME, encoding="utf-8") as file: 113 | config = json.load(file) 114 | except FileNotFoundError: 115 | pass 116 | 117 | return config 118 | 119 | def _parse_config(self, config: Dict[str, Any]) -> None: 120 | required_keys = [ 121 | "dry_run", 122 | "log_level", 123 | "schedule_interval", 124 | "plex" 125 | ] 126 | 127 | for key in required_keys: 128 | if key not in config: 129 | raise KeyError(f"Missing required configuration key: {key}") 130 | 131 | try: 132 | self.dry_run = self._get_value_or_default(config, "dry_run", True) 133 | self.log_level = self._get_value_or_default(config, "log_level", "INFO") 134 | self.schedule_interval = self._get_value_or_default(config, "schedule_interval", 86400, True) 135 | plex_config = self._get_value_or_default(config, "plex", {}) 136 | self.plex = PlexConfig(self._get_value_or_default(plex_config, "base_url", "https://plex.domain.com"), self._get_value_or_default(plex_config, "token", "")) 137 | radarr_config = self._get_value_or_default(config, "radarr", {}) 138 | self.radarr = RadarrConfig(self._get_value_or_default(radarr_config, "enabled", False), self._get_value_or_default(radarr_config, "api_key", ""), self._get_value_or_default(radarr_config, "base_url", "https://radarr.domain.com/api/v3"), self._get_value_or_default(radarr_config, "exempt_tag_names", []), self._get_value_or_default(radarr_config, "watched_deletion_threshold", 7776000, True), self._get_value_or_default(radarr_config, "unwatched_deletion_threshold", 2592000, True)) 139 | sonarr_config = self._get_value_or_default(config, "sonarr", {}) 140 | dynamic_load_config = self._get_value_or_default(sonarr_config, "dynamic_load", {}) 141 | self.sonarr = SonarrConfig(self._get_value_or_default(sonarr_config, "enabled", False), self._get_value_or_default(sonarr_config, "api_key", ""), self._get_value_or_default(sonarr_config, "base_url", "https://sonarr.domain.com/api/v3"), self._get_value_or_default(sonarr_config, "monitor_continuing_series", True), self._get_value_or_default(sonarr_config, "exempt_tag_names", []), DynamicLoad(self._get_value_or_default(dynamic_load_config, "enabled", False), self._get_value_or_default(dynamic_load_config, "episodes_to_load", 3), self._get_value_or_default(dynamic_load_config, "episodes_to_keep", 3), self._get_value_or_default(dynamic_load_config, "watched_deletion_threshold", 7776000, True), self._get_value_or_default(dynamic_load_config, "schedule_interval", 600, True)), self._get_value_or_default(sonarr_config, "watched_deletion_threshold", 7776000, True), self._get_value_or_default(sonarr_config, "unwatched_deletion_threshold", 2592000, True)) 142 | overseerr_config = self._get_value_or_default(config, "overseerr", {}) 143 | self.overseerr = OverseerrConfig(self._get_value_or_default(overseerr_config, "enabled", False), self._get_value_or_default(overseerr_config, "api_key", ""), self._get_value_or_default(overseerr_config, "base_url", "https://overseerr.domain.com/api/v1"), self._get_value_or_default(overseerr_config, "fetch_limit", 10)) 144 | experimental_config = self._get_value_or_default(config, "experimental", {}) 145 | free_space_config = self._get_value_or_default(experimental_config, "free_space", {}) 146 | progressive_deletion_config = self._get_value_or_default(free_space_config, "progressive_deletion", {}) 147 | self.experimental = Experimental(FreeSpace(self._get_value_or_default(free_space_config, "enabled", False), self._get_value_or_default(free_space_config, "minimum_free_space_percentage", 0), self._get_value_or_default(free_space_config, "path", ""), self._get_value_or_default(free_space_config, "prevent_age_based_deletion", False), self._get_value_or_default(free_space_config, "prevent_dynamic_load", False), ProgressiveDeletion(self._get_value_or_default(progressive_deletion_config, "enabled", False), self._get_value_or_default(progressive_deletion_config, "maximum_deletion_cycles", 0), self._get_value_or_default(progressive_deletion_config, "threshold_reduction_per_cycle", 86400, True)))) 148 | except ValueError as err: 149 | print("Error in configuration file:") 150 | print(err) 151 | sys.exit() 152 | 153 | def _get_value_or_default(self, config: Dict[str, Any], key: str, default: Any, convert_to_seconds: bool = False) -> Any: 154 | if key not in config: 155 | print("Missing configuration key: %s. Using default value: %s", key, default) 156 | return default 157 | 158 | if convert_to_seconds: 159 | return self._convert_to_seconds(config.get(key, default), key) 160 | 161 | return config.get(key, default) 162 | 163 | def _convert_to_seconds(self, time: str, key_name: str) -> int: 164 | """ 165 | Converts a time string to seconds. 166 | 167 | Args: 168 | time: A string representing a time interval in the format of . (e.g. 45s (seconds), 30m (minutes), 2h (hours), 1d (days)) 169 | 170 | Returns: 171 | An integer representing the time interval in seconds. 172 | 173 | Raises: 174 | ValueError: If the time string is not in the correct format or contains an invalid time unit. 175 | """ 176 | # If the time is already an integer, return it 177 | try: 178 | return int(time) 179 | except ValueError: 180 | pass 181 | 182 | match = re.match(r'^(\d+)([smhd])$', time.lower()) 183 | 184 | if not match: 185 | raise ValueError(f"{key_name} must be in the format of . (e.g. 45s (seconds), 30m (minutes), 2h (hours), 1d (days))") 186 | 187 | value, unit = int(match.group(1)), match.group(2) 188 | 189 | if unit == "s": 190 | return value 191 | elif unit == "m": 192 | return value * 60 193 | elif unit == "h": 194 | return value * 3600 195 | elif unit == "d": 196 | return value * 86400 197 | else: 198 | return value -------------------------------------------------------------------------------- /src/jobs.py: -------------------------------------------------------------------------------- 1 | """ 2 | This module contains the JobRunner class, 3 | which is responsible for running the job function on a schedule. 4 | """ 5 | import time 6 | import shutil 7 | from collections import defaultdict 8 | import schedule 9 | from src.clients.plex import PlexClient 10 | from src.clients.radarr import RadarrClient 11 | from src.clients.sonarr import SonarrClient 12 | from src.clients.overseerr import OverseerrClient 13 | from src.util import convert_bytes, convert_seconds 14 | from src.logger import logger 15 | 16 | class JobRunner: 17 | """ 18 | Class for running the job function on a schedule. 19 | """ 20 | def __init__(self, config): 21 | self.config = config 22 | self.dry_run = config.dry_run 23 | self.schedule_interval = config.schedule_interval 24 | self.plex = PlexClient(config) 25 | self.radarr = RadarrClient(config) 26 | self.sonarr = SonarrClient(config) 27 | self.overseerr = OverseerrClient(config) 28 | self.radarr_enabled = config.radarr.enabled 29 | self.radarr_watched_deletion_threshold = config.radarr.watched_deletion_threshold 30 | self.radarr_unwatched_deletion_threshold = config.radarr.unwatched_deletion_threshold 31 | self.sonarr_enabled = config.sonarr.enabled 32 | self.dynamic_load = config.sonarr.dynamic_load 33 | self.sonarr_watched_deletion_threshold = config.sonarr.watched_deletion_threshold 34 | self.sonarr_unwatched_deletion_threshold = config.sonarr.unwatched_deletion_threshold 35 | self.overseerr_enabled = config.overseerr.enabled 36 | self.free_space = config.experimental.free_space 37 | self.progressive_deletion = config.experimental.free_space.progressive_deletion 38 | 39 | def __free_space_below_minimum(self): 40 | """ 41 | Checks the free space on the drive where the media is stored. 42 | """ 43 | total, used, free = shutil.disk_usage(self.config.experimental.free_space.path) 44 | free_space_percentage = round(free / total * 100) 45 | logger.info("[JOB][FREE SPACE] Total: %s. Used: %s. Free: %s. Free space percentage: %d%%.", convert_bytes(total), convert_bytes(used), convert_bytes(free), free_space_percentage) 46 | if free_space_percentage < self.config.experimental.free_space.minimum_free_space_percentage: 47 | logger.info("[JOB][FREE SPACE] Free space is below the minimum threshold of %d%%.", self.config.experimental.free_space.minimum_free_space_percentage) 48 | return True 49 | 50 | return False 51 | 52 | def run(self): 53 | """ 54 | Runs the job function on a schedule. 55 | """ 56 | self.get_and_delete_job() 57 | schedule.every(self.schedule_interval).seconds.do(self.get_and_delete_job) 58 | 59 | if self.dynamic_load.enabled: 60 | self.dynamic_load_job() 61 | schedule.every(self.dynamic_load.schedule_interval).seconds.do(self.dynamic_load_job) 62 | 63 | while True: 64 | schedule.run_pending() 65 | time.sleep(1) 66 | 67 | def get_and_delete_job(self, deletion_cycle: int = 0): 68 | """ 69 | This function gets unplayed movies and TV shows and deletes them if they are eligible for deletion. 70 | """ 71 | logger.debug("[JOB] Fetch and delete job started") 72 | 73 | if (self.free_space.enabled and self.free_space.prevent_age_based_deletion) and not self.__free_space_below_minimum(): 74 | logger.info("[JOB] Free space is above the minimum threshold. Skipping job.") 75 | return 76 | 77 | if self.radarr_enabled: 78 | logger.debug("[JOB] Fetching and deleting movies") 79 | self.get_and_delete_movies() 80 | 81 | if self.sonarr_enabled: 82 | logger.debug("[JOB] Fetching and deleting series") 83 | self.get_and_delete_series() 84 | 85 | if self.free_space.enabled and self.progressive_deletion.enabled and self.__free_space_below_minimum(): 86 | self.radarr_watched_deletion_threshold -= self.progressive_deletion.threshold_reduction_per_cycle if self.radarr_watched_deletion_threshold - self.progressive_deletion.threshold_reduction_per_cycle > 0 else 0 87 | self.radarr_unwatched_deletion_threshold -= self.progressive_deletion.threshold_reduction_per_cycle if self.radarr_unwatched_deletion_threshold - self.progressive_deletion.threshold_reduction_per_cycle > 0 else 0 88 | self.sonarr_watched_deletion_threshold -= self.progressive_deletion.threshold_reduction_per_cycle if self.sonarr_watched_deletion_threshold - self.progressive_deletion.threshold_reduction_per_cycle > 0 else 0 89 | self.sonarr_unwatched_deletion_threshold -= self.progressive_deletion.threshold_reduction_per_cycle if self.sonarr_unwatched_deletion_threshold - self.progressive_deletion.threshold_reduction_per_cycle > 0 else 0 90 | logger.info("[JOB][FREE SPACE] Free space is still below the minimum threshold. Decreasing deletion thresholds by %s. New thresholds: Radarr watched: %s. Radarr unwatched: %s. Sonarr watched: %s. Sonarr unwatched: %s.", convert_seconds(self.progressive_deletion.threshold_reduction_per_cycle), convert_seconds(self.radarr_watched_deletion_threshold), convert_seconds(self.radarr_unwatched_deletion_threshold), convert_seconds(self.sonarr_watched_deletion_threshold), convert_seconds(self.sonarr_unwatched_deletion_threshold)) 91 | self.get_and_delete_job(deletion_cycle + 1) 92 | elif deletion_cycle > 0 and deletion_cycle <= self.progressive_deletion.maximum_deletion_cycles: 93 | self.radarr_watched_deletion_threshold += (self.progressive_deletion.threshold_reduction_per_cycle * deletion_cycle) 94 | self.radarr_unwatched_deletion_threshold += (self.progressive_deletion.threshold_reduction_per_cycle * deletion_cycle) 95 | self.sonarr_watched_deletion_threshold += (self.progressive_deletion.threshold_reduction_per_cycle * deletion_cycle) 96 | self.sonarr_unwatched_deletion_threshold += (self.progressive_deletion.threshold_reduction_per_cycle * deletion_cycle) 97 | logger.info("[JOB][FREE SPACE] Free space is above the minimum threshold. Increasing deletion thresholds to original levels. New thresholds: Radarr watched: %s. Radarr unwatched: %s. Sonarr watched: %s. Sonarr unwatched: %s.", convert_seconds(self.radarr_watched_deletion_threshold), convert_seconds(self.radarr_unwatched_deletion_threshold), convert_seconds(self.sonarr_watched_deletion_threshold), convert_seconds(self.sonarr_unwatched_deletion_threshold)) 98 | 99 | 100 | logger.debug("[JOB] Fetch and delete job finished") 101 | 102 | def dynamic_load_job(self): 103 | """ 104 | This function dynamically loads and unloads the Plex library based on the current time. 105 | """ 106 | logger.debug("[JOB] Dynamic load job started") 107 | 108 | if (self.free_space.enabled and self.free_space.prevent_dynamic_load) and not self.__free_space_below_minimum(): 109 | logger.info("[JOB] Free space is above the minimum threshold. Skipping job.") 110 | return 111 | 112 | if self.sonarr_enabled: 113 | logger.debug("[JOB] Dynamic loading series") 114 | self.dynamic_load_series() 115 | 116 | logger.debug("[JOB] Dynamic load job finished") 117 | 118 | def get_and_delete_movies(self): 119 | """ 120 | Fetches unplayed movies and deletes them if they are eligible for deletion. 121 | """ 122 | media = self.plex.get_expired_media("movie", self.radarr_watched_deletion_threshold, self.radarr_unwatched_deletion_threshold, self.schedule_interval) 123 | 124 | media_to_delete = {} 125 | for item in media: 126 | tmdb_id = next( 127 | (guid.id.split("tmdb://")[1].split("?")[0] for guid in item.guids if guid.id.startswith("tmdb://")), 128 | None, 129 | ) 130 | if tmdb_id is not None: 131 | media_to_delete[tmdb_id] = item.title 132 | 133 | media_deleted = self.radarr.get_and_delete_media(media_to_delete, self.dry_run) 134 | if self.overseerr_enabled: 135 | self.overseerr.get_and_delete_media(media_deleted, self.dry_run) 136 | 137 | def get_and_delete_series(self): 138 | """ 139 | Fetches unplayed TV shows and deletes them if they are eligible for deletion. 140 | """ 141 | media = self.plex.get_expired_media("show", self.sonarr_watched_deletion_threshold, self.sonarr_unwatched_deletion_threshold, self.schedule_interval) 142 | 143 | media_to_delete = {} 144 | for item in media: 145 | tvdb_id = next( 146 | (guid.id.split("tvdb://")[1].split("?")[0] for guid in item.guids if guid.id.startswith("tvdb://")), 147 | None, 148 | ) 149 | if tvdb_id is not None: 150 | media_to_delete[tvdb_id] = item.title 151 | 152 | media_deleted = self.sonarr.get_and_delete_media(media_to_delete, self.dry_run) 153 | if self.overseerr_enabled: 154 | self.overseerr.get_and_delete_media(media_deleted, self.dry_run) 155 | 156 | def dynamic_load_series(self): 157 | """ 158 | Dynamically loads and unloads TV shows based on current media consumption. 159 | """ 160 | dynamic_media = self.plex.get_dynamic_load_media(self.dynamic_load.watched_deletion_threshold) 161 | 162 | media_to_load = defaultdict(list) 163 | for item in dynamic_media: 164 | tvdb_id = next( 165 | (guid.id.split("tvdb://")[1].split("?")[0] for guid in item.media.guids if guid.id.startswith("tvdb://")), 166 | None, 167 | ) 168 | if tvdb_id is not None: 169 | media_to_load[tvdb_id] = item 170 | 171 | self.sonarr.get_dynamic_load_media(media_to_load, self.dry_run) 172 | -------------------------------------------------------------------------------- /src/logger.py: -------------------------------------------------------------------------------- 1 | """This module is used to configure the logger for the application.""" 2 | import logging 3 | from logging.handlers import RotatingFileHandler 4 | from src.config import Config 5 | 6 | config = Config() 7 | 8 | logger = logging.getLogger() 9 | logger.setLevel(logging.getLevelName(config.log_level)) 10 | 11 | file_handler = RotatingFileHandler('app.log', maxBytes=1000000, backupCount=3) 12 | stream_handler = logging.StreamHandler() 13 | 14 | formatter = logging.Formatter('%(asctime)s - %(levelname)s - %(message)s') 15 | 16 | file_handler.setFormatter(formatter) 17 | stream_handler.setFormatter(formatter) 18 | 19 | logger.addHandler(file_handler) 20 | logger.addHandler(stream_handler) 21 | -------------------------------------------------------------------------------- /src/main.py: -------------------------------------------------------------------------------- 1 | """Main module for the application.""" 2 | from src.config import Config 3 | from src.jobs import JobRunner 4 | from src.logger import logger 5 | 6 | 7 | def main(args): 8 | """ 9 | Initializes the configuration and starts the job runner. 10 | 11 | Args: 12 | args: Command line arguments. 13 | 14 | Returns: 15 | None 16 | """ 17 | logger.info("Starting Eraserr") 18 | config = Config() 19 | 20 | if args.dry_run: 21 | config.dry_run = args.dry_run 22 | 23 | job_runner = JobRunner(config) 24 | job_runner.run() 25 | -------------------------------------------------------------------------------- /src/models/dynamicmedia.py: -------------------------------------------------------------------------------- 1 | """Module for DynamicMedia class.""" 2 | class DynamicMedia: 3 | """Class for representing dynamic media.""" 4 | def __init__(self, media, unload: bool, season: int, episode: int): 5 | self.media = media 6 | self.unload = unload 7 | self.season = season 8 | self.episode = episode 9 | -------------------------------------------------------------------------------- /src/util.py: -------------------------------------------------------------------------------- 1 | """This file contains utility functions for the project.""" 2 | def convert_bytes(num): 3 | """ 4 | This function will convert bytes to MB, GB, or TB 5 | """ 6 | for unit in ["bytes", "KB", "MB", "GB", "TB"]: 7 | if num < 1024.0: 8 | return f"{num:3.2f} {unit}".strip() 9 | num /= 1024.0 10 | 11 | return f"{num:3.2f}".strip() 12 | 13 | def convert_seconds(num): 14 | """ 15 | This function will convert seconds to minutes, hours, or days 16 | """ 17 | for unit, duration in [("seconds", 60), ("minutes", 60), ("hours", 24)]: 18 | if num < duration: 19 | return f"{num:3.0f} {unit}".strip() 20 | num /= duration 21 | 22 | return f"{num:3.0f} days".strip() 23 | --------------------------------------------------------------------------------