This commit is contained in:
David Maisonave
2024-07-26 12:32:50 -04:00
parent f9cdbb7436
commit 0ae1636d58
4 changed files with 620 additions and 101 deletions

View File

@@ -1,50 +1,62 @@
# This is a Stash plugin which allows users to rename the video (scene) file name by editing the [Title] field located in the scene [Edit] tab.
# By David Maisonave (aka Axter) Jul-2024
# Description: This is a Stash plugin which allows users to rename the video (scene) file name by editing the [Title] field located in the scene [Edit] tab.
# By David Maisonave (aka Axter) Jul-2024 (https://www.axter.com/)
# Get the latest developers version from following link: https://github.com/David-Maisonave/Axter-Stash/tree/main/plugins/RenameFile
# Based on source code from https://github.com/Serechops/Serechops-Stash/tree/main/plugins/Renamer
import requests
import os
import logging
import stashapi.log as log # Importing stashapi.log as log for critical events ONLY
import sys
import shutil
from pathlib import Path
import hashlib
import json
import sys
from stashapi.stashapp import StashInterface
from pathlib import Path
import requests
import logging
from logging.handlers import RotatingFileHandler
# Import settings from renamefile_settings.py
from renamefile_settings import config
import stashapi.log as log # Importing stashapi.log as log for critical events ONLY
from stashapi.stashapp import StashInterface
from renamefile_settings import config # Import settings from renamefile_settings.py
# Get the directory of the script
script_dir = Path(__file__).resolve().parent
# Configure logging for this script with max log file size
log_file_path = script_dir / 'renamefile.log'
rfh = RotatingFileHandler(
filename=log_file_path,
mode='a',
maxBytes=2*1024*1024,
backupCount=2,
encoding=None,
delay=0
)
# **********************************************************************
# Constant global variables --------------------------------------------
SCRIPT_DIR = Path(__file__).resolve().parent # Get the directory of the script
LOG_FILE_PATH = SCRIPT_DIR / 'renamefile.log'
FORMAT = "[%(asctime)s - LN:%(lineno)s] %(message)s"
logging.basicConfig(level=logging.INFO, format=FORMAT, datefmt="%y%m%d %H:%M:%S", handlers=[rfh])
logger = logging.getLogger('renamefile')
DEFAULT_ENDPOINT = "http://localhost:9999/graphql" # Default GraphQL endpoint
DEFAULT_FIELD_KEY_LIST = "title,performers,studio,tags" # Default Field Key List with the desired order
DEFAULT_SEPERATOR = "-"
PLUGIN_ARGS = False
errOccurred = False
PLUGIN_ARGS_MODE = False
WRAPPER_STYLES = config["wrapper_styles"]
POSTFIX_STYLES = config["postfix_styles"]
# GraphQL query to fetch all scenes
QUERY_ALL_SCENES = """
query AllScenes {
allScenes {
id
updated_at
}
}
"""
RFH = RotatingFileHandler(
filename=LOG_FILE_PATH,
mode='a',
maxBytes=2*1024*1024, # Configure logging for this script with max log file size of 2000K
backupCount=2,
encoding=None,
delay=0
)
# **********************************************************************
# Global variables --------------------------------------------
inputToUpdateScenePost = False
exitMsg = "Change success!!"
# Configure local log file for plugin within plugin folder having a limited max log file size
logging.basicConfig(level=logging.INFO, format=FORMAT, datefmt="%y%m%d %H:%M:%S", handlers=[RFH])
logger = logging.getLogger('renamefile')
# ------------------------------------------
# ------------------------------------------
# Code to fetch variables from Plugin UI
# **********************************************************************
# ----------------------------------------------------------------------
# Code section to fetch variables from Plugin UI and from renamefile_settings.py
json_input = json.loads(sys.stdin.read())
FRAGMENT_SERVER = json_input["server_connection"]
stash = StashInterface(FRAGMENT_SERVER)
@@ -66,21 +78,22 @@ settings = {
}
if "renamefile" in pluginConfiguration:
settings.update(pluginConfiguration["renamefile"])
# ------------------------------------------
# ----------------------------------------------------------------------
debugTracing = settings["zzdebugTracing"]
# Extract dry_run setting from settings
dry_run = settings["zzdryRun"]
dry_run_prefix = ''
try:
PLUGIN_ARGS = json_input['args']["mode"]
PLUGIN_ARGS = json_input['args']
PLUGIN_ARGS_MODE = json_input['args']["mode"]
except:
pass
try:
if json_input['args']['hookContext']['input']: inputToUpdateScenePost = True # This avoid calling rename logic twice
if json_input['args']['hookContext']['input']: inputToUpdateScenePost = True # This avoids calling rename logic twice
except:
pass
logger.info(f"\nStarting (debugTracing={debugTracing}) (dry_run={dry_run}) (PLUGIN_ARGS={PLUGIN_ARGS}) (inputToUpdateScenePost={inputToUpdateScenePost})************************************************")
logger.info(f"\nStarting (debugTracing={debugTracing}) (dry_run={dry_run}) (PLUGIN_ARGS_MODE={PLUGIN_ARGS_MODE}) (inputToUpdateScenePost={inputToUpdateScenePost})************************************************")
if debugTracing: logger.info("settings: %s " % (settings,))
if dry_run:
logger.info("Dry run mode is enabled.")
@@ -97,10 +110,11 @@ tag_whitelist = settings["ztagWhitelist"]
if debugTracing: logger.info("Debug Tracing................")
if not tag_whitelist:
tag_whitelist = ""
if debugTracing: logger.info(f"Debug Tracing (tag_whitelist={tag_whitelist})................")
endpoint = settings["zgraphqlEndpoint"] # GraphQL endpoint
if debugTracing: logger.info("Debug Tracing................")
if not endpoint or endpoint == "":
endpoint = DEFAULT_ENDPOINT
if debugTracing: logger.info(f"Debug Tracing (endpoint={endpoint})................")
# Extract rename_files and move_files settings from renamefile_settings.py
rename_files = config["rename_files"]
move_files = settings["zafileRenameViaMove"]
@@ -113,29 +127,11 @@ fieldKeyList = fieldKeyList.replace(";", ",")
fieldKeyList = fieldKeyList.split(",")
if debugTracing: logger.info(f"Debug Tracing (fieldKeyList={fieldKeyList})................")
separator = settings["zseparators"]
# ------------------------------------------
# ------------------------------------------
# ----------------------------------------------------------------------
# **********************************************************************
double_separator = separator + separator
# Extract styles from config
wrapper_styles = config["wrapper_styles"]
postfix_styles = config["postfix_styles"]
try:
if debugTracing: logger.info(f"Debug Tracing (json_input['args']={json_input['args']})................")
except:
pass
# GraphQL query to fetch all scenes
query_all_scenes = """
query AllScenes {
allScenes {
id
updated_at
}
}
"""
if debugTracing: logger.info("Debug Tracing................")
if debugTracing: logger.info(f"Debug Tracing (PLUGIN_ARGS={PLUGIN_ARGS}) (WRAPPER_STYLES={WRAPPER_STYLES}) (POSTFIX_STYLES={POSTFIX_STYLES})................")
# Function to make GraphQL requests
def graphql_request(query, variables=None):
@@ -193,8 +189,8 @@ def form_filename(original_file_stem, scene_details):
# Check if the tag name is in the whitelist
if tag_whitelist == "" or tag_whitelist == None or (tag_whitelist and tag_name in tag_whitelist):
if wrapper_styles.get('tag'):
filename_parts.append(f"{wrapper_styles['tag'][0]}{tag_name}{wrapper_styles['tag'][1]}")
if WRAPPER_STYLES.get('tag'):
filename_parts.append(f"{WRAPPER_STYLES['tag'][0]}{tag_name}{WRAPPER_STYLES['tag'][1]}")
if debugTracing: logger.info("Debug Tracing................")
else:
filename_parts.append(tag_name)
@@ -215,81 +211,81 @@ def form_filename(original_file_stem, scene_details):
studio_name = scene_details.get('studio', {}).get('name', '')
if debugTracing: logger.info(f"Debug Tracing (studio_name={studio_name})................")
if studio_name:
studio_name += postfix_styles.get('studio')
studio_name += POSTFIX_STYLES.get('studio')
if debugTracing: logger.info("Debug Tracing................")
if include_keyField_if_in_name or studio_name.lower() not in title.lower():
if wrapper_styles.get('studio'):
filename_parts.append(f"{wrapper_styles['studio'][0]}{studio_name}{wrapper_styles['studio'][1]}")
if WRAPPER_STYLES.get('studio'):
filename_parts.append(f"{WRAPPER_STYLES['studio'][0]}{studio_name}{WRAPPER_STYLES['studio'][1]}")
else:
filename_parts.append(studio_name)
elif key == 'title':
if title: # This value has already been fetch in start of function because it needs to be defined before tags and performers
title += postfix_styles.get('title')
if wrapper_styles.get('title'):
filename_parts.append(f"{wrapper_styles['title'][0]}{title}{wrapper_styles['title'][1]}")
title += POSTFIX_STYLES.get('title')
if WRAPPER_STYLES.get('title'):
filename_parts.append(f"{WRAPPER_STYLES['title'][0]}{title}{WRAPPER_STYLES['title'][1]}")
else:
filename_parts.append(title)
elif key == 'performers':
if settings["performerAppend"]:
performers = '-'.join([performer.get('name', '') for performer in scene_details.get('performers', [])])
if performers:
performers += postfix_styles.get('performers')
performers += POSTFIX_STYLES.get('performers')
if debugTracing: logger.info(f"Debug Tracing (include_keyField_if_in_name={include_keyField_if_in_name})................")
if include_keyField_if_in_name or performers.lower() not in title.lower():
if debugTracing: logger.info(f"Debug Tracing (performers={performers})................")
if wrapper_styles.get('performers'):
filename_parts.append(f"{wrapper_styles['performers'][0]}{performers}{wrapper_styles['performers'][1]}")
if WRAPPER_STYLES.get('performers'):
filename_parts.append(f"{WRAPPER_STYLES['performers'][0]}{performers}{WRAPPER_STYLES['performers'][1]}")
else:
filename_parts.append(performers)
elif key == 'date':
scene_date = scene_details.get('date', '')
if debugTracing: logger.info("Debug Tracing................")
if scene_date:
scene_date += postfix_styles.get('date')
scene_date += POSTFIX_STYLES.get('date')
if debugTracing: logger.info("Debug Tracing................")
if wrapper_styles.get('date'):
filename_parts.append(f"{wrapper_styles['date'][0]}{scene_date}{wrapper_styles['date'][1]}")
if WRAPPER_STYLES.get('date'):
filename_parts.append(f"{WRAPPER_STYLES['date'][0]}{scene_date}{WRAPPER_STYLES['date'][1]}")
else:
filename_parts.append(scene_date)
elif key == 'resolution':
width = str(scene_details.get('files', [{}])[0].get('width', '')) # Convert width to string
height = str(scene_details.get('files', [{}])[0].get('height', '')) # Convert height to string
if width and height:
resolution = width + postfix_styles.get('width_height_seperator') + height + postfix_styles.get('resolution')
if wrapper_styles.get('resolution'):
filename_parts.append(f"{wrapper_styles['resolution'][0]}{resolution}{wrapper_styles['width'][1]}")
resolution = width + POSTFIX_STYLES.get('width_height_seperator') + height + POSTFIX_STYLES.get('resolution')
if WRAPPER_STYLES.get('resolution'):
filename_parts.append(f"{WRAPPER_STYLES['resolution'][0]}{resolution}{WRAPPER_STYLES['width'][1]}")
else:
filename_parts.append(resolution)
elif key == 'width':
width = str(scene_details.get('files', [{}])[0].get('width', '')) # Convert width to string
if width:
width += postfix_styles.get('width')
if wrapper_styles.get('width'):
filename_parts.append(f"{wrapper_styles['width'][0]}{width}{wrapper_styles['width'][1]}")
width += POSTFIX_STYLES.get('width')
if WRAPPER_STYLES.get('width'):
filename_parts.append(f"{WRAPPER_STYLES['width'][0]}{width}{WRAPPER_STYLES['width'][1]}")
else:
filename_parts.append(width)
elif key == 'height':
height = str(scene_details.get('files', [{}])[0].get('height', '')) # Convert height to string
if height:
height += postfix_styles.get('height')
if wrapper_styles.get('height'):
filename_parts.append(f"{wrapper_styles['height'][0]}{height}{wrapper_styles['height'][1]}")
height += POSTFIX_STYLES.get('height')
if WRAPPER_STYLES.get('height'):
filename_parts.append(f"{WRAPPER_STYLES['height'][0]}{height}{WRAPPER_STYLES['height'][1]}")
else:
filename_parts.append(height)
elif key == 'video_codec':
video_codec = scene_details.get('files', [{}])[0].get('video_codec', '').upper() # Convert to uppercase
if video_codec:
video_codec += postfix_styles.get('video_codec')
if wrapper_styles.get('video_codec'):
filename_parts.append(f"{wrapper_styles['video_codec'][0]}{video_codec}{wrapper_styles['video_codec'][1]}")
video_codec += POSTFIX_STYLES.get('video_codec')
if WRAPPER_STYLES.get('video_codec'):
filename_parts.append(f"{WRAPPER_STYLES['video_codec'][0]}{video_codec}{WRAPPER_STYLES['video_codec'][1]}")
else:
filename_parts.append(video_codec)
elif key == 'frame_rate':
frame_rate = str(scene_details.get('files', [{}])[0].get('frame_rate', '')) + 'FPS' # Convert to string and append ' FPS'
if frame_rate:
frame_rate += postfix_styles.get('frame_rate')
if wrapper_styles.get('frame_rate'):
filename_parts.append(f"{wrapper_styles['frame_rate'][0]}{frame_rate}{wrapper_styles['frame_rate'][1]}")
frame_rate += POSTFIX_STYLES.get('frame_rate')
if WRAPPER_STYLES.get('frame_rate'):
filename_parts.append(f"{WRAPPER_STYLES['frame_rate'][0]}{frame_rate}{WRAPPER_STYLES['frame_rate'][1]}")
else:
filename_parts.append(frame_rate)
elif key == 'galleries':
@@ -298,9 +294,9 @@ def form_filename(original_file_stem, scene_details):
for gallery_name in galleries:
if debugTracing: logger.info(f"Debug Tracing (include_keyField_if_in_name={include_keyField_if_in_name}) (gallery_name={gallery_name})................")
if include_keyField_if_in_name or gallery_name.lower() not in title.lower():
gallery_name += postfix_styles.get('galleries')
if wrapper_styles.get('galleries'):
filename_parts.append(f"{wrapper_styles['galleries'][0]}{gallery_name}{wrapper_styles['galleries'][1]}")
gallery_name += POSTFIX_STYLES.get('galleries')
if WRAPPER_STYLES.get('galleries'):
filename_parts.append(f"{WRAPPER_STYLES['galleries'][0]}{gallery_name}{WRAPPER_STYLES['galleries'][1]}")
if debugTracing: logger.info("Debug Tracing................")
else:
filename_parts.append(gallery_name)
@@ -314,7 +310,7 @@ def form_filename(original_file_stem, scene_details):
for tag_name in tags:
if debugTracing: logger.info(f"Debug Tracing (include_keyField_if_in_name={include_keyField_if_in_name}) (tag_name={tag_name})................")
if include_keyField_if_in_name or tag_name.lower() not in title.lower():
add_tag(tag_name + postfix_styles.get('tag'))
add_tag(tag_name + POSTFIX_STYLES.get('tag'))
if debugTracing: logger.info(f"Debug Tracing (tag_name={tag_name})................")
if debugTracing: logger.info("Debug Tracing................")
@@ -408,7 +404,6 @@ def move_or_rename_files(scene_details, new_filename, original_parent_directory)
logger.error(f"Failed to move or rename file: {path}. Error: {e}")
exitMsg = "Failed to move or rename file"
continue
return new_path # Return the new_path variable after the loop
def perform_metadata_scan(metadata_scan_path):
@@ -499,10 +494,9 @@ def rename_scene(scene_id, stash_directory):
# Main default function for rename scene
def rename_files_task():
global exitMsg
if debugTracing: logger.info("Debug Tracing................")
# Execute the GraphQL query to fetch all scenes
scene_result = graphql_request(query_all_scenes)
scene_result = graphql_request(QUERY_ALL_SCENES)
if debugTracing: logger.info("Debug Tracing................")
all_scenes = scene_result.get('data', {}).get('allScenes', [])
if debugTracing: logger.info("Debug Tracing................")
@@ -523,8 +517,6 @@ def rename_files_task():
stash_directory = config.get('stash_directory', '')
if debugTracing: logger.info("Debug Tracing................")
if debugTracing: logger.info("Debug Tracing................")
# Rename the latest scene and trigger metadata scan
new_filename = rename_scene(latest_scene_id, stash_directory)
if debugTracing: logger.info(f"Debug Tracing (exitMsg={exitMsg})................")
@@ -542,16 +534,15 @@ def rename_files_task():
def fetch_dup_filename_tags(): # Place holder for new implementation
return
if PLUGIN_ARGS == "fetch_dup_filename_tags":
if PLUGIN_ARGS_MODE == "fetch_dup_filename_tags":
fetch_dup_filename_tags()
elif PLUGIN_ARGS == "rename_files_task":
elif PLUGIN_ARGS_MODE == "rename_files_task":
rename_files_task()
elif inputToUpdateScenePost:
rename_files_task()
if debugTracing: logger.info("\n*********************************\nEXITING ***********************\n*********************************")
# ToDo List
# ToDo: Wish List
# Add logic to update Sqlite DB on file name change, instead of perform_metadata_scan.
# Add code to get tags from duplicate filenames