WTV File Renaming for Plex/XBMC

classic Classic list List threaded Threaded
5 messages Options
Reply | Threaded
Open this post in threaded view
|  
Report Content as Inappropriate

WTV File Renaming for Plex/XBMC

darkstarEmber
Greetings. I love this tool and was happy to shell out the money to purchase it. It brings depth to WMC and makes the HTPC experience that much better for me.

*** Problem Statement ***

I've been using Plex to stream WTV files to my iPad and it's a great capability when I'm around or outside of my home.  However, for Plex to recognize various TV and Movie files, they must be named in a certain way. There is some customization with Plex available, but the requirements are detailed by the following URL. I've been able to write a small script that gets it right sometimes. I have yet to find an application that can accurately identify the season and episode of a WTV file as well as Recorded TV HD does. (MC-TVConverter, MCE Buddy Public Release)

The following link details the file naming structure that Plex requires:

http://wiki.plexapp.com/index.php/Media_Naming_and_Organization_Guide#Standard_TV_Shows

Ex: Heroes - s01e01.wtv

Obviously, Recorded TV HD has the needed information to turn a file into the Series -sXXeXX.wtv format. I have found the file "RecordedTVHDdb.s3db" and read it with SQLStudioLite (freeware). A manual CSV dump is enough to write a Perl script to perform this task... however automation would be a great benefit.


*** Feature Request ***

Any of the following responses would be much appreciated:
1) Details on how to read "RecordedTVHDdb.s3db" in a common programming language and I'll code something up and share it with the community.
2) A feature that let's you rename files and put them into a designated folder structure.

Thanks again and this really is a superb add-on to WMC.
Reply | Threaded
Open this post in threaded view
|  
Report Content as Inappropriate

Re: WTV File Renaming for Plex/XBMC

c1orox
Second this request! I use Recorded TV on my main HTPC, but buying another xbox extender for use over a long cat run to the bedroom is not a desirable option.

Using a Roku + Plex (or how about a Recorded TV channel on Roku!) is ideal.

-Adam
Reply | Threaded
Open this post in threaded view
|  
Report Content as Inappropriate

Re: WTV File Renaming for Plex/XBMC

MJT Software
Administrator
In reply to this post by darkstarEmber
If you want to try to program something you can use a .NET language with the System.Data.SQLite.dll file in the Recorded TV HD program files directory.

Here is the website with all the documentation, etc:
http://system.data.sqlite.org/

With a quick Google search here is some code for examples:
http://www.codeproject.com/Articles/22165/Using-SQLite-in-your-C-Application

I use .net 3.5 framework because everybody should have that and use the following code to locate the RecordedTVHD database:

DirectoryInfo diSpecial = new DirectoryInfo(Environment.GetFolderPath(Environment.SpecialFolder.System));

            if (Directory.Exists(Path.Combine(diSpecial.FullName.ToLower().Replace("windows\\system32", ""), "Users\\Public\\")))
            {
                mStringProgramFiles = Path.Combine(diSpecial.FullName.ToLower().Replace("windows\\system32", ""), "Users\\Public\\RecordedTVHD\\");
            }
            else
            {
                if (Directory.Exists(@"C:\ProgramData"))
                {
                    mStringProgramFiles = @"C:\ProgramData\RecordedTVHD\";
                }
                else
                {
                    mStringProgramFiles = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.CommonApplicationData), "\\RecordedTVHD\\");
                }
            }

            try
            {
                if (File.Exists(Path.Combine(mStringProgramFiles, "database\\RecordedTVHDdb.s3db")))
                {
                    sql_con = new SQLiteConnection("Data Source=" + mStringProgramFiles + "\\database\\RecordedTVHDdb.s3db");
                    sql_cmd = new SQLiteCommand(sql_con);
                }
                else
                {
                    MessageBox.Show("Could not locate database file.", "Database error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
            }
            catch
            {
                MessageBox.Show("Could not locate database file.", "Database error", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }


Have fun!
Reply | Threaded
Open this post in threaded view
|  
Report Content as Inappropriate

Re: WTV File Renaming for Plex/XBMC

darkstarEmber
In reply to this post by darkstarEmber
Figured this one out a while ago and wrote the following Perl script. It relies on sqlite3.exe (freeware) and makes a copy of the Recorded TV HD database. You'll need to install a copy of active Perl and also use the command line "ppm install Text-CSV" to install the needed parsing library. Good luck and it works great with renaming for Plex!

Put it on a windows scheduled task which runs invisibly. You'll need to make some edits for your implementation, so good luck... if anyone is still using this product anyway...

#!C:/Perl/bin/Perl.exe --
#!/usr/bin/perl --


    use strict;
    use File::Path;
    use File::Copy;
    use File::Basename;
    #use Benchmark;
    use Cwd;
    use Text::CSV;
   

   
   
    our $programDir = cwd();
    print "$programDir\n\n";
   
   
   
sub makeQuery
{
    my ( $query ) = @_;
    #`"sqlite3.exe" "RecordedTVHDdb.s3db" "select * from episodes;" `;
   
    my $result = `"sqlite3.exe" "RecordedTVHDdb.s3db" "$query"`;
    chomp( $result );
    return $result;
}

sub readFile
{
    my ($inputFile ) = @_;
   
    open( FILEINPUTIN, $inputFile ) or warn "Unable to open file $inputFile\n";
    my @inputFileData = <FILEINPUTIN>;
    chomp( @inputFileData );
    close( FILEINPUTIN );
   
    return @inputFileData;
}
sub saveFile
{
    my ( $outputFileName, @outputFileData ) = @_;
   
    open( FILEOUTPUT, ">$outputFileName" ) or warn "Unable to write to $outputFileName!\n";
    foreach my $line ( @outputFileData )
    {
        print FILEOUTPUT "$line\n";
    }
    close( FILEOUTPUT );
   
    return;
}
sub makeDoubleDigitString
{
    my ( $input ) = @_;
   
    $input += 0;
    $input = abs(int( $input ));
   
    if ( $input < 9 )
    {
        $input = "0$input";
    }
    return $input;  
}
sub makeFileSafe
{
    my ( $string ) = @_;
   
    $string =~ s/[^A-Za-z0-9\-_ ]//g;
   
    return $string;
}
#****************************************
#The purpose of this program is to open the s3db file from Recorded TV HD and then use the information to rename the recorded TV files into something that plex can recognize.

    print "*** Organize Media ***\n\n";


    chdir( "W:/Recorded TV/" ) or warn;


    print "Scanning Recorded TV HD Database...\n";

    my $mainDatabaseFilePath = "F:/Users/Public/RecordedTVHD/database/RecordedTVHDdb.s3db";
    my $cleanDatabaseFilePath = basename( $mainDatabaseFilePath );
   
    #go and get the most recent RecordedTVHD database file
    copy( $mainDatabaseFilePath, $cleanDatabaseFilePath ) or warn "Unable to get most recent copy of database file!\n";
   
    #to make this easy on ourselves, we are simply going to read in an episode headers file...
    my @episodeHeaders = readFile( "episodeHeaders.txt" );
   
    #now, get the dump of the database file...

    my $databaseQuery = makeQuery( "select * from episodes;" );
   
    #create a file and save it
    my @databaseFileData;
    push( @databaseFileData, join( "\t", @episodeHeaders ) );
    $databaseQuery =~ s/\|/\t/g;
    push( @databaseFileData, $databaseQuery);
    saveFile( "episodeDatabaseDump.txt", @databaseFileData );
   

    #saveFile( "F:/changeList.txt", @changeList);
    #saveFile( "changeList.txt", @changeList);
   

   
   
   
    my @changeListAll;
    push( @changeListAll, "CleanInputFile,SeriesName,EpisodeName,Description,TVNetwork,BroadcastDate,ChannelNumber,StationCallSign,Movie,SeasonNumber,EpisodeNumber,PercentageWatched,NewFilename,CaseNumber,FileExists,FileLocked,RenameSuccess" );
       
   
   
    #get the list of files that are on disk...
    my @inputFiles = split( "\n", makeQuery( "select FileLocation from episodes;" ));
    my @cleanInputFiles;
    foreach my $inputFile ( @inputFiles )
    {
        my $cleanInputFile = $inputFile;
        $cleanInputFile =~ s/\\/\//g;
        $cleanInputFile = basename( $cleanInputFile );
        push( @cleanInputFiles, $cleanInputFile );
       
        #let's keep this one simple for now
        my $suffix = "wtv";
       
        #now, let's determine what can be done with each file...
       
       
        my $seriesName =  makeQuery( "select SeriesName from episodes where FileLocation='$inputFile';" );
        my $episodeName = makeQuery( "select EpisodeName from episodes where FileLocation='$inputFile';" );
        my $description = makeQuery( "select Description from episodes where FileLocation='$inputFile';" );
        my $tvNetwork = makeQuery( "select TVNetwork from episodes where FileLocation='$inputFile';" );
        my $broadcastDate =  makeQuery( "select BroadcastDate from episodes where FileLocation='$inputFile';" );
        my $channelNumber = makeQuery( "select ChannelNumber from episodes where FileLocation='$inputFile';" );
        my $stationCallSign =  makeQuery( "select StationCallSign from episodes where FileLocation='$inputFile';" );
        my $movie = makeQuery( "select Movie from episodes where FileLocation='$inputFile';" );
        my $seasonNumber = makeQuery( "select SeasonNumber from episodes where FileLocation='$inputFile';" );
        my $episodeNumber = makeQuery( "select EpisodeNumber from episodes where FileLocation='$inputFile';" );
        my $percentageWatched = makeQuery( "select PercentageWatched from episodes where FileLocation='$inputFile';" );
        print "\n\n";
       
       
        print "Input File:\t" . $inputFile . "\n";
        print "Clean File:\t" . $cleanInputFile . "\n";
        print "Series Name:\t" . $seriesName."\n";
        print "Episode Name:\t" . $episodeName ."\n";
        print "Description:\t" . $description ."\n";
        print "TVNetwork:\t" . $tvNetwork ."\n";
        print "BroadcastDate:\t" . $broadcastDate ."\n";
        print "ChannelNumber:\t" . $channelNumber ."\n";
        print "StationCallSign:\t" . $stationCallSign ."\n";
        print "Movie:\t" . $movie ."\n";
        print "SeasonNumber:\t" . $seasonNumber ."\n";
        print "EpisodeNumber:\t" . $episodeNumber ."\n";
        print "PercentageWatched:\t" . $percentageWatched ."\n";
       
       
       
       
        #now, it is time for the exciting sorting to begin!

        #Date-Based Television Series
       
        my $newFilename;
        my $caseNumber = 0;
        if ( $movie == 1 )
        {
            #Movie
            $newFilename = makeFileSafe($seriesName) . " - s00e00" . ".$suffix";
            $caseNumber = 1;
        }
        elsif ( $seriesName =~ /\S/ and $seasonNumber =~ /\S/ and $episodeNumber =~ /\S/ and $episodeName =~ /\S/ )
        {
             #Series - Episode Notation
            $newFilename = makeFileSafe($seriesName) . " - s" . makeDoubleDigitString($seasonNumber) . "e" .
            makeDoubleDigitString($episodeNumber) . " - " . makeFileSafe($episodeName) . ".$suffix";
            $caseNumber = 2;
        }
        elsif ( $seriesName =~ /\S/ and $seasonNumber =~ /\S/ and $episodeNumber =~ /\S/ )
        {
            # Series - Episode Notation
            $newFilename = makeFileSafe($seriesName) . " - s" . makeDoubleDigitString($seasonNumber) . "e" .
            makeDoubleDigitString($episodeNumber) . ".$suffix";
            $caseNumber = 3;
        }
        elsif ( $seriesName =~ /\S/ and $episodeName =~ /\S/ )
        {
            my ( $broadcastDateDate, $broadcastTimeTime ) = split( " ", $broadcastDate );
           
            my $broadcastDigits = $broadcastDateDate;
            $broadcastDigits =~ s/\D//g;
           
            #Special Episode
            #ShowName - s00eYY - Optional Show Title.wtv
            $newFilename = makeFileSafe($seriesName) . " - " . "s00e" . $broadcastDigits ." - ". makeFileSafe($episodeName). ".$suffix";
            $caseNumber = 4;

        }
        elsif ( $seriesName =~ /\S/ )
        {
            my ( $broadcastDateDate, $broadcastTimeTime ) = split( " ", $broadcastDate );
           
            my $broadcastDigits = $broadcastDateDate;
            $broadcastDigits =~ s/\D//g;
           
            #Special Episode
            #ShowName - s00eYY - Optional Show Title.wtv
            $newFilename = makeFileSafe($seriesName) . " - " . "s00e" . $broadcastDigits . ".$suffix";
            $caseNumber = 5;

        }
        elsif ( $seriesName =~ /\S/ and $broadcastDate =~ /\S/  and 0)
        {
             my ( $broadcastDateDate, $broadcastTimeTime ) = split( " ", $broadcastDate );
           
            # Date-Based
            #   ShowName - YYYY-MM-DD.wtv
            #   ShowName - MM-DD-YYYY.wtv
            #2016-06-12 17:34:18.7779799
            $newFilename = makeFileSafe($seriesName) . " - " .   $broadcastDateDate.".$suffix";
            #$newFilename = makeFileSafe($seriesName) . " - " .   $broadcastDateDate ." - ". makeFileSafe($tvNetwork . "_" . $channelNumber).".$suffix";
            $caseNumber = 6;
           
        }
        else
        {
            #leave it alone. we don't know what it really is.
            $caseNumber = 7;
        }
       
        print "New Filename:\t" . $newFilename ."\n";
        print "Case Number:\t" . $caseNumber . "\n";
       

       
        #time for the file modification action...
       
        #test the file to see if it is locked
       
        my $fileExists = 0;
        if ( -e $cleanInputFile ) { $fileExists = 1; }
        print "File Exists:\t$fileExists\n";
       
        my $fileLocked = 0;
        if ( not rename($cleanInputFile, $cleanInputFile ) ){ $fileLocked = 1; }
        print "File Locked:\t$fileLocked\n";
       
        my $renameSuccess = 0;
        #here's the magic...
        if ( $fileExists == 1 and $fileLocked == 0)
        {
            $renameSuccess = 1;
            move($cleanInputFile, $newFilename ) or $renameSuccess = 0;
        }
        print "Rename Success:\t$renameSuccess\n";

        print "\n\n";
       
        my @changeList;
        push( @changeList, $cleanInputFile );
        push( @changeList, $seriesName );
        push( @changeList, $episodeName );
        push( @changeList, $description );
        push( @changeList, $tvNetwork );
        push( @changeList, $broadcastDate );
        push( @changeList, $channelNumber );
        push( @changeList, $stationCallSign );
        push( @changeList, $movie );
        push( @changeList, $seasonNumber );
        push( @changeList, $episodeNumber );
        push( @changeList, $percentageWatched );
        push( @changeList, $newFilename );
        push( @changeList, $caseNumber );
        push( @changeList, $fileExists );
        push( @changeList, $fileLocked );
        push( @changeList, $renameSuccess );
       
        push(@changeListAll, join( "\t", @changeList) );
    }
   
   
   
   
   
    saveFile( "changeList.txt", @changeListAll );
   
    print "Script Complete!!!\n";
    sleep( 3 );
   
Reply | Threaded
Open this post in threaded view
|  
Report Content as Inappropriate

Re: WTV File Renaming for Plex/XBMC

IT Troll
Nice script, thanks for sharing.

If the author of RTVHD made the source code available I am sure development could continue within the user community.
Loading...