feat: Enhance Plex management with library scanner integration and bash completion support

This commit is contained in:
Peter Wood
2025-06-26 09:15:24 -04:00
parent 563daa51af
commit 6e84bb33d6
4 changed files with 326 additions and 36 deletions

View File

@@ -43,7 +43,7 @@ The completion system provides intelligent tab completion for command-line flags
- `--help`, `-h` - Show help message
- `--dry-run` - Preview backup without executing
- `--no-upload` - Skip B2 upload (local backup only)
- `--no-upload` - Skip B2 upload (local backup only)
- `--verbose` - Enable verbose logging
### backup-plex.sh
@@ -187,7 +187,7 @@ backup-immich.sh --<TAB>
# Relative path
./backup-immich.sh --<TAB>
# Absolute path
# Absolute path
/home/acedanger/shell/immich/backup-immich.sh --<TAB>
```
@@ -276,9 +276,9 @@ _script_name_completion() {
COMPREPLY=()
cur="${COMP_WORDS[COMP_CWORD]}"
prev="${COMP_WORDS[COMP_CWORD-1]}"
opts="--option1 --option2 --option3"
# Handle special cases
case "${prev}" in
--special-option)
@@ -286,7 +286,7 @@ _script_name_completion() {
return 0
;;
esac
# Standard flag completion
if [[ ${cur} == -* ]]; then
COMPREPLY=( $(compgen -W "${opts}" -- ${cur}) )

View File

@@ -131,7 +131,7 @@ For commands that accept boolean flags:
$ scan-plex-libraries.sh refresh 29 <TAB>
true false
# Analyze with deep flag
# Analyze with deep flag
$ scan-plex-libraries.sh analyze 29 <TAB>
true false
```

View File

@@ -2,7 +2,7 @@
# Bash completion for Plex-related scripts
# Author: Peter Wood <peter@peterwood.dev>
#
#
# This file provides intelligent tab completion for:
# - plex.sh (main Plex management script)
# - scan-plex-libraries.sh (library scanner script)
@@ -16,16 +16,16 @@
_plex_sh_completion() {
local cur="${COMP_WORDS[COMP_CWORD]}"
local prev="${COMP_WORDS[COMP_CWORD-1]}"
# Available commands for plex.sh
local commands="start stop restart status scan repair nuclear help"
# If we're completing the first argument (command)
if [[ ${COMP_CWORD} -eq 1 ]]; then
COMPREPLY=($(compgen -W "$commands" -- "$cur"))
return 0
fi
# If previous word was 'scan', complete with scanner options
if [[ "$prev" == "scan" ]]; then
local scanner_commands="list scan refresh analyze generate tree interactive"
@@ -33,7 +33,7 @@ _plex_sh_completion() {
COMPREPLY=($(compgen -W "$scanner_commands $scanner_options" -- "$cur"))
return 0
fi
# For other commands, no additional completion needed
return 0
}
@@ -42,11 +42,11 @@ _plex_sh_completion() {
_scan_plex_libraries_completion() {
local cur="${COMP_WORDS[COMP_CWORD]}"
local prev="${COMP_WORDS[COMP_CWORD-1]}"
# Available commands for scan-plex-libraries.sh
local commands="list scan refresh analyze generate tree interactive"
local options="-v --verbose -h --help"
# If we're completing the first argument
if [[ ${COMP_CWORD} -eq 1 ]]; then
# If it starts with -, show options
@@ -57,7 +57,7 @@ _scan_plex_libraries_completion() {
fi
return 0
fi
# Handle specific command completions
case "${COMP_WORDS[1]}" in
refresh)
@@ -79,19 +79,19 @@ _scan_plex_libraries_completion() {
# Could potentially call the script to get section IDs but that's expensive
;;
esac
return 0
}
# Completion function for generic plex aliases that might pass through to plex.sh
_plex_alias_completion() {
local cur="${COMP_WORDS[COMP_CWORD]}"
# For plex-scan alias, complete with scanner commands
if [[ "${COMP_WORDS[0]}" == *"plex-scan"* ]]; then
local scanner_commands="list scan refresh analyze generate tree interactive"
local scanner_options="-v --verbose -h --help"
if [[ ${COMP_CWORD} -eq 1 ]]; then
if [[ "$cur" == -* ]]; then
COMPREPLY=($(compgen -W "$scanner_options" -- "$cur"))
@@ -105,13 +105,13 @@ _plex_alias_completion() {
fi
return 0
fi
# For plex-scanner alias, use the full scanner completion
if [[ "${COMP_WORDS[0]}" == *"plex-scanner"* ]]; then
_scan_plex_libraries_completion
return 0
fi
# For other plex aliases, just complete with main plex.sh commands
local commands="start stop restart status scan repair nuclear help"
COMPREPLY=($(compgen -W "$commands" -- "$cur"))
@@ -123,10 +123,10 @@ _plex_alias_completion() {
_plex_scanner_with_sections() {
local cur="${COMP_WORDS[COMP_CWORD]}"
local prev="${COMP_WORDS[COMP_CWORD-1]}"
# First try the basic completion
_scan_plex_libraries_completion
# If we didn't get any completions and we're looking for a section ID
if [[ ${#COMPREPLY[@]} -eq 0 ]]; then
case "${COMP_WORDS[1]}" in
@@ -136,14 +136,14 @@ _plex_scanner_with_sections() {
# Attempt to get section IDs from the scanner
local script_dir="$(dirname "${COMP_WORDS[0]}")"
local scanner_script=""
# Try to find the scanner script
if [[ -f "$script_dir/scan-plex-libraries.sh" ]]; then
scanner_script="$script_dir/scan-plex-libraries.sh"
elif [[ -f "/home/acedanger/shell/plex/scan-plex-libraries.sh" ]]; then
scanner_script="/home/acedanger/shell/plex/scan-plex-libraries.sh"
fi
if [[ -n "$scanner_script" ]]; then
# Attempt to get section IDs (with timeout to avoid hanging)
local section_ids
@@ -155,7 +155,7 @@ _plex_scanner_with_sections() {
;;
esac
fi
return 0
}
@@ -199,7 +199,7 @@ _plex_list_sections() {
_plex_extended_completion() {
local cur="${COMP_WORDS[COMP_CWORD]}"
local cmd="${COMP_WORDS[0]}"
# This function can be extended for future plex-related commands
case "$cmd" in
*plex-backup*)
@@ -209,7 +209,7 @@ _plex_extended_completion() {
# If restore scripts get their own completion, handle here
;;
esac
return 0
}

View File

@@ -11,15 +11,16 @@ This document provides comprehensive documentation for the modern `plex.sh` scri
The enhanced `plex.sh` script is a modern Plex service management tool that performs the following advanced tasks:
1. **Smart Service Management**: Intelligent start/stop/restart operations with dependency checking
2. **Enhanced Status Display**: Detailed service status with health indicators and port monitoring
3. **Safety Validation**: Pre-operation checks and post-operation verification
4. **Progress Indicators**: Visual feedback for all operations with timing information
5. **Comprehensive Logging**: Detailed logging with color-coded output and timestamps
6. **Configuration Validation**: Checks for common configuration issues
7. **Network Monitoring**: Port availability and network configuration validation
8. **Process Management**: Advanced process monitoring and cleanup capabilities
9. **Recovery Operations**: Automatic recovery from common service issues
10. **Performance Monitoring**: Service health and resource usage tracking
2. **Library Scanner Integration**: Integrated access to comprehensive library scanning operations
3. **Enhanced Status Display**: Detailed service status with health indicators and port monitoring
4. **Safety Validation**: Pre-operation checks and post-operation verification
5. **Progress Indicators**: Visual feedback for all operations with timing information
6. **Comprehensive Logging**: Detailed logging with color-coded output and timestamps
7. **Configuration Validation**: Checks for common configuration issues
8. **Network Monitoring**: Port availability and network configuration validation
9. **Process Management**: Advanced process monitoring and cleanup capabilities
10. **Recovery Operations**: Automatic recovery from common service issues
11. **Performance Monitoring**: Service health and resource usage tracking
## Related Scripts in the Plex Ecosystem
@@ -28,6 +29,7 @@ This script is part of a comprehensive Plex management suite:
### Core Management Scripts
- **`plex.sh`** (this script) - Service management and control
- **`scan-plex-libraries.sh`** ⭐ **NEW** - Comprehensive library scanning and metadata management
- **`backup-plex.sh`** - Database backup with integrity checking and auto-repair
- **`restore-plex.sh`** - Safe database restoration with validation
@@ -49,6 +51,266 @@ This script is part of a comprehensive Plex management suite:
- **`plex-recent-additions.sh`** - Recent media additions reporting and statistics
## Library Scanner Integration ⭐ **NEW**
### Overview
The `plex.sh` script now includes integrated access to comprehensive library scanning functionality through the new `scan-plex-libraries.sh` script. This integration provides seamless access to all Plex Media Scanner operations directly from the main management interface.
### Library Scanner Features
The integrated library scanner provides:
- **Library Management**: List all Plex library sections with IDs and names
- **Media Scanning**: Scan for new media files (individual libraries or all at once)
- **Metadata Refresh**: Refresh library metadata with force options for complete rebuilds
- **Deep Analysis**: Comprehensive media analysis for codec information and metadata
- **Thumbnail Generation**: Generate preview thumbnails and fanart images
- **Library Structure**: Display hierarchical library structure and organization
- **Interactive Mode**: User-friendly menu system for easy library management
- **Batch Operations**: Perform operations on all libraries or specific selections
- **Error Handling**: Comprehensive validation and error reporting
- **Service Integration**: Automatic Plex service status validation before operations
### Scanner Integration Commands
The library scanner is accessible through the main `plex.sh` script:
```bash
# Launch interactive scanner interface
./plex.sh scan
# Pass commands directly to scanner
./plex.sh scan list # List all libraries
./plex.sh scan scan # Scan all libraries for new media
./plex.sh scan scan 29 # Scan specific library (ID 29)
./plex.sh scan refresh 29 true # Force refresh specific library
./plex.sh scan analyze 29 true # Deep analyze specific library
./plex.sh scan generate 29 # Generate thumbnails for library
./plex.sh scan tree 29 # Show library structure
```
### Direct Scanner Access
The scanner can also be accessed directly:
```bash
# Direct script execution
./scan-plex-libraries.sh interactive # Interactive mode
./scan-plex-libraries.sh list # List libraries
./scan-plex-libraries.sh scan # Scan all libraries
./scan-plex-libraries.sh -v scan 29 # Verbose scan of specific library
# Via aliases (if shell configuration is loaded)
plex-scan # Launch via plex.sh integration
plex-scanner list # Direct scanner access
plex-scanner scan 29 # Direct scan of specific library
```
### Scanner Command Reference
#### Core Scanner Commands
- **`list`** - Display all available library sections with IDs and names
- **`scan [section_id]`** - Scan for new media files (all libraries if no ID specified)
- **`refresh [section_id] [force]`** - Refresh metadata (set force=true for complete refresh)
- **`analyze [section_id] [deep]`** - Analyze media files (set deep=true for comprehensive analysis)
- **`generate [section_id]`** - Generate thumbnails and fanart images
- **`tree <section_id>`** - Display hierarchical library structure (requires section ID)
- **`interactive`** - Launch interactive menu system
#### Scanner Options
- **`-v, --verbose`** - Enable verbose output for detailed operation information
- **`-h, --help`** - Display comprehensive help and usage information
#### Example Scanner Operations
```bash
# List all available libraries with their section IDs
$ ./plex.sh scan list
Available Library Sections:
=========================
29: Movies
30: TV Shows
31: Music
# Scan Movies library for new content
$ ./plex.sh scan scan 29
[>] Scanning library section 29 for new media...
[] Library section 29 scan completed
# Force refresh all libraries (complete metadata rebuild)
$ ./plex.sh scan refresh "" true
[~] Refreshing metadata for all libraries...
[i] Refreshing section 29...
[] Section 29 refreshed successfully
[i] Refreshing section 30...
[] Section 30 refreshed successfully
[] All libraries refreshed successfully
# Deep analyze TV Shows library
$ ./plex.sh scan analyze 30 true
[?] Analyzing media in library section 30...
[] Library section 30 analysis completed
# Generate thumbnails for Movies library
$ ./plex.sh scan generate 29
[*] Generating thumbnails for library section 29...
[] Thumbnails generated for library section 29
```
### Interactive Scanner Mode
The interactive mode provides a user-friendly menu system:
```bash
$ ./plex.sh scan
🎬 Plex Library Scanner - Interactive Mode
Select an operation to perform:
Available Operations:
1) List all libraries
2) Scan libraries for new media
3) Refresh library metadata
4) Analyze library media
5) Generate thumbnails
6) Show library tree
q) Quit
Choose an option [1-6,q]: 2
Scan Options:
1) Scan all libraries
2) Scan specific library
Choose [1-2]: 1
[>] Scanning all libraries for new media...
[] All libraries scanned successfully
```
### Scanner Error Handling and Validation
The library scanner includes comprehensive error handling:
- **Service Validation**: Automatically checks if Plex Media Server is running
- **Scanner Detection**: Locates Plex Media Scanner binary across different installation paths
- **Section ID Validation**: Verifies library section IDs exist before operations
- **Operation Verification**: Confirms successful completion of all scanner operations
- **Graceful Failure**: Provides helpful error messages and recovery suggestions
### Scanner Logging and Monitoring
All scanner operations are logged:
- **Operation Logs**: Detailed logs written to `/home/acedanger/shell/logs/plex-scanner.log`
- **Timestamp Tracking**: All operations include precise timestamps
- **Verbose Mode**: Enhanced debugging information available with `-v` flag
- **Status Reporting**: Real-time status updates during long-running operations
### Scanner Performance Considerations
For optimal performance:
- **Large Libraries**: Scanner operations may take considerable time for large media collections
- **Deep Analysis**: Deep analysis is resource-intensive, use selectively
- **Concurrent Operations**: Avoid running multiple scanner operations simultaneously
- **System Resources**: Scanner operations can be CPU and I/O intensive during execution
### Scanner Best Practices
Recommended usage patterns:
1. **Regular Scanning**: Set up regular scans for libraries with frequent media additions
2. **Selective Operations**: Use specific section IDs for targeted operations when possible
3. **Monitor Progress**: Use verbose mode to understand operation progress and impact
4. **Service Health**: Ensure Plex service is healthy before performing scanner operations
5. **Batch Operations**: For multiple libraries, consider using "scan all" for efficiency
### Scanner Troubleshooting
Common issues and solutions:
1. **"Plex Media Server is not running"**
- Start Plex: `./plex.sh start`
- Verify status: `./plex.sh status`
2. **"Plex Media Scanner binary not found"**
- Verify Plex installation is complete
- Check if binary exists in standard locations
- Ensure proper system PATH configuration
3. **"Section ID not found"**
- Use `./plex.sh scan list` to see valid section IDs
- Verify the library hasn't been deleted or renamed
4. **Scanner operations timeout or fail**
- Check system resources (CPU, memory, disk I/O)
- Verify media files are accessible and not corrupted
- Review scanner logs for detailed error information
### Scanner Bash Completion ⭐ **NEW**
The library scanner includes comprehensive bash completion support:
#### Tab Completion Features
- **Command Completion**: Tab completion for all scanner commands and options
- **Context-Aware**: Different completions based on command context
- **Boolean Flags**: Smart completion for `true`/`false` values where applicable
- **Alias Support**: Completion works with all plex-related aliases
#### Example Tab Completion Usage
```bash
# Main plex.sh command completion
$ ./plex.sh <TAB>
start stop restart status scan repair nuclear help
# Scanner sub-command completion
$ ./plex.sh scan <TAB>
list scan refresh analyze generate tree interactive -v --verbose -h --help
# Boolean flag completion for refresh and analyze
$ ./plex.sh scan refresh 29 <TAB>
true false
$ ./plex.sh scan analyze 29 <TAB>
true false
# Direct scanner completion
$ ./scan-plex-libraries.sh <TAB>
list scan refresh analyze generate tree interactive
# Alias completion
$ plex-scan <TAB>
list scan refresh analyze generate tree interactive
$ plex-scanner <TAB>
list scan refresh analyze generate tree interactive
```
#### Completion Installation
Bash completion is automatically installed by the setup scripts:
- **Automatic Setup**: Installed by `bootstrap.sh` and `setup.sh`
- **Shell Integration**: Sourced in `.zshrc` for immediate availability
- **Alias Support**: Works with all plex-related aliases (`plex`, `plex-scan`, `plex-scanner`, etc.)
#### Manual Completion Setup
If needed, completion can be enabled manually:
```bash
# Enable bash completion in zsh
autoload -U +X bashcompinit && bashcompinit
autoload -U compinit && compinit -u
# Source the completion script
source /home/acedanger/shell/completions/plex-scripts-completion.bash
```
## Enhanced Features
### Smart Terminal Detection and Color Output
@@ -139,6 +401,9 @@ Shows:
# Display comprehensive status
./plex.sh status
# Launch library scanner
./plex.sh scan
```
### Available Commands
@@ -148,12 +413,23 @@ The script supports the following commands:
```bash
# Basic service operations
./plex.sh start # Start Plex Media Server
./plex.sh stop # Stop Plex Media Server
./plex.sh stop # Stop Plex Media Server
./plex.sh restart # Restart Plex Media Server (also accepts 'reload')
./plex.sh status # Show detailed service status (also accepts 'info')
./plex.sh scan # Launch library scanner (NEW)
./plex.sh logs # Display recent Plex Media Server logs
./plex.sh help # Show help message (also accepts '--help' or '-h')
# Library scanner operations (NEW)
./plex.sh scan # Interactive scanner mode
./plex.sh scan list # List all library sections
./plex.sh scan scan # Scan all libraries for new media
./plex.sh scan scan 29 # Scan specific library (ID 29)
./plex.sh scan refresh 29 true # Force refresh specific library
./plex.sh scan analyze 29 true # Deep analyze specific library
./plex.sh scan generate 29 # Generate thumbnails for library
./plex.sh scan tree 29 # Show library structure
# Logs command with options
./plex.sh logs # Display last 20 lines of Plex logs
./plex.sh logs -n 50 # Display last 50 lines of Plex logs
@@ -185,8 +461,17 @@ The `plex.sh` script is designed to work seamlessly with other Plex management s
# Used by recovery scripts for service control
./recover-plex-database.sh # Uses plex.sh for service management
# Library scanner integration with service management
./plex.sh scan scan # Scan all libraries
./plex.sh scan refresh "" true # Force refresh all libraries after service restart
# Manual integration with porcelain output
./plex.sh --porcelain start # For use in scripts/automation
# Scanner integration in maintenance scripts
./plex.sh scan scan # Regular media scanning
./plex.sh scan analyze # Weekly deep analysis
./plex.sh scan generate # Thumbnail regeneration
```
### Security and Safety Features
@@ -434,6 +719,11 @@ For scheduled operations:
# Daily health check
0 6 * * * /home/acedanger/shell/plex/plex.sh status --validate
# Automated library scanning (NEW)
0 4 * * * /home/acedanger/shell/plex/plex.sh scan scan # Daily scan for new media
0 2 * * 0 /home/acedanger/shell/plex/plex.sh scan refresh "" true # Weekly metadata refresh
0 1 * * 1 /home/acedanger/shell/plex/plex.sh scan analyze # Weekly media analysis
```
## Exit Codes and Return Values