Pages

Sunday, December 27, 2009

Mythtv Php Script to Create Symlinks with Titles

<?php
###
### CREATE Database file to title lookup
###

$link = mysql_connect('localhost', 'mythtv', 'db_password');
if (!$link) {
    die('Could not connect: ' . mysql_error());
}
$db = mysql_select_db("mythconverg",$link);
if (!$db) {
    die ('Can\'t use mythconverg : ' . mysql_error());
}

$titleLookup = array();

$result = mysql_query("select title, basename from recorded");

while ($row = mysql_fetch_array($result)) {
    $title = $row["title"];
    $titleLookup[$row["basename"]] = $title;
}
mysql_free_result($result);

mysql_close($link);

###
### Create symbolic links
###

$srcBaseFolder = "/var/lib/mythtv/recordings/";
$destBaseFolder = "/var/lib/mythtv/link-share/";

if ($handle = opendir($srcBaseFolder)) {

   while (false !== ($file = readdir($handle))) {

      if ( preg_match('/\.mpg$/', $file) ) {
          $src = $srcBaseFolder . $file;
          $destBase = $destBaseFolder . $titleLookup[$file];
          $dest = $destBase . ".mpg";

          $x = 0;
          while( file_exists($dest) ){
              if( basename(readlink($dest)) == basename($src) ){
                  break;
              }
              $dest = $destBase . "-" . ++$x . ".mpg";
          }
    
          if( !file_exists($dest) ){
              symlink( $src, $dest );
          }
       }
   }

   closedir($handle);
}

###
### Remove bad links
###

if ($handle = opendir($destBaseFolder)) {

   while (false !== ($file = readdir($handle))) {

      $file = $destBaseFolder . $file;

      if ( is_link($file) ) {
          if( !file_exists( readlink($file) ) ){
             unlink($file);
          }
      }
   }

   closedir($handle);
}


No comments:

Post a Comment