Advertisement
Guest User

Anime TheTVDB Rename Script

a guest
Feb 17th, 2011
1,772
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
PHP 8.55 KB | None | 0 0
  1. <?php
  2. /* Anime Rename script v1.0 by Werner Buck updatdate by squareatom 02/17/2011
  3.  *
  4.  * Searches directory recursively for .mkv/.avi/.mp4 video files.  
  5.  * When found it tries to find the season and episode on www.thetvdb.com to rename
  6.  * the file so it can be correctly scraped by XBMC's TvDB scraper.
  7.  *
  8.  * Can be used for SABnzbd and or as standalone script
  9.  * Requires:
  10.  * - PHP-CLI (ubuntu apt-get install php5-cli)
  11.  * - Correct permissions.
  12.  * Could work for windows not tested.
  13.  *  
  14.  * Example command:
  15.  * php -f procanime.php -- '/storage/Anime/Mobile Suit Gundam 00/'
  16.  */
  17. error_reporting(0);
  18.  
  19. if ($argc == 1 || $argv[1] == '--help' || $argv[1] == '/?' || $argv[1] == '-help') {
  20.     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");
  21. } elseif ($argc > 1) {
  22.     $directory = "";
  23.     for ($i=1; $i < count ($argv); $i++) {
  24.         if ($i != 1) {
  25.             $directory .= ' ';
  26.         }
  27.         $directory .= $argv[$i] . '';
  28.     }
  29.     //remove trailing slash
  30.     if ('/' == substr($directory, strlen($directory)-1)) {
  31.         $directory = substr_replace($directory, '', strlen($directory)-1);
  32.     }
  33.     $status = rec_listFiles($directory);
  34.     if ($status === false) {
  35.         fwrite(STDOUT, "FAILED, directory does not exist or is not accessible. Make sure your permissions are properly setup.\n");
  36.     } else {
  37.         for ($i=0; $i < count($status); $i++) {
  38.            
  39.             $fullfile = $status[$i];
  40.             $file = basename($fullfile);
  41.             $dirname = dirname($fullfile);
  42.             $extension = get_extension($file);
  43.             if ($extension == ".mkv" || $extension == ".avi" || $extension == ".mp4") {
  44.                 $result = animealize($file);
  45.                 if ($result['status'] == 1) {
  46.                     fwrite(STDOUT, $result['output']);
  47.                     fwrite(STDOUT, "FAILED, Show not found on TheTVDB.com.\n\n");
  48.                 } elseif ($result['status'] == 2) {
  49.                     fwrite(STDOUT, $result['output']);
  50.                     fwrite(STDOUT, "FAILED, Absolute number not found on TheTVDB.com for this show.\n\n");             
  51.                 } elseif ($result['status'] == 3) {
  52.                     fwrite(STDOUT, $result['output']);
  53.                     fwrite(STDOUT, "SKIPPED, Already named correctly.\n");
  54.                 } elseif ($result['status'] == 4) {
  55.                     fwrite(STDOUT, $result['output']);
  56.                     //Do actual rename here:
  57.                     $worked = rename($fullfile, $dirname . '/' . $result['filename']);
  58.                     if ($worked === false) {
  59.                         fwrite(STDOUT, "FAILED, Could not rename ".$fullfile." to  ".$dirname."/".$result['filename'].". Check Permissions!\n\n");
  60.                     } else {
  61.                         fwrite(STDOUT, "SUCCESS, Renamed from ".$fullfile." to  ".$dirname."/".$result['filename']."\n\n");
  62.                     }
  63.             }
  64.             }
  65.         }
  66.     }
  67. }
  68.  
  69. function animealize ($file) {
  70.     $output = $file . "\n";
  71.     if (preg_match('/(S|s)([0-9]+)(E|e)([0-9]+)/', $file, $match) == 0) {
  72.         $result = get_show_name(rid_extension($file));
  73.         $output .= "Show name: " . $result . "\n";
  74.         $seasonarray = get_season_number($result);
  75.         $output .= "Possible season number: " . $seasonarray['res'] . "\n";
  76.         $episodearray = get_episode_number($result);
  77.         $output .= "Episode number: " . $episodearray['res'] . "\n";
  78.         $cleanshowname = $result;
  79.         if ($seasonarray) {
  80.             $cleanshowname = trim(str_replace($seasonarray['del'],'',$cleanshowname));
  81.         }
  82.         $cleanshowname = trim(str_replace($episodearray['del'],'',$cleanshowname));
  83.         $output .= "Clean Show Name: " . $cleanshowname . "\n";
  84.         $tvdb_series_info = get_tvdb_seriesinfo($cleanshowname);
  85.         if ($tvdb_series_info === false) {
  86.             return array('status' => '1', 'output' => $output);
  87.         }
  88.         $output .= "TheTVDB Series Name: " . $tvdb_series_info['name'] . "\n";
  89.         $output .= "TheTVDB Series ID: " . $tvdb_series_info['id'] . "\n";
  90.         $tvdb_episode_info = get_tvdb_episodeinfo($tvdb_series_info['id'], $episodearray['res'], $seasonarray['res']);
  91.         if ($tvdb_episode_info === false) {
  92.             return array('status' => '2', 'output' => $output);
  93.         }
  94.         $output .= "TheTVDB Series Season: " . $tvdb_episode_info['season'] . "\n";
  95.         $output .= "TheTVDB Series Episode: " . $tvdb_episode_info['episode'] . "\n";
  96.         $new_filename = gen_proper_filename($file, $tvdb_episode_info['episode'], $tvdb_episode_info['season']);
  97.     } else {
  98.         return array('status' => '3', 'output' => $output);
  99.     }
  100.     return array('status' => '4', 'output' => $output, 'filename' => $new_filename);
  101. }
  102.  
  103.  
  104. function gen_proper_filename($input, $episode, $season) {
  105.     $delimiter = '.';
  106.     $extension = get_extension($input);
  107.     $output = rid_extension($input);
  108.     if ($episode > 99) {
  109.         $string = 'S' . str_pad($season, 2, "0", STR_PAD_LEFT) . 'E' . str_pad($episode, 3, "0", STR_PAD_LEFT);
  110.     } else {
  111.         $string = 'S' . str_pad($season, 2, "0", STR_PAD_LEFT) . 'E' . str_pad($episode, 2, "0", STR_PAD_LEFT);
  112.     }
  113.     $output = $output . $delimiter . $string . $extension;
  114.     return $output;
  115. }
  116.  
  117. function get_tvdb_seriesinfo($input) {
  118.     $thetvdb = "http://www.thetvdb.com/";
  119.     $result = file_get_contents($thetvdb . 'api/GetSeries.php?seriesname='.urlencode($input));
  120.     $postemp1 = strpos($result, "<seriesid>") + strlen("<seriesid>");
  121.     $postemp2 = strpos($result, "<", $postemp1);
  122.     $seriesid = substr($result, $postemp1, $postemp2 - $postemp1);
  123.     if (is_numeric($seriesid) === false) {
  124.         return false;
  125.     }
  126.     $postemp1 = strpos($result, "<SeriesName>") + strlen("<SeriesName>");
  127.     $postemp2 = strpos($result, "<", $postemp1);
  128.     $seriesname = substr($result, $postemp1, $postemp2 - $postemp1);
  129.     $tvdb = array('id' => $seriesid, 'name' => $seriesname);
  130.     return $tvdb;
  131. }
  132.  
  133. function get_tvdb_episodeinfo($seriesid, $episode, $season) {
  134.     if (empty($season)) {
  135.         $thetvdb = "http://www.thetvdb.com/";
  136.         $result = file_get_contents($thetvdb . 'api/F0A9519B01D1C096/series/'.$seriesid.'/absolute/'.$episode);
  137.         if ($result === false) {
  138.             return false;
  139.         }
  140.         $postemp1 = strpos($result, "<EpisodeNumber>") + strlen("<EpisodeNumber>");
  141.         $postemp2 = strpos($result, "<", $postemp1);
  142.         $episodenumber = substr($result, $postemp1, $postemp2 - $postemp1);
  143.         $postemp1 = strpos($result, "<SeasonNumber>") + strlen("<SeasonNumber>");
  144.         $postemp2 = strpos($result, "<", $postemp1);
  145.         $episodeseason = substr($result, $postemp1, $postemp2 - $postemp1);
  146.         $tvdb = array('episode' => $episodenumber, 'season' => $episodeseason);
  147.     } else {
  148.         $tvdb = array('episode' => $episode, 'season' => $season);
  149.     }
  150.     return $tvdb;
  151. }
  152.  
  153. function get_show_name($input) {
  154.     $pattern = '/' . '\[[^]]+\]|\([^]]+\)' . '/i';
  155.     $result = preg_replace($pattern,"",$input);
  156.     $result = str_replace("-", " ",$result);
  157.     $result = str_replace("_", " ",$result);
  158.     $result = str_replace(".", " ",$result);
  159.     // remove double spaces in the middle
  160.     while (sizeof ($array=explode ("  ",$result)) != 1)
  161.     {
  162.          $result = implode (" ",$array);
  163.     }
  164.     return trim($result);
  165. }
  166.  
  167. function rid_extension($thefile) {
  168.     if (strpos($thefile,'.') === false) {
  169.         return $thefile;
  170.     } else {
  171.         return substr($thefile, 0, strrpos($thefile,'.'));
  172.     }
  173. }
  174.  
  175. function get_extension($thefile) {
  176.     return substr($thefile, strrpos($thefile,'.'));
  177. }
  178.  
  179. function get_episode_number($input) {
  180.     if (preg_match('/' . '(E|e)([0-9]+)' . '/', $input, $episodenumber) > 0) {
  181.         $episodenumber = array('del' => $episodenumber[0], 'res' => $episodenumber[2]);
  182.         return $episodenumber;
  183.     } else {
  184.         preg_match_all('/' . '[0-9]+' . '/', $input, $matches);
  185.         //Kijk voor alle episodes
  186.         $matches = $matches[0];
  187.         for ($i=0; $i < count($matches); $i++) {
  188.             $lastnum = $matches[$i];
  189.         }
  190.         $lastnum = array('del' => $lastnum, 'res' => $lastnum);
  191.         return $lastnum;
  192.     }
  193. }
  194.  
  195. function get_season_number($input) {
  196.     $pattern = '/' . '(S|s)([0-9]+)' . '/';
  197.     if (preg_match($pattern, $input, $match) > 0) {
  198.         $match = array('del' => $match[0], 'res' => $match[2]);
  199.         return $match;
  200.     } else {
  201.         return false;
  202.     }
  203. }
  204.  
  205. function rec_listFiles( $from = '.')
  206. {
  207.     if(! is_dir($from))
  208.         return false;
  209.    
  210.     $files = array();
  211.     if( $dh = opendir($from))
  212.     {
  213.         while( false !== ($file = readdir($dh)))
  214.         {
  215.             // Skip '.' and '..'
  216.             if( $file == '.' || $file == '..')
  217.                 continue;
  218.             $path = $from . '/' . $file;
  219.             if( is_dir($path) )
  220.                 $files=array_merge($files,rec_listFiles($path));
  221.             else
  222.                 $files[] = $path;
  223.         }
  224.         closedir($dh);
  225.     }
  226.     return $files;
  227. }
  228.  
  229. ?>
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement