def SearchIsoHuntCategory(sender, query=None, category=99):
    dir = MediaContainer()
    url = "http://isohunt.com/js/rss"
    if query != None:
        url += "/%s" % query
    if category != 99:
        url += "?iht=%d" % category
    Log(url, True)
    feed = HTML.ElementFromURL(url, errors='ignore').xpath("//item")
    if feed == None:
        return MessageContainer("Error", "Search returned no results")
    if len(feed) == 0:
        return MessageContainer("Error", "No results").ToXML()
    for element in feed:
        title = element.xpath("title")[0].text
        category = element.xpath("category")[0].text
        link = element.find("enclosure").get("url")
        size = prettysize(int(element.find("enclosure").get("length")))
        dir.Append(
            Function(DirectoryItem(AddTorrent,
                                   title,
                                   subtitle=None,
                                   summary="Category: %s\nSize: %s" %
                                   (category, size),
                                   thumb=R(ICON),
                                   art=R(ART)),
                     torrentUrl=link))
    return dir
def SearchEZTV(sender, query=None):
  dir = MediaContainer()
  url = "http://ezrss.it/search/index.php?simple&mode=rss&show_name="
  if query != None:
    url += "%s" % query
  Log(url, True)
  feed = HTML.ElementFromURL(url, errors='ignore').xpath("//item")
  if feed == None:
    return MessageContainer("Error", "Search failed")
  if len(feed) == 0:
    return MessageContainer("Error", "No results")
  for element in feed:
    title = element.xpath("title")[0].text
    category = element.xpath("category")[0].text
    link = element.find("enclosure").get("url")
    size = prettysize(int(element.find("enclosure").get("length")))
    dir.Append(Function(DirectoryItem(AddTorrent,title,subtitle=None,summary="Category: %s\nSize: %s" % (category,size),thumb=R(ICON),art=R(ART)),torrentUrl=link))
  return dir

# This is currently unused due to issues between PIL and Framework v1
# re-enable it later if PIL gets included in the framework by sticking this at the top:
# from icon      import TorrentIconCached
# and the rest in a file called icon.py:
# from PMS import *
# from PMS.Objects import *
# from PMS.Shortcuts import *
# from PIL import Image, ImageFont, ImageDraw
# import cStringIO
#
# LargeFont	= ImageFont.truetype("/Library/Fonts/Arial Bold.ttf", 100)
# SmallFont	= ImageFont.truetype("/Library/Fonts/Arial Bold.ttf", 30)
#
# def TorrentIcon(name, status, progress=100):
# 	result	= cStringIO.StringIO()
# 	image	= Image.new("RGBA", (304, 450), (0, 0, 0, 0))
# 	draw	= ImageDraw.Draw(image)
#
#  	Log("name: %s, status: %s" % (name, status), True)
# 	draw.text((1, 1), status, font=LargeFont, fill="black")
# 	draw.text((0, 0),	status,	font=LargeFont, fill="white")
# 	draw.text((1, 131),	name,	font=SmallFont, fill="black")
# 	draw.text((0, 130),	name,	font=SmallFont, fill="white")
#
# 	if progress >= 0:
# 		draw.rectangle( ( 0, 170, 3 * progress, 200 ), fill="white", outline="black")
# 		draw.rectangle( ( 3 * progress,	170, 300, 200 ), fill="#444", outline="black")
#
# 	image.save(result, "PNG")
# 	imagedata=result.getvalue()
# 	return DataObject(data = result.getvalue(), contentType="image/png")
#
# def TorrentIconCached(name, status, progress=100):
# 	# TorrentIconCached(torrent["name"],"%d%%" % progress,progress)
# 	if Data.Exists("%s.png" % progress):
# 		return DataObject(data = Data.Load("%s.png" % progress), contentType="image/png")
# 	else:
# 		return TorrentIcon(name, status, progress)
def ViewFiles(sender, hash):
  # Display the contents of a torrent
  # #################################
  # Log("Need details for: %s" % hash, True)

  error, result = RTC("torrent-get",
      { "ids": [ hash ], "fields": [ "hashString", "files", "wanted" ] })

  if error != None:
    return MessageContainer(
      "Transmission error",
      "Unable to list files."
    )

  dir = MediaContainer()
  for torrent in result["torrents"]:
    if torrent["hashString"] != hash:
      continue

    for i in range(0, len(torrent["files"])):
      f = torrent["files"][i]

      Log("Name: %s" % (f["name"]), True)

      if torrent["wanted"][i] == 1:
        if f["bytesCompleted"] == f["length"]:
          summary = "Complete"
        else:
          # Display progress "12.3 MB of 45.6 GB (0%)"
          summary = "%s of %s (%s%%)\n" % (
              prettysize(f["bytesCompleted"]),
              prettysize(f["length"]),
              (f["bytesCompleted"]) / (f["length"] / 100)
          )
      else:
        summary = "Not Downloading"

      dir.Append(PopupDirectoryItem("%d" % i, f["name"], summary=summary))

    return dir
def ViewFiles(sender, hash):
    # Display the contents of a torrent
    # #################################
    # Log("Need details for: %s" % hash, True)

    error, result = RTC("torrent-get", {
        "ids": [hash],
        "fields": ["hashString", "files", "wanted"]
    })

    if error != None:
        return MessageContainer("Transmission error", "Unable to list files.")

    dir = MediaContainer()
    for torrent in result["torrents"]:
        if torrent["hashString"] != hash:
            continue

        for i in range(0, len(torrent["files"])):
            f = torrent["files"][i]

            Log("Name: %s" % (f["name"]), True)

            if torrent["wanted"][i] == 1:
                if f["bytesCompleted"] == f["length"]:
                    summary = "Complete"
                else:
                    # Display progress "12.3 MB of 45.6 GB (0%)"
                    summary = "%s of %s (%s%%)\n" % (prettysize(
                        f["bytesCompleted"]), prettysize(f["length"]),
                                                     (f["bytesCompleted"]) /
                                                     (f["length"] / 100))
            else:
                summary = "Not Downloading"

            dir.Append(PopupDirectoryItem("%d" % i, f["name"],
                                          summary=summary))

        return dir
def SearchEZTV(sender, query=None):
  dir = MediaContainer(viewGroup="List")
  url = "http://ezrss.it/search/index.php?simple&mode=rss&show_name="
  if query != None:
    url += "%s" % query
  Log(url, True)
  feed = HTML.ElementFromURL(url, errors='ignore').xpath("//item")
  if feed == None:
    return MessageContainer("Error", "Search failed")
  if len(feed) == 0:
    return MessageContainer("Error", "No results")
  for element in feed:
    title = element.xpath("title")[0].text
    category = element.xpath("category")[0].text
    link = element.find("enclosure").get("url")
    size = prettysize(int(element.find("enclosure").get("length")))
    dir.Append(Function(DirectoryItem(AddTorrent,title,subtitle=None,summary="Category: %s\nSize: %s" % (category,size),thumb=R(ICON),art=R(ART)),torrentUrl=link))
  return dir
def SearchIsoHuntCategory(sender, query=None, category=99):
  dir = MediaContainer()
  url = "http://isohunt.com/js/rss"
  if query != None:
    url += "/%s" % query
  if category != 99:
    url += "?iht=%d" % category
  Log(url, True)
  feed = HTML.ElementFromURL(url, errors='ignore').xpath("//item")
  if feed == None:
    return MessageContainer("Error", "Search returned no results")
  if len(feed) == 0:
    return MessageContainer("Error", "No results").ToXML()
  for element in feed:
    title = element.xpath("title")[0].text
    category = element.xpath("category")[0].text
    link = element.find("enclosure").get("url")
    size = prettysize(int(element.find("enclosure").get("length")))
    dir.Append(Function(DirectoryItem(AddTorrent,title,subtitle=None,summary="Category: %s\nSize: %s" % (category,size),thumb=R(ICON),art=R(ART)),torrentUrl=link))
  return dir
def TorrentList(sender):
  error, result  = RTC("torrent-get",
    { "fields": [
      "hashString","name","status",
      "eta","errorString",
      "totalSize","leftUntilDone","sizeWhenDone",
      "peersGettingFromUs",  "peersSendingToUs",  "peersConnected",
      "rateDownload",      "rateUpload",
      "downloadedEver",    "uploadedEver"
    ] }
  )
  if error != None:
    if error != "Connection refused":
      return MessageContainer(
          "Transmission unavailable",
          "There was an unknown error."
      )
    else:
      return MessageContainer(
          "Transmission unavailable",
          "Please make sure Transmission is running with Remote access enabled.  For more information please see http://wiki.plexapp.com/index.php/Transmission"
      )
  elif result["torrents"] != None:
    dir = MediaContainer()
    progress    = 100;
    for torrent in result["torrents"]:
      summary = ""

      if torrent["errorString"]:
        summary += "Error: %s\n" % (torrent["errorString"])

      if torrent["leftUntilDone"] > 0 and torrent["status"] != TRANSMISSION_SEEDING:
        # Display progress "12.3 MB of 45.6 GB (0%)"
        progress = ((torrent["sizeWhenDone"] - torrent["leftUntilDone"]) /
              (torrent["sizeWhenDone"] / 100))

        summary += "%s of %s (%d%%)\n" % (
            prettysize(torrent["sizeWhenDone"] - torrent["leftUntilDone"]),
            prettysize(torrent["sizeWhenDone"]), progress
          )

        # Display an ETA; "3 days remaining"
        if torrent["eta"] > 0 and torrent["status"] != TRANSMISSION_PAUSED:
          summary += prettyduration(torrent["eta"]) + " remaining\n"
        else:
          summary += "Remaining time unknown\n"

        if torrent["status"] == TRANSMISSION_DOWNLOADING:
          # Display download status "Downloading from 3 of 6 peers"
          summary += "Downloading from %d of %d peers\n" % (
              torrent["peersSendingToUs"],
              torrent["peersConnected"]
            )

          # Display download and upload rates
          summary += "Downloading at %s/s\nUploading at %s/s\n" % (
          prettysize(torrent["rateDownload"]),
          prettysize(torrent["rateUpload"])
            )
        else:
          # Display torrent status
          summary += TorrentStatus(torrent)
      else:
        if torrent["status"] == TRANSMISSION_SEEDING:
          summary += "Complete\n"
          progress=100
        # else:
        #   Log("torrent status is: %d" % torrent["status"], True)

        if torrent["downloadedEver"] == 0:
          torrent["downloadedEver"] = 1

        summary += "%s, uploaded %s (Ratio %.2f)\n" % (
            prettysize(torrent["totalSize"]),
            prettysize(torrent["uploadedEver"]),
            float(torrent["uploadedEver"]) / float(torrent["downloadedEver"])
          )

        if torrent["status"] == TRANSMISSION_SEEDING:
          summary += "Seeding to %d of %d peers\n" % (
              torrent["peersGettingFromUs"],
              torrent["peersConnected"]
            )
          summary += "Uploading at %s/s\n" % (
              prettysize(torrent["rateUpload"])
            )
      # This is so that we don't bloat the plugin with 101 images.
      # It might change later if PIL is included into the framework
      nearest = int(round(progress/10)*10)

      # The summary has been built, add the item:
      dir.Append(
          Function(
              PopupDirectoryItem(
                  TorrentInfo,
                  torrent["name"],
                  summary=summary,
                  thumb=R("%s.png" % nearest)
              ),
              name = torrent["name"],
              status = torrent["status"],
              hash = torrent["hashString"]
              )
          )

    # Add "Pause all torrents" menu item
    dir.Append(Function(DirectoryItem(PauseTorrent,L('MenuPauseAll'),subtitle=None,summary=None,thumb=R(PAUSE),art=R(ART)), hash='all'))

    # Add "Resume all torrents" menu item
    dir.Append(Function(DirectoryItem(ResumeTorrent,L('MenuResumeAll'),subtitle=None,summary=None,thumb=R(RESUME),art=R(ART)), hash='all'))

    return dir
def SearchEZTV(sender, query=None):
    dir = MediaContainer()
    url = "http://ezrss.it/search/index.php?simple&mode=rss&show_name="
    if query != None:
        url += "%s" % query
    Log(url, True)
    feed = HTML.ElementFromURL(url, errors='ignore').xpath("//item")
    if feed == None:
        return MessageContainer("Error", "Search failed")
    if len(feed) == 0:
        return MessageContainer("Error", "No results")
    for element in feed:
        title = element.xpath("title")[0].text
        category = element.xpath("category")[0].text
        link = element.find("enclosure").get("url")
        size = prettysize(int(element.find("enclosure").get("length")))
        dir.Append(
            Function(DirectoryItem(AddTorrent,
                                   title,
                                   subtitle=None,
                                   summary="Category: %s\nSize: %s" %
                                   (category, size),
                                   thumb=R(ICON),
                                   art=R(ART)),
                     torrentUrl=link))
    return dir


# This is currently unused due to issues between PIL and Framework v1
# re-enable it later if PIL gets included in the framework by sticking this at the top:
# from icon      import TorrentIconCached
# and the rest in a file called icon.py:
# from PMS import *
# from PMS.Objects import *
# from PMS.Shortcuts import *
# from PIL import Image, ImageFont, ImageDraw
# import cStringIO
#
# LargeFont	= ImageFont.truetype("/Library/Fonts/Arial Bold.ttf", 100)
# SmallFont	= ImageFont.truetype("/Library/Fonts/Arial Bold.ttf", 30)
#
# def TorrentIcon(name, status, progress=100):
# 	result	= cStringIO.StringIO()
# 	image	= Image.new("RGBA", (304, 450), (0, 0, 0, 0))
# 	draw	= ImageDraw.Draw(image)
#
#  	Log("name: %s, status: %s" % (name, status), True)
# 	draw.text((1, 1), status, font=LargeFont, fill="black")
# 	draw.text((0, 0),	status,	font=LargeFont, fill="white")
# 	draw.text((1, 131),	name,	font=SmallFont, fill="black")
# 	draw.text((0, 130),	name,	font=SmallFont, fill="white")
#
# 	if progress >= 0:
# 		draw.rectangle( ( 0, 170, 3 * progress, 200 ), fill="white", outline="black")
# 		draw.rectangle( ( 3 * progress,	170, 300, 200 ), fill="#444", outline="black")
#
# 	image.save(result, "PNG")
# 	imagedata=result.getvalue()
# 	return DataObject(data = result.getvalue(), contentType="image/png")
#
# def TorrentIconCached(name, status, progress=100):
# 	# TorrentIconCached(torrent["name"],"%d%%" % progress,progress)
# 	if Data.Exists("%s.png" % progress):
# 		return DataObject(data = Data.Load("%s.png" % progress), contentType="image/png")
# 	else:
# 		return TorrentIcon(name, status, progress)
def TorrentList(sender):
    error, result = RTC(
        "torrent-get", {
            "fields": [
                "hashString", "name", "status", "eta", "errorString",
                "totalSize", "leftUntilDone", "sizeWhenDone",
                "peersGettingFromUs", "peersSendingToUs", "peersConnected",
                "rateDownload", "rateUpload", "downloadedEver", "uploadedEver"
            ]
        })
    if error != None:
        if error != "Connection refused":
            return MessageContainer("Transmission unavailable",
                                    "There was an unknown error.")
        else:
            return MessageContainer(
                "Transmission unavailable",
                "Please make sure Transmission is running with Remote access enabled.  For more information please see http://wiki.plexapp.com/index.php/Transmission"
            )
    elif result["torrents"] != None:
        dir = MediaContainer()
        progress = 100
        for torrent in result["torrents"]:
            summary = ""

            if torrent["errorString"]:
                summary += "Error: %s\n" % (torrent["errorString"])

            if torrent["leftUntilDone"] > 0 and torrent[
                    "status"] != TRANSMISSION_SEEDING:
                # Display progress "12.3 MB of 45.6 GB (0%)"
                progress = (
                    (torrent["sizeWhenDone"] - torrent["leftUntilDone"]) /
                    (torrent["sizeWhenDone"] / 100))

                summary += "%s of %s (%d%%)\n" % (
                    prettysize(torrent["sizeWhenDone"] -
                               torrent["leftUntilDone"]),
                    prettysize(torrent["sizeWhenDone"]), progress)

                # Display an ETA; "3 days remaining"
                if torrent["eta"] > 0 and torrent[
                        "status"] != TRANSMISSION_PAUSED:
                    summary += prettyduration(torrent["eta"]) + " remaining\n"
                else:
                    summary += "Remaining time unknown\n"

                if torrent["status"] == TRANSMISSION_DOWNLOADING:
                    # Display download status "Downloading from 3 of 6 peers"
                    summary += "Downloading from %d of %d peers\n" % (
                        torrent["peersSendingToUs"], torrent["peersConnected"])

                    # Display download and upload rates
                    summary += "Downloading at %s/s\nUploading at %s/s\n" % (
                        prettysize(torrent["rateDownload"]),
                        prettysize(torrent["rateUpload"]))
                else:
                    # Display torrent status
                    summary += TorrentStatus(torrent)
            else:
                if torrent["status"] == TRANSMISSION_SEEDING:
                    summary += "Complete\n"
                    progress = 100
                # else:
                #   Log("torrent status is: %d" % torrent["status"], True)

                if torrent["downloadedEver"] == 0:
                    torrent["downloadedEver"] = 1

                summary += "%s, uploaded %s (Ratio %.2f)\n" % (
                    prettysize(torrent["totalSize"]),
                    prettysize(torrent["uploadedEver"]),
                    float(torrent["uploadedEver"]) /
                    float(torrent["downloadedEver"]))

                if torrent["status"] == TRANSMISSION_SEEDING:
                    summary += "Seeding to %d of %d peers\n" % (
                        torrent["peersGettingFromUs"],
                        torrent["peersConnected"])
                    summary += "Uploading at %s/s\n" % (prettysize(
                        torrent["rateUpload"]))
            # This is so that we don't bloat the plugin with 101 images.
            # It might change later if PIL is included into the framework
            nearest = int(round(progress / 10) * 10)

            # The summary has been built, add the item:
            dir.Append(
                Function(PopupDirectoryItem(TorrentInfo,
                                            torrent["name"],
                                            summary=summary,
                                            thumb=R("%s.png" % nearest)),
                         name=torrent["name"],
                         status=torrent["status"],
                         hash=torrent["hashString"]))

        # Add "Pause all torrents" menu item
        dir.Append(
            Function(DirectoryItem(PauseTorrent,
                                   L('MenuPauseAll'),
                                   subtitle=None,
                                   summary=None,
                                   thumb=R(PAUSE),
                                   art=R(ART)),
                     hash='all'))

        # Add "Resume all torrents" menu item
        dir.Append(
            Function(DirectoryItem(ResumeTorrent,
                                   L('MenuResumeAll'),
                                   subtitle=None,
                                   summary=None,
                                   thumb=R(RESUME),
                                   art=R(ART)),
                     hash='all'))

        return dir