Skip to content

bin101/Sonarr-Season-Unmonitor

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

1 Commit
 
 
 
 
 
 

Repository files navigation

Sonarr Season Unmonitor

Automatically unmonitor seasons in Sonarr when all episodes have been deleted and no future episodes are expected. Prevents unnecessary searches for completed/cancelled seasons.

🎯 Main Features

  • Automatic Season Unmonitoring: Unmonitors seasons after episode deletion
  • Future Episode Detection: Keeps seasons monitored if future episodes are expected
  • Bulk Cleanup Mode: Processes all series at once
  • Custom Script Integration: Runs automatically on episode deletion
  • Background Execution with Delay: Spawns background process with 10-minute delay to avoid race conditions
  • Test Mode: Safe test runs without changes
  • Environment Variable Support: Docker-friendly configuration

📋 Requirements

  • Python 3.6+
  • requests library
  • Sonarr v3 API
  • Configured API connection

🚀 Installation

  1. Copy script to Sonarr scripts folder:
cp sonarr-season-unmonitor.py /path/to/sonarr/scripts/
chmod +x /path/to/sonarr/scripts/sonarr-season-unmonitor.py
  1. Create configuration file (see Configuration)

  2. Set up in Sonarr as Custom Script (see Sonarr Setup)

Configuration

Config File (season-unmonitor.conf)

[API]
url = http://localhost:8989
key = your_sonarr_api_key
url_base =

Environment Variables

# API Configuration
API_KEY=your_sonarr_api_key
SONARR_URL=http://localhost:8989
URL_BASE=/sonarr

Docker Compose

environment:
  - API_KEY=your_sonarr_api_key
  - SONARR_URL=http://sonarr:8989
  - URL_BASE=/sonarr

🔧 Usage

As Sonarr Custom Script (Recommended)

# Runs automatically on episode deletion
# Script spawns a background process with 10-minute delay
# to avoid race conditions with other scripts
/scripts/sonarr-season-unmonitor.py

Note: When triggered by EpisodeFileDelete event, the script immediately spawns a background process with a 10-minute delay and exits. This allows Sonarr to continue processing other tasks while preventing race conditions with other custom scripts that may be running simultaneously.

Bulk Cleanup Mode

# Process all series and seasons
/scripts/sonarr-season-unmonitor.py --cleanup-all

Test Mode

# Test run without changes
/scripts/sonarr-season-unmonitor.py --test

Configuration Test

# Test API connection
/scripts/sonarr-season-unmonitor.py --test-config

Custom Delay (Advanced)

# Adjust delay for background execution (default: 10 minutes)
/scripts/sonarr-season-unmonitor.py --delay-minutes 5

📝 Command Line Arguments

Argument Description Default
--test Test mode, no changes False
--cleanup-all Process all series False
--test-config Test API configuration False
--config PATH Path to configuration file Auto-Detection
--delay-minutes N Delay in minutes for background execution 10
--delayed-execution Internal flag for background process Auto-set
--debug Enable debug mode with detailed logging False

Sonarr Setup

Configure Custom Script

  1. Settings → Connect → + → Custom Script
  2. Name: Season Unmonitor
  3. On Episode File Delete: ✅ Enabled
  4. Path: /scripts/sonarr-season-unmonitor.py
  5. Arguments: (leave empty)

Run Test

  1. Click Test in Sonarr
  2. Check logs:
✅ Successfully connected to Sonarr API
✅ Configuration test completed successfully!

📊 How It Works

Season Unmonitoring Logic

  1. Episode Deletion Trigger: Script runs when episode is deleted
  2. Background Process Spawn: Immediately spawns detached background process with configurable delay (default: 10 minutes)
  3. Main Process Exit: Main process exits immediately, allowing Sonarr to continue
  4. Delay Wait: Background process waits for specified delay to avoid race conditions
  5. Season Analysis: Checks if season has any remaining episodes
  6. Future Episode Check: Verifies no monitored episodes with future air dates
  7. Unmonitor Decision: Unmonitors season if empty and no future episodes
  8. Logging: Records all actions for review

Background Execution & Race Condition Prevention

When triggered by Sonarr's EpisodeFileDelete event:

  • The script immediately spawns a background process and exits
  • Sonarr continues processing without waiting
  • The background process waits 10 minutes (configurable) before executing
  • This prevents race conditions with other scripts that may run on the same event
  • Environment variables from Sonarr are automatically inherited by the background process

Example

Season 3 - 10 episodes total

  • Episodes 1-8: Deleted
  • Episodes 9-10: Never downloaded, air date in past
  • Result: Season 3 unmonitored ✅

Season 4 - 12 episodes total

  • Episodes 1-8: Deleted
  • Episodes 9-10: Never downloaded, air date in future
  • Result: Season 4 remains monitored ⏳

Future Episode Detection

The script checks for monitored episodes with:

  • airDate in the future (after today)
  • monitored = true
  • hasFile = false

This prevents unmonitoring seasons that still have upcoming episodes.

🔍 Logging

Log File

  • Path: /config/logs/sonarr-season-unmonitor.txt
  • Rotation: Weekly, 4 backups
  • Format: YYYY-MM-DD HH:MM:SS LEVEL Message

Log Levels

  • INFO: Normal operations
  • DEBUG: Detailed information (--test)
  • WARNING: Non-critical issues
  • ERROR: Critical errors

Example Logs

2026-01-12 14:30:00 INFO EpisodeFileDelete event detected. Spawning background process with delay...
2026-01-12 14:30:00 INFO Spawning background process with 10 minute delay...
2026-01-12 14:30:00 INFO Background process spawned with PID 12345
2026-01-12 14:30:00 INFO Background process spawned. Main script exiting to allow Sonarr to continue.

... 10 minutes later in background process ...

2026-01-12 14:40:00 INFO Background process started. Waiting 10 minutes (600 seconds) before processing...
2026-01-12 14:40:00 INFO Delay completed. Continuing with execution...
2026-01-12 14:40:01 INFO Processing EpisodeFileDelete event for series 'Breaking Bad' (ID: 1), Season 1
2026-01-12 14:40:02 INFO Season 1 of 'Breaking Bad' has 13 total episodes, 0 still have files
2026-01-12 14:40:03 INFO No episodes with files remaining in season 1 and no future monitored episodes. Unmonitoring season.
2026-01-12 14:40:04 INFO Successfully unmonitored season 1 for series 'Breaking Bad'

🛠️ Troubleshooting

Common Issues

Environment variable not found

❌ sonarr_eventtype not found in environment variables
  • Run in --cleanup-all mode for manual execution
  • Check Custom Script configuration in Sonarr

API connection failed

❌ Failed to connect to Sonarr API
  • Check Sonarr URL
  • Validate API key
  • Test network connection

No configuration found

❌ No configuration file found and no environment variables set
  • Create config file
  • Set environment variables

Collect Debug Information

# Test configuration
/scripts/sonarr-season-unmonitor.py --test-config

# Test mode with full output
/scripts/sonarr-season-unmonitor.py --test --cleanup-all

🔒 Security

Safe Operations

  • Read-Only Tests: Test mode only reads data
  • Conservative Logic: Only unmonitors when certain
  • Validation: Checks all inputs before processing

Backup Recommendations

  • Sonarr Database: Regular backups
  • Config Files: Version control configuration
  • Monitor Settings: Note current monitoring state

🔄 Environment Variable Priority

  1. Environment Variables (highest priority)
  2. Config File
  3. Default Values (lowest priority)

📈 Performance

Optimizations

  • Efficient API Usage: Minimal requests
  • Smart Processing: Only checks relevant seasons
  • Robust Error Handling: Continues on errors
  • Background Execution: Doesn't block Sonarr operations

Typical Runtime

  • Single Season: ~1-2 seconds (after 10-minute delay)
  • Series (10 seasons): ~5-10 seconds
  • Bulk Mode (100 series): ~2-5 minutes

📚 Example Scenarios

Scenario 1: Custom Script Mode

# Triggered by Sonarr when episode is deleted
# Environment variables automatically set:
# sonarr_eventtype=EpisodeFileDelete
# sonarr_series_id=123
# sonarr_series_title=Breaking Bad
# sonarr_episodefile_seasonnumber=1
# 
# Script immediately spawns background process and exits
# Background process waits 10 minutes before processing

Scenario 2: Manual Cleanup

# Clean up all series manually
/scripts/sonarr-season-unmonitor.py --cleanup-all

Scenario 3: Docker Container

services:
  sonarr:
    environment:
      - API_KEY=${SONARR_API_KEY}
      - SONARR_URL=http://sonarr:8989
    volumes:
      - ./scripts:/scripts

Scenario 4: Cronjob

# Weekly cleanup at Sunday 2 AM
0 2 * * 0 /scripts/sonarr-season-unmonitor.py --cleanup-all

🧪 Testing

Configuration Test

/scripts/sonarr-season-unmonitor.py --test-config

Expected Output:

✅ Successfully connected to Sonarr API
✅ System status: OK
✅ Configuration test completed successfully!

Dry Run Test

/scripts/sonarr-season-unmonitor.py --test --cleanup-all

Expected Output:

🧪 TEST MODE: No changes will be made
📺 Processing series: Breaking Bad (ID: 1)
📅 Season 1: Would unmonitor (no files, no future episodes)
📅 Season 2: Keeping monitored (has future episodes)

🚨 Important Notes

Conservative Approach

The script uses a conservative approach:

  • Only unmonitors when absolutely certain
  • Preserves monitoring for edge cases
  • Logs all decisions for transparency

Future Episode Logic

A season is kept monitored if it has any monitored episode with:

  • airDate > today
  • monitored = true
  • hasFile = false

This handles:

  • Announced but not yet aired episodes
  • Episodes with uncertain air dates
  • Upcoming season continuations

🔗 See Also

About

Automatic Sonarr Season Unmonitoring

Resources

Stars

Watchers

Forks

Releases

Packages

Contributors

Languages