thingsinjars

  • 16 Sep 2010

    Writing a Plex Plugin Part I

    In my awesome home cinema setup (about which I'll need to blog sometime), I use many pieces of inter-connected software and hardware. The hub, though, is the OS X computer in the middle running the Plex Media Server and the Transmission BitTorrent client. This post describes the plugin which ties them together.

    I've just released version 1.0 of the Transmission plugin for the Plex Media Server. As with all good software projects, there were actually many releases before 1.0 but I thought this was the right time to write up a walk-through of what the code looks like and does. I didn't write the initial version of the plugin but I've maintained it since v0.7 and now pretty much rewritten everything a couple of times. I'll post my walkthrough in a few installments because it's quite long.

    The code as it currently stands (v1.0) is available for download below but within a few days you should also be able to download it within 'Plex Online'

    Transmission Plugin for Plex Media Server v1.0

    As Michael A. pointed out in the comments, I haven't actually mentioned anywhere below what it is that the plugin does. For a quick overview, check out the Plex wiki Transmission page.

    This plugin is built to be compatible with Plex Plugin Framework v1 which initially looked like quite a major change from the previous version of the framework but isn't really that different. For Plex plugins, every time an action is performed, the system generates a URL and passes it down through its own menu structure until it gets to a plugin that handles that URL. The plugin then deals with the info in the URL however it likes. In the previous versions of this plugin, the URL was parsed manually and split into strings separated by '/'

    For example the URL:

    /video/transmission/id/status/action/

    would first cause Plex to look in its 'video' menu item and find the plugin that said it could handle 'transmission' URLs. The plugin would take the rest of the string and separate it out. First contact the Transmission application, ask for all information about the torrent called 'id', check its 'status' and then perform the 'action' if possible.

    The new plugin does pretty much the same except I no longer manually parse the URL. The plugin still registers with Plex to say it can handle URLs starting '/video/transmission' but then it passes functions through instead of URL-catching menu items. If you're familiar with JavaScript, it's like passing an anonymous function to handle something instead of catching the event manually.

    Anyway, here's the python code with a running commentary:

    Imports

    First we import the Plex Media Server framework:

    from PMS import *
    from PMS.Objects import *
    from PMS.Shortcuts import *

    These are a couple of handy functions from the very first version of the plugin which make the outputs much more readable.

    from texttime  import prettyduration
    from textbytes  import prettysize

    This next line actually causes Plex to issue a warning. These libraries won't all be available in the next version of the framework. Instead of urllib and urllib2, developers are to use the built-in HTTP module. Unfortunately, HTTP doesn't allow access to the headers of responses and the Transmission authentication system relies on exchanging a session ID via headers.

    import urllib,urllib2,base64

    Declarations

    Set up some constants to save typing later on

    PLUGIN_PREFIX = "/video/transmission"
    PLUGIN_TITLE = "Transmission"

    This is the first call to the Localisation module. Plex plugins allow for complete string localisation via a JSON file (I've only included English in this version because my torrent-related German and Japanese are poor). This will look in the JSON file for the key 'Title' and return whatever value is associated with it (or 'Title' if there is none).

    NAME = L('Title')

    More shorthand

    ART        = 'art-default.jpg'
    ICON      = 'icon-default.png'
    SETTINGS  = 'settings-hi.png'
    PAUSE      = 'pause-hi.png'
    RESUME    = 'resume-hi.png'
    SEARCH    = 'search-hi.png'
    TV        = 'tv-hi.png'
    
    TRANSMISSION_WAITING      = 1
    TRANSMISSION_CHECKING      = 2
    TRANSMISSION_DOWNLOADING  = 4
    TRANSMISSION_SEEDING      = 8
    TRANSMISSION_PAUSED        = 16

    Definitions

    Required

    Here is where we start the plugin code. This is one of the standard functions which gets called when the plugin is initialised.

    def Start():

    Tell Plex we can handle '/video/transmission' URLs and that our main function is called 'MainMenu'

      Plugin.AddPrefixHandler(
        PLUGIN_PREFIX, 
        MainMenu, 
        PLUGIN_TITLE, 
        ICON, 
        ART)
    
      MediaContainer.art = R(ART)
      MediaContainer.title1 = NAME
      DirectoryItem.thumb = R(ICON)

    Another standard function, this handles the preferences. To connect to Transmission, you need the URL and port it is running on (127.0.0.1:9091 if it's on the same machine as the Plex Media Server) and the username and password if you have set them.

    def CreatePrefs():
        Prefs.Add(id='hostname', type='text', default='127.0.0.1:9091', label='Hostname')
        Prefs.Add(id='username', type='text', default='', label='Username')
        Prefs.Add(id='password', type='text', default='', label='Password', option='hidden')

    This is called immediately after the preferences dialog is submitted. This is the most basic checking you can do but it could include a call to Transmission to verify the info provided.

    def ValidatePrefs():
        u = Prefs.Get('username')
        p = Prefs.Get('password')
        h = Prefs.Get('hostname')
        if( h ):
            return MessageContainer(
                "Success",
                "Info provided is ok"
            )
        else:
            return MessageContainer(
                "Error",
                "You need to provide url, username, and password"
            )

    You'll notice the return here is a MessageContainer. That's Plex's version of an alert. It doesn't generate a new page, just pops up a little window.

    Custom

    That was the end of the predefined functions, the plugin proper starts here. As Transmission requires a username, password and a short-lived session ID (since Transmission v1.53) to perform actions, we define a function which will attempt to make a connection with just username & password. Transmission will then send back a 409 Conflict response to basically say "Urk, that's not quite right. If you want to talk to me, you'll need this:" and give us our session ID in a header.

    def GetSession():
      h = Prefs.Get('hostname')
      u = Prefs.Get('username')
      p = Prefs.Get('password')
      url = "http://%s/transmission/rpc/" % h
      request = { "method" : "session-get" }
      headers = {}
      if( u and p and h):
        headers["Authorization"] = "Basic %s" % 
          (base64.encodestring("%s:%s" % (u, p))[:-1])
        try:
          body = urllib2.urlopen(
            urllib2.Request(
              url, 
              JSON.StringFromObject(request), 
              headers
            )
          ).read()
        except urllib2.HTTPError, e:
          if e.code == 401 or e.code == 403:
            return L('ErrorInvalidUsername'), {}
          return e.hdrs['X-Transmission-Session-Id']
        except:
          return L('ErrorNotRunning'), {}

    Once the HTTP module allows access to returned headers, we will be able to use something like this to set global authorisation once and forget about it:

    response = HTTP.Request(
        url, 
        { "method" : "session-get" }, 
        headers={}, 
        cacheTime=None
        )
    HTTP.SetPassword(h,u,p)
    HTTP.SetHeader(
      'X-Transmission-Session-Id', 
      response.headers['X-Transmission-Session-Id']
      )

    Remote Transmission Calls

    This uses the RPC API of Transmission to do everything we need. We pass into the function 'What we want to do' and 'Who we want it done to' basically.

    def RTC(method, arguments = {}, headers = {}):
      h = Prefs.Get('hostname')
      u = Prefs.Get('username')
      p = Prefs.Get('password')
      url = "http://%s/transmission/rpc/" % h
    
      session_id = GetSession()
    
      request = {
        "method":    method,
        "arguments":  arguments
      }

    Setup authentication here because, even though we've already gotten the session ID, it's useless if we don't actually use it.

      if( u and p ):
        headers["Authorization"] = "Basic %s" %
          (base64.encodestring("%s:%s" % (u, p))[:-1])
    
      headers["X-Transmission-Session-Id"] = session_id

    Now that we've built our instruction, throw it at Transmission and see what comes back.

      try:
        body = urllib2.urlopen(
          urllib2.Request(
            url, 
            JSON.StringFromObject(request), 
            headers)
          ).read()
      except urllib2.HTTPError, e:
        if e.code == 401 or e.code == 403:
          return L('ErrorInvalidUsername'), {}
        return "Error reading response from Transmission", {}
      except urllib2.URLError, e:
        return e.reason[1], {}
    
      result = JSON.ObjectFromString(body)

    We don't do error handling here as we want this function to be as generic as possible so we send anything we receive straight back to the calling function.

      if result["result"] == "success":
        result["result"] = None
    
      if result["arguments"] == None:
        result["arguments"] = {}
    
      return result["result"], result["arguments"]

    Menus

    Right, we've got our helper methods set up, we're ready to make our first menu. This is the main one we mentioned earlier.

    def MainMenu():

    You can set your menu screen to be laid out as “List”, “InfoList”, “MediaPreview”, “Showcase”, “CoverFlow”, “PanelStream” or “WallStream”. I'm keeping it simple here. Also, there's an extra call to GetSession just to check everything's fine and wake the app up.

        dir = MediaContainer(viewGroup="List")
        GetSession()

    Pretty much all the menu items throughout the rest of this plugin are added using the same code which boils down to:

      dir.Append(
        Function(
          DirectoryItem(
            FunctionName,
            "Pretty Menu Item Name",
            subtitle="Short subtitle",
            summary="Longer menu item summary and description",
            thumb=R(ICON),
            art=R(ART)
          )
        )
      )

    Starting in the middle, this reads as:

    • Create a DirectoryItem.
    • When this item is selected, use the function FunctionName to handle it.
    • Display the text "Pretty Menu Item Name" for this item
    • Display the text "Short subtitle" underneath this item (or None)
    • Display the text "Longer menu item summary and description" for this item if required (or None)
    • Use the resource called ICON (mentioned above) as the icon for this item
    • Use the resource ART as the background
    • This is a Function menu item
    • Finally, Append this to the current menu

    The first two main menu items are built exactly like that:

      dir.Append(
        Function(
          DirectoryItem(
            TorrentList,
            "Torrents",
            subtitle=None,
            summary="View torrent progress and control your downloads.",
            thumb=R(ICON),
            art=R(ART)
          )
        )
      )
      dir.Append(
        Function(
          DirectoryItem(
            SearchTorrents,
              "Search for a torrent",
              subtitle=None,
              summary="Browse the TV shows directory or search for files to download.",
              thumb=R(SEARCH),
              art=R(ART)
            )
          )
        )

    This is a special 'Preferences' item that will call the Prefs functions defined at the top.

      dir.Append(
        PrefsItem(
          title="Preferences",
          subtitle="Set Transmission access details",
          summary="Make sure Transmission is running and 'Remote access' is enabled then enter the access details here.",
          thumb=R(SETTINGS)
        )
      )

    A quick note: the function 'R' here, much like the localisation one 'L' above is a built-in helper function. It handles resources such as images. If you're developing a plugin and can't understand why your icon images are caching so much, it might be because you're going through this function.

    Send the directory (or Menu) back to Plex

        return dir

    The rest of the code deals with torrent control and some clever built-in site scraping functionality which I'll cover later.

    Geek, Development

  • 20 Aug 2010

    licences.xml

    JavaScript libraries and CSS frameworks are very popular these days. With each library, plugin, extension and template, comes another licencing statement. For most of these licences (MIT, for instance), you must include the licence statement in order to be able to use the code. In many cases, you also have to provide the original source and your own modifications. While, for uncompiled technologies such as these, this is a trivial matter, both this requirement and that of including the licence are awkward to implement if you like to minify your code. The licence is usually kept in an uncompressed comment at the top of the library (the YUI compressor specifically takes this into account with comments marked /*! */ ) and, although anyone can read your modifications to whatever you've used, post-minification code is much harder to follow (cf. three of my last four blog posts) and is really not 'in the spirit' of sharing your code.

    I'd like to be able to bundle all the licences and sources together outside the production files. Somewhere the interested user would be able to look them up if they liked but not somewhere that would automatically be downloaded on a standard visit. To that end, I have looked around for an established standard for this and not found anything. If you know of one, please let me know. Until I do find a good standard, here's my suggestion – a simple XML file located at /licences.xml in the format outlined below. It contains details of the file the licence pertains to, the uncompressed source (optional), the title of the licence and a URL where the full licence text can be found (on opensource.org or creativecommons.org, for instance). It also includes a (probably superfluous) shortname for the licence. I might remove that bit. You can optionally include this meta in your HTML if you want an explicit link between your source and the licence file:

    <meta name="licences" value="/licences.xml" />

    I'm currently undecided as to whether to go with XML or JSON. They're fairly interchangeable (barring XML attributes) but JSON takes less space. Then again, there's not as much need to save space in this file. Anyone have any recommendations? The entire format is, of course, up for discussion. Have I forgotten anything? Have I included anything unnecessary? I'm going to start using this in my projects until someone points out some major legal problem with it, I think.

    XML

     
    <licences>
     <licence>
      <source>
       <url>
        /includes/script/jquery/1.4/jquery.min.js
       </url>
       <uncompressed>
        /includes/script/jquery/1.4/jquery.js
       </uncompressed>
      </source>
      <deed>
       <title>
       MIT License
       </title>
       <url>
        http://www.opensource.org/licenses/mit-license.php
       </url>
       <shortform>
       MIT
       </shortform>
      </deed>
     </licence>
     <licence>
      <source>
       <url>
        /includes/script/custom/0.1/custom.js
       </url>
       <uncompressed>
        /includes/script/custom/0.1/custom.min.js
       </uncompressed>
      </source>
      <deed>
       <title>
       Attribution Share Alike
       </title>
       <url>
        http://creativecommons.org/licenses/by-sa/3.0
       </url>
       <shortform>
       cc by-sa
       </shortform>
      </deed>
     </licence>
    </licences>
    

    JSON

     
    {
     licences:{
      {
       source:{
        url:'/includes/script/jquery/1.4/jquery.min.js',
        uncompressed:'/includes/script/jquery/1.4/jquery.js'
       },
       deed:{
        title:'MIT License',
        url:'http://www.opensource.org/licenses/mit-license.php',
        shortform:'MIT'
       }
      },
      {
       source:{
        url:'/includes/script/custom/0.1/custom.min.js',
        uncompressed:'/includes/script/custom/0.1/custom.js'
       },
       deed:{
        title:'Attribution Share Alike',
        url:'http://creativecommons.org/licenses/by-sa/3.0',
        shortform:'cc by-sa'
       }
      }
     }
    }
    

    Ideas, Geek, Opinion

  • 19 Aug 2010

    Maze 1k

    • Random perfect maze generation, solution and rendering in 1011 bytes

    Okay, this is the last one for a while. Really.

    Unlike my previous 1k JavaScript demos, I really had to struggle to get this one into the 1024 byte limit. I'd already done all the magnification and optimization techniques I knew of so I had to bring in some things which were new to me from qfox.nl and Ben Alman and a few other places. This, combined with some major code refactoring, brought it down from 1.5k to just under 1. In the process, all possible readability was lost so here's a quick run through what it does and why.

    First up, a bunch of declarations.

    These are the colours used to draw the maze. Note, I used the shortest possible way to write each colour (red instead of #F00, 99 instead of 100). The value stored in the maze array (mentioned later) refers not only to the type of block it is but also to the index of the colour in this array, saving some space.

    u = ["#eff", "red", "#122", "rgba(99,255,99,.1)", "#ff0"],

    This is used for the number of blocks wide and high the maze is, the number of pixels per block, the size of the canvas and the redraw interval. Thanks to Ben Alman for pointing out in his article how to best use a constant.

     c = 21,

    Here is the reference to the canvas. Mid-minification, I did have a bunch of function shortcuts here - r=Math.random, for instance - but I ended up refactoring them out of the code.

    m = document.body.children[0];

    For most of the time when working on this, the maze was wider than it was high because I thought that made a more interesting maze. When it came down to it, though, it was really a matter of bytesaving to drop the distinct values for width and height. After that, we grab the canvas context so we can actually draw stuff.

    m.width = m.height = c * c;
    h = m.getContext("2d");

    The drawing function

    The generation and solution algorithm is quite nice and all but without this to draw it on the screen, it's really just a mathematical curio. This takes a colour, x and y and draws a square.

    l = function (i, e, f) {
      h.fillStyle = i;
      h.fillRect(e * c, f * c, c, c)
    };

    Designing a perfect maze

    "You've got 1 minute to design a maze it takes 2 minutes to solve."
    - Cobb, Inception.

    Apologies for the unnecessary Inception quote. It's really not relevant.

    Algorithmically, this is a fairly standard perfect maze generator. It starts at one point and randomly picks a direction to walk in then it stops picks another random direction and repeats. If it can't move, it goes back to the last choice it made and picks a different direction, if there are no more directions, all blocks have been covered and we're done. In a perfect maze, there is a path (and only one path) between any two randomly chosen points so we can make the maze then denote the top left as the start and the bottom right as the end. This particular algorithm takes 2 steps in every direction instead of 1 so that we effectively carve out rooms and leave walls. You can take single steps but it's actually more of a hassle.

    For more on how this kind of maze-generation works, check out this article on Tile-based maze generation.

    Blank canvas

    This is a standard loop to create a blank maze full of walls with no corridors. The 2 represents the 'wall' block type and the colour #122. The only really odd thing about this is the code f-->0 which is not to be read 'as f tends to zero' but is instead 'decrement f by 1, is it greater than zero?'

    g = function () {
      v = [];  //our stack of moves taken so we can retrace our steps.
      for (i = [], e = c; e-- > 0;) {
        i[e] = [];
        for (f = c; f-- > 0;) i[e][f] = 2
      }

    By this point, we have a two-dimensional JavaScript array filled with 2s

    Putting things in

      f = e = 1;    // our starting point, top left.
      i[e][f] = 0; // us, the zippy yellow thing

    Carving out the walls

    This is our first proper abuse of the standard for-loop convention. You don't need to use the three-part structure for 'initialize variable; until variable reaches a different value; change value of variable'. It's 'do something before we start; keep going until this is false; do this after every repetition' so here we push our first move onto the stack then repeat the loop while there's still a move left on the stack.

      for (v.push([e, f]); v.length;) {

    P here is the list of potential moves from our current position. For every block, we have a look to see what neighbours are available then concatenate that cardinal direction onto the strong of potential moves. This was originally done with bitwise flags (the proper way) but it ended up longer. It's also a bit of a nasty hack to set p to be 0 instead of "" but, again, it's all about the bytes.

      p = 0;

    Can we walk this way?

    These are all basically the same and mean 'if we aren't at the edge of the board and we're looking at a wall, we can tunnel into it.'.

     if (e < 18 && i[e + 2][f] == 2) p += "S"
     if (e >= 2 && i[e - 2][f] == 2) p += "N";
     if (f >= 2 && i[e][f - 2] == 2) p += "W";
     if (i[e][f + 2] == 2) p += "E";
    
     if (p) { //    If we've found at least one move
      switch (p[~~ (Math.random() * p.length)]) { // randomly pick one

    If there was anything to note from that last chunk, it would be that the operator ~~ can be used to floor the current value. It will return the integer below thye current value.

    Take two steps

    This is a nice little hack. Because we're moving two spaces, we need to set the block we're on and the next one to be 0 (empty). This takes advantage of the right-associative unary operator 'decrement before' and the right associativity of assignment operators. It subtracts 1 from e (to place us on the square immediately above) then sets that to equal 0 then subtracts 1 from the new e (to put us on the next square up again) and sets that to equal the same as the previous operation, i.e. 0.

      case "N":
          i[--e][f] = i[--e][f] = 0;
          break;

    Do the same for s, w and e

        case "S":
          i[++e][f] = i[++e][f] = 0;
          break;
        case "W":
          i[e][--f] = i[e][--f] = 0;
          break;
        case "E":
          i[e][++f] = i[e][++f] = 0
        }

    Whichever move we chose, stick that onto the stack.

        v.push([e, f])

    If there were no possible moves, backtrack

      } else {
        b = v.pop(); //take the top move off the stack
        e = b[0]; // move there
        f = b[1]
      }
     }

    End at the end

    At the very end, set the bottom right block to be the goal then return the completed maze.

      i[19][19] = 1;
      return i
    };

    Solver

    This is the solving function. Initially, it used the same algorithm as the generation function, namely 'collect the possible moves, randomly choose one' but this took too much space. So instead it looks for spaces north, then south, then west, then east. It follows the first one it finds.

    s = function () {

    Set the block type of the previous block as 'visited' (rgba(99,255,99,.1) the alpha value makes the yellow fade to green).

      n[o][y] = 3;

    A bit of ternary background

    This next bit looks worse than it is. It's the ternary operator nested several times. The ternary operator is a shorthand way of writing:

    if ( statement A is true ) {
      Do Action 1
    } else {
      Do Action 2
    }

    In shorthand, this is written as:

    Statement A ? Action 1 : Action 2;

    In this, however, I've replace Action 2 with another ternary operator:

    Statement A ? Action 1 : ( Statement B ? Action 2 : Action 3 );

    And again, and again. Each time, it checks a direction, if it's empty, mark it as visited and push the move onto our stack.

    (n[o + 1][y] < 2) ?
      (n[++o][y] = 0, v.push([o, y])) :
        (n[o - 1][y] < 2) ?
          (n[--o][y] = 0, v.push([o, y])) :
            (n[o][y - 1] < 2) ?
              (n[o][--y] = 0, v.push([o, y])) :
                (n[o][y + 1] < 2) ?
                  (n[o][++y] = 0, v.push([o, y])) :

    If none of the neighbours are available, backtrack

                    (b = v.pop(), o = b[0], y = b[1]);

    Show where we are

    Finally, set our new current block to be yellow

      n[o][y] = 4;

    Are we there yet?

    If we are at the bottom right square, we've completed the maze

      if (o == 19 && y == 19) {
      n = g();    //Generate a new maze
      o = y = 1; //Move us back to the top right
      s()     //Solve again

    If we haven't completed the maze, call the solve function again to take the next step but delay it for 21 milliseconds so that it looks pretty and doesn't zip around the maze too fast.

      } else setTimeout(s, c);

    Paint it black. And green. And yellow.

    This is the code to render the maze. It starts at the top and works through the whole maze array calling the painting function with each block type (a.k.a. colour) and position.

        for (d in n) for (a in n[d]) l(u[n[d][a]], a, d)
      };

    Start

    This is the initial call to solve the maze. The function s doesn't take any arguments but by passing these in, they get called before s and save a byte that would have been used if they had been on a line themselves.

    s(n = g(), o = y = 1)

    Done

    This little demo isn't as visually appealing as the Art Maker 1k or as interactive as the Spinny Circles 1k but it is quite nice mathematically. There are now some astounding pieces of work in the JS1K demo competition, though. I do recommend spending a good hour playing about with them all. Don't, however, open a bunch of them in the background at the same time. Small code isn't necessarily memory-efficient and you could quite easily grind your computer to a standstill.

    Geek, Javascript, Development

  • 12 Aug 2010

    Art Maker 1K

    Even though the rules for js1k only let me make one submission, I couldn't stop myself making another. This one is inspired by those pseudo-romantic pictures that you get all over tumblr that get reblogged endlessly (actually, it was inspired by the blog That Isn't Art by someone with the same opinion as myself).

    It randomly creates a sentence, adds some softly-moving almost bokeh coloured-circles and look, I made an art! Wait for the sentence to change or click (or touch) to change it yourself.

    Art Maker 1k

    And of course, don't forget the original spinny-circles 1k

    Geek, Javascript, Development, Design

  • newer posts
  • older posts

Categories

Toys, Guides, Opinion, Geek, Non-geek, Development, Design, CSS, JS, Open-source Ideas, Cartoons, Photos

Shop

Colourful clothes for colourful kids

I'm currently reading

Projects

  • Awsm Street – Kid's clothing
  • Stickture
  • Explanating
  • Open Source Snacks
  • My life in sans-serif
  • My life in monospace
Simon Madine (thingsinjars)

@thingsinjars.com

Hi, I’m Simon Madine and I make music, write books and code.

I’m the Engineering Lead for komment.

© 2025 Simon Madine