Skip to content

Instantly share code, notes, and snippets.

@jonjomckay
Last active December 8, 2015 23:58
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jonjomckay/af36735dd9126935ae5d to your computer and use it in GitHub Desktop.
Save jonjomckay/af36735dd9126935ae5d to your computer and use it in GitHub Desktop.
Anime Renamer
<?php
/* Anime Rename script v1.0 by Werner Buck updatdate by squareatom 02/17/2011 and again update by fda 04/17/2011 and updated by jonjomckay 08/12/2015
*
* Searches directory recursively for .mkv/.avi/.mp4 video files.
* When found it tries to find the season and episode on www.thetvdb.com to rename
* the file so it can be correctly scraped by XBMC's TvDB scraper.
*
* Can be used for SABnzbd and or as standalone script
* Requires:
* - PHP-CLI (ubuntu apt-get install php5-cli)
* - Correct permissions.
* Could work for windows not tested.
*
* Example command:
* php -f procanime.php -- '/storage/Anime/Mobile Suit Gundam 00/'
*/
error_reporting(0);
if ($argc == 1 || $argv[1] == '--help' || $argv[1] == '/?' || $argv[1] == '-help') {
fwrite(STDOUT, "Anime Rename script v1.0\n\nSearches directory recursively for .mkv/.avi/.mp4 video files.\nWhen found it tries to find the season and episode on www.thetvdb.com to rename\nthe
file so it can be correctly scraped by XBMC's TvDB scraper.\n\nCan be used for SABnzbd and or as standalone script\nRequires:\n- PHP-CLI (ubuntu apt-get install php5-cli)\n- Correct permissions.\nCould
work for windows not tested.\n\nExample command:\nphp -f ".$argv[0]." -- '/storage/Anime/Mobile Suit Gundam 00/'\n");
} elseif ($argc > 1) {
$directory = "";
for ($i=1; $i < count ($argv); $i++) {
if ($i != 1) {
$directory .= ' ';
}
$directory .= $argv[$i] . '';
}
//remove trailing slash
if ('/' == substr($directory, strlen($directory)-1)) {
$directory = substr_replace($directory, '', strlen($directory)-1);
}
$status = rec_listFiles($directory);
if ($status === false) {
fwrite(STDOUT, "FAILED, directory does not exist or is not accessible. Make sure your permissions are properly setup.\n");
} else {
for ($i=0; $i < count($status); $i++) {
$fullfile = $status[$i];
$file = basename($fullfile);
$dirname = dirname($fullfile);
$extension = get_extension($file);
if ($extension == ".mkv" || $extension == ".avi" || $extension == ".mp4") {
$result = animealize($file);
if ($result['status'] == 1) {
fwrite(STDOUT, $result['output']);
fwrite(STDOUT, "FAILED, Show not found on TheTVDB.com.\n\n");
} elseif ($result['status'] == 2) {
fwrite(STDOUT, $result['output']);
fwrite(STDOUT, "FAILED, Absolute number not found on TheTVDB.com for this show.\n\n");
} elseif ($result['status'] == 3) {
fwrite(STDOUT, $result['output']);
fwrite(STDOUT, "SKIPPED, Already named correctly.\n");
} elseif ($result['status'] == 4) {
fwrite(STDOUT, $result['output']);
//Do actual rename here:
$worked = rename($fullfile, $dirname . '/' . $result['filename']);
if ($worked === false) {
fwrite(STDOUT, "FAILED, Could not rename ".$fullfile." to ".$dirname."/".$result['filename'].". Check Permissions!\n\n");
} else {
fwrite(STDOUT, "SUCCESS, Renamed from ".$fullfile." to ".$dirname."/".$result['filename']."\n\n");
}
}
}
}
}
}
function animealize ($file) {
$output = $file . "\n";
if (preg_match('/(S|s)([0-9]+)(E|e)([0-9]+)/', $file, $match) == 0) {
$result = get_show_name(rid_extension($file));
$output .= "Show name: " . $result . "\n";
$seasonarray = get_season_number($result);
$output .= "Possible season number: " . $seasonarray['res'] . "\n";
$episodearray = get_episode_number($result);
$output .= "Episode number: " . $episodearray['res'] . "\n";
$cleanshowname = $result;
if ($seasonarray) {
$cleanshowname = trim(str_replace($seasonarray['del'],'',$cleanshowname));
}
$cleanshowname = trim(str_replace($episodearray['del'],'',$cleanshowname));
$output .= "Clean Show Name: " . $cleanshowname . "\n";
$tvdb_series_info = get_tvdb_seriesinfo($cleanshowname);
if ($tvdb_series_info === false) {
return array('status' => '1', 'output' => $output);
}
$output .= "TheTVDB Series Name: " . $tvdb_series_info['name'] . "\n";
$output .= "TheTVDB Series ID: " . $tvdb_series_info['id'] . "\n";
$tvdb_episode_info = get_tvdb_episodeinfo($tvdb_series_info['id'], $episodearray['res'], $seasonarray['res']);
if ($tvdb_episode_info === false) {
return array('status' => '2', 'output' => $output);
}
$output .= "TheTVDB Series Season: " . $tvdb_episode_info['season'] . "\n";
$output .= "TheTVDB Series Episode: " . $tvdb_episode_info['episode'] . "\n";
$new_filename = gen_proper_filename($file, $tvdb_episode_info['episode'], $tvdb_episode_info['season']);
} else {
return array('status' => '3', 'output' => $output);
}
return array('status' => '4', 'output' => $output, 'filename' => $new_filename);
}
function gen_proper_filename($input, $episode, $season) {
$delimiter = '.';
$extension = get_extension($input);
$output = rid_extension($input);
if ($episode > 99) {
$string = 'S' . str_pad($season, 2, "0", STR_PAD_LEFT) . 'E' . str_pad($episode, 3, "0", STR_PAD_LEFT);
} else {
$string = 'S' . str_pad($season, 2, "0", STR_PAD_LEFT) . 'E' . str_pad($episode, 2, "0", STR_PAD_LEFT);
}
$output = $string . $extension;
return $output;
}
function get_tvdb_seriesinfo($input) {
$thetvdb = "http://www.thetvdb.com/";
$result = file_get_contents($thetvdb . 'api/GetSeries.php?seriesname='.urlencode($input));
$postemp1 = strpos($result, "<seriesid>") + strlen("<seriesid>");
$postemp2 = strpos($result, "<", $postemp1);
$seriesid = substr($result, $postemp1, $postemp2 - $postemp1);
if (is_numeric($seriesid) === false) {
return false;
}
$postemp1 = strpos($result, "<SeriesName>") + strlen("<SeriesName>");
$postemp2 = strpos($result, "<", $postemp1);
$seriesname = substr($result, $postemp1, $postemp2 - $postemp1);
$tvdb = array('id' => $seriesid, 'name' => $seriesname);
return $tvdb;
}
function get_tvdb_episodeinfo($seriesid, $episode, $season) {
if (empty($season)) {
$thetvdb = "http://www.thetvdb.com/";
$result = file_get_contents($thetvdb . 'api/F0A9519B01D1C096/series/'.$seriesid.'/absolute/'.$episode.'/en.xml');
if ($result === false) {
return false;
}
$postemp1 = strpos($result, "<EpisodeNumber>") + strlen("<EpisodeNumber>");
$postemp2 = strpos($result, "<", $postemp1);
$episodenumber = substr($result, $postemp1, $postemp2 - $postemp1);
$postemp1 = strpos($result, "<SeasonNumber>") + strlen("<SeasonNumber>");
$postemp2 = strpos($result, "<", $postemp1);
$episodeseason = substr($result, $postemp1, $postemp2 - $postemp1);
$tvdb = array('episode' => $episodenumber, 'season' => $episodeseason);
} else {
$tvdb = array('episode' => $episode, 'season' => $season);
}
return $tvdb;
}
function get_show_name($input) {
$pattern = '/' . '\[[^]]+\]|\([^]]+\)' . '/i';
$result = preg_replace($pattern,"",$input);
$result = str_replace("-", " ",$result);
$result = str_replace("_", " ",$result);
$result = str_replace(".", " ",$result);
// remove double spaces in the middle
while (sizeof ($array=explode (" ",$result)) != 1)
{
$result = implode (" ",$array);
}
return trim($result);
}
function rid_extension($thefile) {
if (strpos($thefile,'.') === false) {
return $thefile;
} else {
return substr($thefile, 0, strrpos($thefile,'.'));
}
}
function get_extension($thefile) {
return substr($thefile, strrpos($thefile,'.'));
}
function get_episode_number($input) {
if (preg_match('/' . '(E|e)([0-9]+)' . '/', $input, $episodenumber) > 0) {
$episodenumber = array('del' => $episodenumber[0], 'res' => $episodenumber[2]);
// fda change <--start
if ($episodearray['res'][0] == '0')
$episodenumber['res'] = substr($episodenumber['res'], 1);
// fda changes end-->
return $episodenumber;
} else {
preg_match_all('/' . '[0-9]+' . '/', $input, $matches);
//Kijk voor alle episodes
$matches = $matches[0];
for ($i=0; $i < count($matches); $i++) {
$lastnum = $matches[$i];
}
$lastnum = array('del' => $lastnum, 'res' => $lastnum);
// fda change <--start
if ($lastnum['res'][0] == '0')
$lastnum['res'] = substr($lastnum['res'], 1);
// fda changes end-->
return $lastnum;
}
}
function get_season_number($input) {
$pattern = '/' . '(S|s)([0-9]+)' . '/';
if (preg_match($pattern, $input, $match) > 0) {
$match = array('del' => $match[0], 'res' => $match[2]);
return $match;
} else {
return false;
}
}
function rec_listFiles( $from = '.')
{
if(! is_dir($from))
return false;
$files = array();
if( $dh = opendir($from))
{
while( false !== ($file = readdir($dh)))
{
// Skip '.' and '..'
if( $file == '.' || $file == '..')
continue;
$path = $from . '/' . $file;
if( is_dir($path) )
$files=array_merge($files,rec_listFiles($path));
else
$files[] = $path;
}
closedir($dh);
}
return $files;
}
?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment