Files
profilarr/backend/app/importarr/profile.py
santiagosayshey d8f944af11 improvements: whole lotta stuff (#18)
* feat: initialise task scheduler

* feat: add "next run" field to task status

* fix: adjust status route path

* feat: task dashboard + api functions

* fix: return sucess object for alert

* refactor: turn task cards into seperate objects

* fix: change task names

* feat: implement compile and import module
- only working for custom formats for now

* refactor/feature: refactor compilation module
- seperate file for mappings
- seperate format compiler into new file
- add compiler for profiles

* feat: add import logic for quality profiles

* fix: properly resolve cutoff IDs for singular qualities

* fix: remux mappings for sonarr

* fix: retain quality group order
- stop groups first, then singular

* fix: dynamically find next group ID to stop duplicate IDs from occuring

* fix: normalise quality letter case

* feat: add api functions for import functionality

* fix: adjust validation for import.js

* feat: add mass selection tool componnet
- keyboard shortcuts to enter state
- mass delete / import

* feat: add loading indicator on import

* style: improve selected card styling

* fix: append extra custom formats with 0 score

* perf: add git status caching to improve load times

* fix: adjust mass import handling and selection logic
- use content.name rather than content.id

* fix: enhance quality name mapping with alternate names and case-insensitive lookups

* feat: add description truncation to ProfileCard for improved readability
- also remove qualitites

* fix: update upgrade quality selection logic to handle disabling scenarios

* feat: expand language mappings with additional languages and identifiers

* feat: enhance profile conversion logging with language handling

* fix: clarify language setting impact in ProfileLanguagesTab component

* feat: add Sonarr language mappings and update language selection logic

* feat: implement language normalization and enhance logging in format conversion

* feat: enhance logging in format conversion and add language specification handling

* feat: add Afrikaans and Albanian languages to the language constants

* refactor: remove language strictness feature and update language handling in ProfileModal

* feat: add logging setup for improved debugging in mappings module

* feat: enhance language compilation to work with new system

* feat: update language handling in ProfileLanguagesTab to support 'any' behavior

* fix: remove redundant import statement in profile.py

* feat: implement in-memory format import functionality and update profile compiler to utilize it for non english language compilation

* feat: add comparison for tweaks in quality profile changes

* feat: add functions to convert display names to filenames and vice versa

* fix: remove unnecessary filename modification in formats data

* feat: add process_tweaks function to handle profile tweaks and import formats before compilation

* feat: refactor process_tweaks to modularize format import and scoring
- include lossless audio tweak handling

* feat: add support for Dolby Vision no fallback and bleeding edge codecs in process_tweaks

* feat: add support for disabling prereleases based on profile tweaks

* fix: reduce cache TTL from 30 seconds to 1 second for quicker updates

* feat: add resetState function to initialize profile modal state

* feat: enhance save_yaml_file function to optionally use data name for filename

* feat: enhance handle_rename function to account for staged renames

* feat: enhance revert functionality to handle untracked files and staged deletions

* chore: update timezone setting in docker-compose.yml

* feat: increase maximum description length in ProfileCard component

* refactor: generic YAML comparison and change summary functionality

* refactor: incoming changes now uses generic comparison logic

* refactor: add YAML conflict comparison functionality with detailed summary generation for merge conflicts

* refactor: heavily simplified resolve conflict modal to work with new generic conflict parsing

* refactor: implement GitStatusManager for improved repository status handling and sync task updates

* refactor: integrate GitStatusManager to update remote status after pull operations

* refactor: remove isDevMode prop from ChangeRow, ConflictRow, ConflictTable, ChangeTable, RepoContainer, and ActionButtons components

* refactor: migrate settings handling from settings_utils to db module and enhance settings management

* refactor: remove deprecated authentication methods and streamline push operations with SSH access

* refactor: enhance error handling and authentication for Git operations, including PAT support

* refactor: remove old settings_utils

* refactor: add settings prop to StatusContainer and update database initialization for profilarr_pat

* refactor: simplify format name handling in ViewChanges component by removing old API call

* fix: update fetchSettings to handle cases with no git repository and ensure settings is null

* fix: enhance get_git_status to return a valid status object when no git repository is found

* style: various improvements to repo container
- add database stats
- add organisation / profile avatar
- parse organisation / repo name
- improvements to branch button

* feat: implement authentication setup and middleware for secure session management

* fix: auto login after setting up authentication

* feat: enhance authentication setup with GET method and track failed attempts

* feat: add authentication setup and login components with API integration

* feat: redesign SetupPage component with improved layout and user guidance

* feat: enhance LoginPage layout with improved design and user guidance

* refactor: remove unused API functions for regex and format management

* improvements: whole lot more stuff (#17)

* feat: implement configuration management for directory paths and session settings

* feat: implement backup management with API endpoints for backup operations

* feat: add backup import functionality with zip file validation and restoration

* feat: implement backup API with endpoints for listing, creating, downloading, restoring, deleting, and importing backups

* feat: enhance backup listing with file size and last modified time

* feat: add backup management interface with listing, creation, restoration, and deletion functionalities

* fix: refresh backups list after successful deletion

* feat: create BackupCard component for displaying backup details and actions

* fix: status parsing improvements
- now properly shows outgoing changes with / without developer mode

* fix: remove authentication bypass for backup routes during testing

* feat: add logging configuration and ensure log directory creation

* feat: implement application-wide logging configuration and ensure log directory creation

* feat: add logging blueprint with endpoints for retrieving and searching log files

* feat: add git logging configuration to enhance logging capabilities

* refactor: enhance logging details and improve error handling in repository cloning and file processing

* refactor: update tab labels for clarity in settings page

* refactor: remove unused tasks and streamline task scheduler

* refactor: improve repository settings handling and UI updates in RepoContainer

* style: add slight gradient to modal

* feat: enhance footer with GitHub repository info and organization avatar

* refactor: update imports and enhance modal layout for linking Git repository

* refactor: remove documentation and issue links from footer component

* refactor: git settings refactor.
- new git container to contain repo / status
- split repo container into active / empty components
- split status into seperate sections for incoming, outgoing, conflict

* chore: simplify environment configuration by using .env file in docker-compose

* fix: update remote status after commit and push operations

* refactor: restructure application initialization and configure Git user settings on startup

* refactor: improve default Git user configuration handling in initialization

* style: enhance UI styling and structure for Git status display

* style: enhance UI layout and styling for ChangeRow and ChangeTable components

* style: enhance UI layout and styling for CommitMessage component

* style: improve selected row styling

* style: enhance UI styling for ConflictRow and ConflictTable components

* style: update merge process to include remote status update after finalization

* style: update noChangesMessages for improved clarity and engagement

* feat: add animated Logo component and integrate it into Navbar

* feat: enhance selection handling
- add shift selection
- add will be selected state and styling

* feat: enhance mouse tracking for shift selection

* refactor: remove deprecated ActionButtons

* style: unify button colors and update tooltips in IncomingChanges and OutgoingChanges components

* feat: add auto-pull feature with toggle in settings and backend support

* fix: update auto-pull implementation to use integer values

* feat: implement auto-pull functionality in remote status update

* file: improve value formatting for new files

* fix: change logger level to DEBUG and add debug message for profile import attempts

* refactor: remove logging statements and streamline exception handling in format compiler

* feat: enhance format import process with detailed logging and error handling

* feat: enhance profile import process with detailed logging and error handling

* refactor: remove non error logging statements for profile compilation

* feat: enhance logging for memory-based format import with detailed success and error messages

* feat: add logging for language settings and compiled profile data in profile import

* feat: add dedicated logging for importarr with separate log file and configuration

* feat: add logging API with functions to fetch logs, search, and filter by level

* feat: add logs tab to settings page with LogContainer component

* feat: add LogContainer and LogViewer components for enhanced log management

* fix: dynamic vertical height for log viewer

* fix: reduce log file size and increase backup count for improved log management

* fix: enhance error logging with exception type and full traceback for better debugging

* fix: use mapped cutoff name for profile conversion to ensure correct quality mapping

* fix: add validation for git repository existence before syncing

* fix: implement delete constraints check before item deletion to prevent breaking references

* fix: enhance delete constraints check with improved logging and name normalization

* fix: add protection against deletion of required custom formats in delete constraints check

* feat: implement ANSI color parsing in LogViewer for improved log readability

* feat: enhance ViewChanges component with improved key parsing and rendering of changes

* refactor: improve styling and structure of ResolveConflicts component for better readability and usability

* fix: improve error handling and response for arr config saving

* feat: extend arr configuration with additional fields and sync methods

* feat: add DataSelectorModal component for selecting data to sync

* feat: enhance ArrModal and DataSelectorModal with improved layout and data display

* feat: update ArrContainer to use new API import and include additional arrConfig fields

* feat: enhance ArrCard component with sync details and improved layout

* feat: add AddButton component with custom positioning and animations

* feat: replace Add New Card section with AddButton component for improved UX

* feat: reposition AddButton in ArrContainer for better visibility

* feat: replace AddNewCard with AddButton in RegexPage for improved UX

* feat: replace AddNewCard with AddButton in FormatPage for improved UX

* feat: replace AddNewCard with AddButton in ProfilePage for improved UX
2025-02-05 16:09:59 +10:30

339 lines
13 KiB
Python

# app/importarr/profile.py
import requests
import logging
import json
import yaml
from pathlib import Path
from typing import Dict, List, Optional, Any
from ..data.utils import load_yaml_file, get_category_directory
from ..compile.profile_compiler import compile_quality_profile
from ..compile.mappings import TargetApp
from .format import import_formats_to_arr
logger = logging.getLogger('importarr')
def import_profiles_to_arr(profile_names: List[str], base_url: str,
api_key: str, arr_type: str) -> Dict:
logger.info(
f"Received {len(profile_names)} profiles to import for {arr_type}")
results = {
'success': True,
'added': 0,
'updated': 0,
'failed': 0,
'details': []
}
try:
logger.info("Looking for existing profiles...")
existing_profiles = get_existing_profiles(base_url, api_key)
if existing_profiles is None:
return {
'success': False,
'error': 'Failed to get existing profiles'
}
existing_profile_map = {
profile['name']: profile['id']
for profile in existing_profiles
}
logger.debug(f"Found {len(existing_profile_map)} existing profiles")
target_app = TargetApp.RADARR if arr_type.lower(
) == 'radarr' else TargetApp.SONARR
for profile_name in profile_names:
try:
profile_file = f"{get_category_directory('profile')}/{profile_name}.yml"
profile_data = load_yaml_file(profile_file)
logger.info("Received profile:\n" +
yaml.dump(profile_data, sort_keys=False))
# Log the language setting (if any)
profile_language = profile_data.get('language', 'any')
if profile_language != 'any':
logger.info(
f"Profile '{profile_name}' has language override: {profile_language}"
)
logger.info(
f"Processing tweaks and importing formats for profile '{profile_name}'"
)
profile_data = process_tweaks(profile_data, base_url, api_key,
arr_type)
logger.info("Compiling quality profile...")
compiled_profiles = compile_quality_profile(
profile_data=profile_data,
target_app=target_app,
base_url=base_url,
api_key=api_key,
format_importer=import_formats_to_arr)
if not compiled_profiles:
raise ValueError("Profile compilation returned no data")
# We'll assume the compile function returns a list, and we take the first
profile_data = compiled_profiles[0]
logger.info(
"Looking for existing custom formats to sync format IDs..."
)
existing_formats = get_existing_formats(base_url, api_key)
if existing_formats is None:
raise ValueError("Failed to get updated format list")
format_id_map = {
fmt['name']: fmt['id']
for fmt in existing_formats
}
logger.debug(
f"Found {len(format_id_map)} existing custom formats")
logger.info(
f"Synchronizing format IDs in profile '{profile_name}'")
profile_data = sync_format_ids(profile_data, format_id_map)
logger.debug("Format items after sync:")
for item in profile_data.get('formatItems', []):
logger.debug(
f" {item['name']} => Score: {item.get('score', 0)}, "
f"Format ID: {item.get('format', 'missing')}")
logger.info("Compiled to:\n" +
json.dumps(profile_data, indent=2))
result = process_profile(profile_data=profile_data,
existing_names=existing_profile_map,
base_url=base_url,
api_key=api_key)
results[result['action']] += 1
results['details'].append(result['detail'])
if not result['success']:
results['success'] = False
except Exception as e:
logger.error(
f"Error processing profile {profile_name}: {str(e)}, type: {type(e).__name__}"
)
logger.exception("Full traceback:")
results['failed'] += 1
results['details'].append({
'name': profile_name,
'action': 'failed',
'success': False,
'error': str(e)
})
results['success'] = False
logger.info(
f"Importing {len(profile_names)} profiles complete. "
f"Added: {results['added']}, Updated: {results['updated']}, "
f"Failed: {results['failed']}")
return results
except Exception as e:
logger.error(f"Error in import_profiles_to_arr: {str(e)}")
return {'success': False, 'error': str(e)}
def get_existing_profiles(base_url: str, api_key: str) -> Optional[List[Dict]]:
try:
response = requests.get(
f"{base_url.rstrip('/')}/api/v3/qualityprofile",
headers={'X-Api-Key': api_key})
if response.status_code == 200:
return response.json()
return None
except Exception as e:
logger.error(f"Error getting existing profiles: {str(e)}")
return None
def get_existing_formats(base_url: str, api_key: str) -> Optional[List[Dict]]:
try:
response = requests.get(f"{base_url.rstrip('/')}/api/v3/customformat",
headers={'X-Api-Key': api_key})
if response.status_code == 200:
return response.json()
return None
except Exception as e:
logger.error(f"Error getting existing formats: {str(e)}")
return None
def sync_format_ids(profile_data: Dict, format_id_map: Dict[str, int]) -> Dict:
if 'formatItems' not in profile_data:
profile_data['formatItems'] = []
existing_format_names = {
item['name']
for item in profile_data['formatItems']
}
synced_items = []
for item in profile_data['formatItems']:
if item['name'] in format_id_map:
synced_items.append({
'format': format_id_map[item['name']],
'name': item['name'],
'score': item['score']
})
else:
logger.warning(f"Custom format not found in arr: {item['name']}")
for format_name, format_id in format_id_map.items():
if format_name not in existing_format_names:
synced_items.append({
'format': format_id,
'name': format_name,
'score': 0
})
profile_data['formatItems'] = synced_items
return profile_data
def process_tweaks(profile_data: Dict, base_url: str, api_key: str,
arr_type: str) -> Dict:
logger.debug(f"Processing tweaks for profile: {profile_data.get('name')}")
tweaks = profile_data.get('tweaks', {})
if tweaks.get('preferFreeleech', False):
freeleech_formats = ["Free25", "Free50", "Free75", "Free100"]
freeleech_scores = [{
"name": n,
"score": s
} for n, s in zip(freeleech_formats, range(1, 5))]
_import_and_score_formats(formats=freeleech_formats,
scores=freeleech_scores,
profile_data=profile_data,
base_url=base_url,
api_key=api_key,
arr_type=arr_type,
feature_name="freeleech")
lossless_formats = [
"FLAC", "DTS-X", "DTS-HD MA", "TrueHD", "TrueHD (Missing)"
]
default_score = 0 if tweaks.get('allowLosslessAudio', False) else -9999
lossless_scores = [{
"name": f,
"score": default_score
} for f in lossless_formats]
_import_and_score_formats(formats=lossless_formats,
scores=lossless_scores,
profile_data=profile_data,
base_url=base_url,
api_key=api_key,
arr_type=arr_type,
feature_name="lossless audio")
dv_formats = ["Dolby Vision (Without Fallback)"]
dv_score = 0 if tweaks.get('allowDVNoFallback', False) else -9999
dv_scores = [{"name": n, "score": dv_score} for n in dv_formats]
_import_and_score_formats(formats=dv_formats,
scores=dv_scores,
profile_data=profile_data,
base_url=base_url,
api_key=api_key,
arr_type=arr_type,
feature_name="Dolby Vision no fallback")
codec_formats = ["AV1", "VVC"]
codec_score = 0 if tweaks.get('allowBleedingEdgeCodecs', False) else -9999
codec_scores = [{"name": f, "score": codec_score} for f in codec_formats]
_import_and_score_formats(formats=codec_formats,
scores=codec_scores,
profile_data=profile_data,
base_url=base_url,
api_key=api_key,
arr_type=arr_type,
feature_name="bleeding edge codecs")
return profile_data
def _import_and_score_formats(formats: List[str], scores: List[Dict[str, Any]],
profile_data: Dict, base_url: str, api_key: str,
arr_type: str, feature_name: str) -> None:
logger.info(
f"Processing {feature_name} formats for profile '{profile_data.get('name')}'"
)
try:
result = import_formats_to_arr(formats, base_url, api_key, arr_type)
if not result.get('success', False):
logger.warning(
f"Failed to import {feature_name} formats for '{profile_data.get('name')}'"
)
except Exception as e:
logger.error(f"Error importing {feature_name} formats: {str(e)}")
return
if 'custom_formats' not in profile_data:
profile_data['custom_formats'] = []
profile_data['custom_formats'].extend(scores)
def process_profile(profile_data: Dict, existing_names: Dict[str, int],
base_url: str, api_key: str) -> Dict:
profile_name = profile_data['name']
if profile_name in existing_names:
profile_data['id'] = existing_names[profile_name]
logger.info(f"Found existing profile '{profile_name}'. Updating...")
success = update_profile(base_url, api_key, profile_data)
return {
'success': success,
'action': 'updated' if success else 'failed',
'detail': {
'name': profile_name,
'action': 'updated',
'success': success
}
}
else:
logger.info(f"Profile '{profile_name}' not found. Adding...")
success = add_profile(base_url, api_key, profile_data)
return {
'success': success,
'action': 'added' if success else 'failed',
'detail': {
'name': profile_name,
'action': 'added',
'success': success
}
}
def update_profile(base_url: str, api_key: str, profile_data: Dict) -> bool:
try:
url = f"{base_url.rstrip('/')}/api/v3/qualityprofile/{profile_data['id']}"
logger.info(f"Updating profile at URL: {url}")
response = requests.put(url,
headers={'X-Api-Key': api_key},
json=profile_data)
logger.info(f"Update response status: {response.status_code}")
return response.status_code in [200, 201, 202, 204]
except Exception as e:
logger.error(f"Error updating profile: {str(e)}")
return False
def add_profile(base_url: str, api_key: str, profile_data: Dict) -> bool:
try:
url = f"{base_url.rstrip('/')}/api/v3/qualityprofile"
logger.info(f"Adding profile at URL: {url}")
response = requests.post(url,
headers={'X-Api-Key': api_key},
json=profile_data)
logger.info(f"Add response status: {response.status_code}")
return response.status_code in [200, 201, 202, 204]
except Exception as e:
logger.error(f"Error adding profile: {str(e)}")
return False