Skip to content

Commit

Permalink
Merge pull request #72 from ant385525/renamer-update
Browse files Browse the repository at this point in the history
Update sonarr and radarr rename scripts to work with recent *arr updates and general logic fixes
  • Loading branch information
revenz authored Dec 17, 2024
2 parents 7f2720d + 59ebabc commit 984c342
Show file tree
Hide file tree
Showing 2 changed files with 128 additions and 105 deletions.
24 changes: 12 additions & 12 deletions Scripts/Flow/Applications/Radarr/Radarr - Rename.js
Original file line number Diff line number Diff line change
Expand Up @@ -3,12 +3,11 @@ import { Radarr } from 'Shared/Radarr';
/**
* @description This script will send a rename command to Radarr
* @author Shaun Agius, Anthony Clerici
* @revision 9
* @uid efaf3887-4fcb-42ce-97b2-cc07f1b619d2
* @param {string} URI Radarr root URI and port (e.g. http://radarr:1234)
* @revision 10
* @param {string} URI Radarr root URI and port (e.g. http://radarr:7878)
* @param {string} ApiKey API Key
* @output Item renamed
* @output Item not renamed
* @output Item renamed successfully
* @output Rename not required for item
* @output Item not found
*/
function Script(URI, ApiKey) {
Expand Down Expand Up @@ -38,17 +37,18 @@ function Script(URI, ApiKey) {
});

try {
// Ensure movie is rescanned before renaming
// Ensure movie is refreshed before renaming
let refreshBody = {
movieId: movie.id
movieIds: [movie.id],
isNewMovie: false
}
let refreshData = radarr.sendCommand('RescanMovie', refreshBody)
Logger.ILog('Movie rescanned');
let refreshData = radarr.sendCommand('RefreshMovie', refreshBody)
Logger.ILog('Movie refreshed');

// Wait for the completion of the refresh scan
// Wait for the completion of the refresh
let refreshCompleted = radarr.waitForCompletion(refreshData.id);
if (!refreshCompleted) {
Logger.ILog('rescan not completed');
Logger.ILog('refresh not completed');
return -1;
}

Expand All @@ -74,7 +74,7 @@ function Script(URI, ApiKey) {
return 2;
}

newFileName = System.IO.Path.GetFileName(renamedMovie.newPath);
newFileName = renamedMovie.newPath;
Logger.ILog(`Found it, renaming file to ${newFileName}`);

if (newFileName === null) {
Expand Down
209 changes: 116 additions & 93 deletions Scripts/Flow/Applications/Sonarr/Sonarr - Rename.js
Original file line number Diff line number Diff line change
@@ -1,21 +1,20 @@
import { Sonarr } from 'Shared/Sonarr';

/**
* @description This script will send a rename command to Sonarr
* @description This script will rename the file through Sonarr
* @author Shaun Agius, Anthony Clerici
* @uid 944d4427-6143-4402-b84c-e36ff6c24e52
* @revision 10
* @param {string} URI Sonarr root URI and port (e.g. http://sonarr:1234)
* @revision 11
* @param {string} URI Sonarr root URI and port (e.g. http://sonarr:8989)
* @param {string} ApiKey API Key
* @output Item renamed
* @output Item not renamed
* @output Item renamed successfully
* @output Rename not required for item
* @output Item not found
*/
function Script(URI, ApiKey) {
let sonarr = new Sonarr(URI, ApiKey);
const folderPath = Variables.folder.FullName;
const currentFileName = Variables.file.Name;
const ogPath = Variables.file.Orig.FileName;
const folderPath = Variables.folder.Orig.FullName;
const ogFileName = Variables.file.Orig.FileName;
let currentFileName = Variables.file.FullName;
let newFileName = null;

// Find series name from sonarr
Expand All @@ -24,104 +23,112 @@ function Script(URI, ApiKey) {
if (!series) {
Logger.WLog('Series not found for path: ' + folderPath);
return 3;
} else {
Logger.ILog(`Series found: ${series.title}`);
}

let episodeFile = fetchEpisodeFile(ogPath, series, sonarr)
// Find episode
let [ogEpisodeFile, episode] = fetchEpisode(currentFileName, series, sonarr);

if (!episodeFile) {
Logger.WLog('Episode not in series ' + series.id);
return 3;
if (episode) {
Logger.ILog(`Original episode found: Season ${episode.seasonNumber} Episode: ${episode.episodeNumber}`)
} else {
Logger.WLog(`Episode could not be extracted from series`);
return -1;
}

let episodeFileId = episodeFile.id;
let episode = fetchEpisode(episodeFileId, sonarr);

try {
// Ensure series is refreshed before renaming
let rescanData = rescanSeries(series.id, sonarr);

// Wait for the completion of the scan
let rescanCompleted = sonarr.waitForCompletion(rescanData.id, sonarr);
if (!rescanCompleted) {
Logger.WLog('Rescan failed');
return -1;
}
// Ensure series is refreshed before renaming
let refreshData = refreshSeries(series.id, sonarr);

// Sometimes sonarr doesn't autodetect the transcoded files so we need to manually import it for sonarr to rename it
let manualImport = fetchManualImportFile(currentFileName, series.id, sonarr);
if (manualImport) {
Logger.ILog('Updated file not auto-detected by Sonarr. Manually importing')

let importCommand = manuallyImportFile(manualImport, episode.id, sonarr)

let importCompleted = sonarr.waitForCompletion(importCommand.id, sonarr);
if (!importCompleted) {
Logger.WLog('import not completed');
return -1;
}
// Wait for the completion of the scan
let refreshCompleted = sonarr.waitForCompletion(refreshData.id, sonarr);
if (!refreshCompleted) {
Logger.WLog('refresh failed');
return -1;
}

// Refresh for newly imported episode
rescanData = rescanSeries(series.id, sonarr);
// Wait for the completion of the scan
rescanCompleted = sonarr.waitForCompletion(rescanData.id, sonarr);
if (!rescanCompleted) {
Logger.WLog('Rescan failed');
return -1;
}
// init new file objects
let newEpisodeFile = null;
let newEpisodeFileId = null;

// Reset episodeFile and episode
episodeFile = fetchEpisodeFile(currentFileName, series, sonarr)
// Sometimes sonarr doesn't autodetect the transcoded files so we need to manually import it for sonarr to rename it
let manualImport = fetchManualImportFile(ogFileName, series.id, episode.seasonNumber, sonarr);
if (manualImport) {
Logger.ILog('Updated file not auto-detected by Sonarr. Manually importing')

episodeFileId = episodeFile.id;
episode = fetchEpisode(episodeFileId, sonarr);
let importCommand = manuallyImportFile(manualImport, episode.id, sonarr)

// Sonarr likely unmonitored episode in this scenario, set to monitored
toggleMonitored([episode.id], URI, ApiKey);
let importCompleted = sonarr.waitForCompletion(importCommand.id, sonarr);
if (!importCompleted) {
Logger.WLog('import not completed');
return -1;
}

let renamedEpisodes = fetchRenamedFiles(series.id, sonarr);
if (!renamedEpisodes) {
Logger.ILog('No episodes need to be renamed');
return 2;
// Refresh for newly imported episode
refreshData = refreshSeries(series.id, sonarr);
// Wait for the completion of the scan
refreshCompleted = sonarr.waitForCompletion(refreshData.id, sonarr);
if (!refreshCompleted) {
Logger.WLog('refresh failed');
return -1;
}

Logger.ILog(`Searching for episode file with id ${episodeFileId}`);
renamedEpisodes.every((renamedFile) => {
if (renamedFile.episodeFileId === episodeFileId) {
newFileName = System.IO.Path.GetFileName(renamedFile.newPath);
Logger.ILog(`Found it, renaming file ${episodeFileId} to ${newFileName}`);
return false;
}
return true;
});
// Set new episodeFile and episode
[newEpisodeFile, episode] = fetchEpisode(currentFileName, series, sonarr);
newEpisodeFileId = newEpisodeFile.id;

if (newFileName === null) {
Logger.WLog("Episode doesn't need renaming");
return 2;
}
// Sonarr likely unmonitored episode in this scenario, set to monitored
toggleMonitored([episode.id], URI, ApiKey);
} else {
Logger.ILog(`Manual import not needed`);
}

let renameBody = {
seriesId: series.id,
files: [episodeFileId]
}
let renameResponse = sonarr.sendCommand('RenameFiles', renameBody, URI, ApiKey);
let renameCompleted = sonarr.waitForCompletion(renameResponse.id);
let renamedEpisodes = fetchRenamedFiles(series.id, sonarr);
if (!renamedEpisodes) {
Logger.ILog('No episodes need to be renamed');
return 2;
}

if (!renameCompleted) {
Logger.ILog('Rename not completed');
return -1;
// Find file id of newly grabbed file
if (!newEpisodeFileId) {
[newEpisodeFile, episode] = fetchEpisode(currentFileName, series, sonarr);
newEpisodeFileId = newEpisodeFile.id;
}

Logger.ILog(`Searching for episode file with id ${newEpisodeFileId}`);
renamedEpisodes.every((renamedFile) => {
if (renamedFile.episodeFileId === newEpisodeFileId) {
// Get differences in the path
newFileName = renamedFile.newPath;
Logger.ILog(`Found it, renaming file ${newEpisodeFileId} to ${newFileName}`);
return false;
}
Logger.ILog(`Episode file ${episodeFileId} successfully renamed. Setting as working file.`)
return true;
});

// Sonarr has successfully renamed the file, set new filename as working directory
let newFilePath = System.IO.Path.Combine(Variables.folder.FullName, newFileName);
Flow.SetWorkingFile(newFilePath);
return 1;
if (newFileName === null) {
Logger.WLog("Episode doesn't need renaming");
return 2;
}

let renameBody = {
seriesId: series.id,
files: [newEpisodeFileId]
}
let renameResponse = sonarr.sendCommand('RenameFiles', renameBody, URI, ApiKey);
let renameCompleted = sonarr.waitForCompletion(renameResponse.id);

} catch (error) {
Logger.WLog('Error: ' + error.message);
if (!renameCompleted) {
Logger.ILog('Rename not completed');
return -1;
}
Logger.ILog(`Episode file ${newEpisodeFileId} successfully renamed. Setting as working file.`)

// Sonarr has successfully renamed the file, set new filename as working directory
let newFilePath = System.IO.Path.Combine(Variables.folder.FullName, newFileName);
Flow.SetWorkingFile(newFilePath);
return 1;

}

// Repeatedly try finding a show by shortening the path
Expand Down Expand Up @@ -167,27 +174,29 @@ function fetchRenamedFiles(seriesId, sonarr) {
}

function fetchEpisodeFile(path, series, sonarr) {
Logger.ILog(`Searching for ${path}`);
let allFiles = sonarr.getFilesInShow(series);

for (let file of allFiles) {
if (file.path.endsWith(path)) {
return file;
}
}
Logger.WLog(`Episode file not found in series ${series.title}`);
return null
}

function fetchEpisode(episodeFileId, sonarr) {
function fetchEpisodeFromId(episodeFileId, sonarr) {
let endpoint = 'episode';
let queryParams = `episodeFileId=${episodeFileId}`;
let response = sonarr.fetchJson(endpoint, queryParams);

return response[0];
}

function fetchManualImportFile(currentFileName, seriesId, sonarr) {
function fetchManualImportFile(currentFileName, seriesId, seasonNumber, sonarr) {
let endpoint = 'manualimport';
let queryParams = `seriesId=${seriesId}&filterExistingFiles=true`;
let queryParams = `seriesId=${seriesId}&filterExistingFiles=true&seasonNumber=${seasonNumber}`;
let response = sonarr.fetchJson(endpoint, queryParams);

for (let file of response) {
Expand Down Expand Up @@ -220,11 +229,12 @@ function manuallyImportFile(fileToImport, episodeId, sonarr) {
return sonarr.sendCommand('manualImport', body)
}

function rescanSeries(seriesId, sonarr) {
function refreshSeries(seriesId, sonarr) {
let refreshBody = {
seriesId: seriesId
seriesIds: [seriesId],
isNewSeries: false
}
return sonarr.sendCommand('RescanSeries', refreshBody)
return sonarr.sendCommand('RefreshSeries', refreshBody)
}

function toggleMonitored(episodeIds, URI, ApiKey, monitored=true) {
Expand All @@ -246,8 +256,21 @@ function toggleMonitored(episodeIds, URI, ApiKey, monitored=true) {
Logger.ILog(`Monitored toggled for ${episodeIds}`);
return responseData;
} else {
let error = response.Content.ReadAsStringAsync().Result;
Logger.WLog("API error: " + error);
let error = response.Content.ReadAsStringAsync().Code;
Logger.WLog("API error when manually imoporting. code " + error);
return null;
}
}

function fetchEpisode(currentFileName, series, sonarr) {
let episodeFile = fetchEpisodeFile(currentFileName, series, sonarr);

if (!episodeFile) {
return [null, null];
}

let episodeFileId = episodeFile.id;
let episode = fetchEpisodeFromId(episodeFileId, sonarr);

return [episodeFile, episode];
}

0 comments on commit 984c342

Please sign in to comment.