Showing posts with label PowerShell. Show all posts
Showing posts with label PowerShell. Show all posts

Saturday, April 14, 2012

MDL: Maintain the XBMC Library

One of the most frustrating things about XBMC is the static nature of its library.  The forums are full of people asking “How do you force the XBMC library to refresh?”  Many of them are asking specifically about the thumbnails and fanart.  My biggest concern is the metadata.

I have a mild case of OCD and am constantly tweaking the information about my movie collection.  Unfortunately, XBMC doesn’t ever pick up this information.  You can refresh movies manually, one by one.  But that process is tedious at best.

You can also delete the database and rebuild it.  But that kind of defeats the purpose of having a library, doesn’t it?  If you go this path you lose watch history, ratings and other information.

I think that I have developed a script that accomplishes what I need.  It removes just enough information to force re-population without getting rid of the things that I care about.  I currently have it setup to run once per week, which should be more than sufficient for my needs.

The script is in PowerShell, but shouldn’t be overly difficult to rewrite in just about anything.  A couple notes:

a) I am not worried about refreshing pictures here.  Though that can be accomplished pretty easily by deleting the thumbnail cache.

b) Use at your own risk.  I am not 100% certain that this is stable in all circumstances.  I’ve run it a bunch on my setup, but make no guarantees what it will do to yours.

c) I’m pretty sure its inefficient, I am not a programmer by nature.  If you find methods to improve it, please do so and post your results back here.

# You should be able to edit here and the rest of the script should work
# With the very important exception of the section marked !!!!LOOK AT ME!!!! below.
$xbmcuserid = "user"
$xbmcpassword = "pass"
$xbmcIP = "192.168.1.2"
$xbmcPort = "8000"
$mySQLIP = "192.168.1.2"
$url = "http://" + $xbmcIP + ":" + $xbmcPort + "/jsonrpc"
$xbmcDB = "xbmc_video"

# Connect to the mySQL database
[void][System.Reflection.Assembly]::LoadWithPartialName("MySql.Data")
$XBMCConnection = New-Object MySql.Data.MySqlClient.MySqlConnection
$XBMCConnection.ConnectionString = "database=" + $xbmcDB + ";server=" + $mySQLIP + ";Persist Security Info=false;user id=" + $xbmcuserid + ";pwd=" + $xbmcpassword
$XBMCConnection.Open()

# Make a copy of the movie table
$copyCommand = $XBMCConnection.CreateCommand()
$copyCommand.CommandText = "CREATE TABLE movie_copy SELECT * FROM movie"
$copyCommand.ExecuteNonQuery()

# Clean out the movie table
$cleanCommand = $XBMCConnection.CreateCommand()
$cleanCommand.CommandText = "DELETE FROM movie WHERE idMovie > 0"
$cleanCommand.ExecuteNonQuery()

# !!!!!!!!!!!!!!LOOK AT ME!!!!!!!!!!!!!!
# You are going to need to clean out the hashes associated with the movies or the scan will just skip past everything
# You can clear out all of the hashes (movies and TVs) but that will cause everything to rescan
# I prefer to just scan the stuff that I care about YMMV
# !!!!!!!!!!!!!!LOOK AT ME!!!!!!!!!!!!!!
$cleanHashCommand = $XBMCConnection.CreateCommand()
$cleanHashCommand.CommandText = "UPDATE path` SET `strHash` = '0' WHERE strPath like '%Movies/%';"
$cleanHashCommand.ExecuteNonQuery()

# Ask XBMC to look for new videos - this will reload the NFOs into the database
$command = '{"jsonrpc": "2.0", "method": "VideoLibrary.Scan", "id": 1}'
$bytes = [System.Text.Encoding]::ASCII.GetBytes($command)
$web = [System.Net.WebRequest]::Create($url)
$web.Method = "POST"
$web.ContentLength = $bytes.Length
$web.ContentType = "application/x-www-form-urlencoded"
$stream = $web.GetRequestStream()
$stream.Write($bytes,0,$bytes.Length)
$stream.close()
$reader = New-Object System.IO.Streamreader -ArgumentList $web.GetResponse().GetResponseStream()
$reader.ReadToEnd()
$reader.Close()

# Wait for 30 minutes, this is probably me being lazy. 
# I can't think of a way to see if the scanning has been completed or not
start-sleep -s 1800

# Reset the movie ids back to what they were. 
# This is required if you a) care about Recent Movies being accurate.  b) you use sets c) probably something else too
$ResetIDCommand = $XBMCConnection.CreateCommand()
$ResetIDCommand.CommandText = "UPDATE " + $xbmcDB + ".movie_copy t1, " + $xbmcDB + ".movie t2 SET t2.idMovie=t1.idMovie WHERE t1.idFile = t2.idFile"
$ResetIDCommand.ExecuteNonQuery()

# Drop the backed up table
$DropCommand = $XBMCConnection.CreateCommand()
$DropCommand.CommandText = "DROP TABLE " + $xbmcDB + ".movie_copy"
$DropCommand.ExecuteNonQuery()

# Clean the database
# Don't know if this is necessary, but it can't hurt, right?
$command = '{"jsonrpc": "2.0", "method": "VideoLibrary.Clean", "id": 1}'
$bytes = [System.Text.Encoding]::ASCII.GetBytes($command)
$web = [System.Net.WebRequest]::Create($url)
$web.Method = "POST"
$web.ContentLength = $bytes.Length
$web.ContentType = "application/x-www-form-urlencoded"
$stream = $web.GetRequestStream()
$stream.Write($bytes,0,$bytes.Length)
$stream.close()
$reader = New-Object System.IO.Streamreader -ArgumentList $web.GetResponse().GetResponseStream()
$reader.ReadToEnd()
$reader.Close()

Sunday, June 26, 2011

MDL: Backing Up to Flickr Part I

For better or worse I’ve decided that I would use flickr as my photo backup solution.  For one, it’s not terribly expensive – around $30 for unlimited storage – and it makes picture sharing pretty easy.  There are privacy concerns for some, but I’m simply not sure that I care.
The downside is that there aren’t really any tools out there that automate sending the pictures to flickr.  Foldr Monitr comes close, but its buggy, isn’t updated anymore and I just don’t like the choices that it has made. 
After about two years of complaining I guess I’ll just have to handle the problem myself.  Odds are that you won’t like the choices that I’ve made, but hopefully I’ve given you enough pieces that you can make the necessary modifications without having to start from scratch the way that I did.
You are going to need a database of some kind to keep track of everything – I have a copy of MySQL running already for XBMC so that’s what I’ll use.  I’m also going to use PowerShell since that is what I know which means that I’ll have to install the ODBC driver for MySQL.
Finally, I suck as a programmer.  Don’t use any of this code with the expectations that you’ll learn how to get better at scripting.  Also, don’t point out how if I changed some bit of code around it would be SOOO MUCH BETTER!   I don’t care – if my code functions for me, inefficient or not, I am quite content.
So be warned – this thing works for me and my needs 95% of the time.  And if I run across an anomaly where it doesn’t do what is expected if x & y are true – I stop doing  both x & y at the same time.  The chances that I’ll update the script to accommodate your special circumstances are pretty damn rare.  And adding any functionality at all is all but unthinkable.
All that being said, feel free to borrow the code and adapt it to your own purposes – you just can’t take this and put it into something that you are going to sell.  And if you update the scripts for public consumption – please give me my due by linking back here.  Obviously while noting how crappy the code is and how much work you had to put into it to make it semi-functional for a normal human being.
Part II will get into the script and perhaps the database – assuming that I actually finishing writing the god damned thing.

Update: I have completely abandoned this project.  Flickr is just too much of a pain in the ass.  I am almost completely migrated to CrashPlan for offsite backups of my pictures with the plus of being able to backup non-pictures as well.

Technorati Tags: ,,,

Saturday, May 08, 2010

MDL: Script to Convert MPG to AVIs

The MPG videos that I have are not getting along with XBMC.  To get around this I need to convert them all to AVI format.

avidemux has a great command utility and PowerShell has the power to batch the process.

$avidemux = New-Object System.Diagnostics.ProcessStartInfo
$avidemux.FileName = "D:\avimux\avidemux2_cli.exe"
$avidemux.windowStyle ="Hidden"

foreach
($SourceVideoFile in (Get-ChildItem @("D:\videos\") -recurse -include @("*mpg", "*.mpeg") | sort-object name))
{      
    $SourceVideoFile.fullname
    $avidemux.arguments = "--autoindex --load ""{0}"" --save ""{1}"" --output-format AVI --quit" -f $SourceVideoFile.fullname, ($SourceVideoFile.directoryname + "\" + $SourceVideoFile.basename +".avi")
    $avidemuxProcess = [System.Diagnostics.Process]::Start($avidemux)
    $avidemuxProcess.WaitForExit()
}

All done!  The videos all converted in a couple of hours.

Technorati Tags: ,,

Sunday, February 21, 2010

MDL: Home Theater Meet PowerShell

IntroPart IPart II

As I mentioned in the last post, getting video to my wide array of end points can be a little challenging.  You may have been surprised when I said that getting video on a Zune was a challenge.

Well, it’s not that it is hard per se – after all the Zune software will go discover all that media from any Windows share just like it does for music.  The problem is that it needs to transcode all of that media before it can copy it to the Zune.

The other issue is those large video files aren’t optimized for playing on such a small screen.  It all works, but waiting for an hour or more to copy a single movie to your Zune isn’t my idea of a good time.  And I’m not always prepared enough to do it ahead of time.

So my solution was to couple HandBrake – a fantastic program for converting video files – with PowerShell.  I had to teach myself PowerShell along the way, but in the end I have a powerful script that converts all of my video files to smaller formats optimized for the Zune.  The good news for you is that the exact same process will work for iPods or any device that can play video with a couple small tweaks.

Step one is to download Handbrake and the Handbrake CLI (command line interface).  Launch Handbrake and create a profile that will convert videos into a format that your portable device can play.

There are a couple of items in this script that will need to be modified for your particular situation.

  1. Your preset – on Line 4 I’ve called mine simply ‘Zune’, change this to whatever profile you created for your device.
  2. The location of the Handbrake CLI on Line 2.
  3. The location of your source videos – you can have as many as you want, just make sure that they are separated by a comma – Line 7.
  4. The destination for your converted movies – Line 9.
   1: $HandBrake = New-Object System.Diagnostics.ProcessStartInfo



   2: $HandBrake.FileName = "C:\Program Files\Handbrake\HandBrakeCLI.exe"



   3: $HandBrake.windowStyle ="Hidden"



   4: $HandBrakeOptions = " --preset='Zune' "



   5:  



   6: foreach 



   7: ($SourceVideoFile in (Get-ChildItem @("D:\movies\", "D:\TV\") -recurse -include @("*mpg", "*.mp4", "*.mkv", "*.avi", "*.mpeg") | sort-object name)) 



   8: {



   9:     $ZuneOutputFile = "D:\Zune\" + ($SourceVideoFile |% { [IO.Path]::GetFileNameWithoutExtension($_) }) + ".mp4"



  10:     if (!(test-path $ZuneOutputFile))



  11:     {



  12:         



  13:         $HandBrake.arguments = $HandBrakeOptions + "-i " + '"' + $SourceVideoFile.fullname + '"' + " -o " + '"' + $ZuneOutputFile +'"'



  14:         $HandBrakeProcess = [System.Diagnostics.Process]::Start($HandBrake) 



  15:         $HandBrakeProcess.WaitForExit() 



  16:     }



  17: }




In short, the script:




  1. Compiles a list of all video files in the locations specified (and, conveniently, all of the subfolders too).


  2. Checks to see if the file exists in the destination.


  3. If it doesn’t already exist it converts it based on the profile that you set up.



Some items of note:  the script hides all of the conversion process so that it can be scheduled without interrupting any other activity on the computer it is running on. 



It will also take forever to run the first time since it needs to convert all of that video.  But if you schedule it on a routine basis it shouldn’t take too long.



Pretty cool, huh?



Technorati Tags: ,