def play(self, videoId):
        api = NetworkTenVideo()
        media = api.get_media_for_video(videoId)
        self.log.debug("Found media renditions for video: %s", repr(media.items))
        if len(media.items):
            # Blindly go for the highest bitrate for now.
            # Later versions could include a customisable setting of which stream to use
            media_sorted = sorted(media.items, key=lambda m: m.encodingRate, reverse=True)
            media = media_sorted[0]
            path = media.defaultURL
            self.log.info("Using rendition: %s with url: %s" % (media, path))
        else:
            # Fallback to API FLVFullLength (e.g. for live streams)
            media = api.get_fallback_media_for_video(videoId)
            path = media.remoteUrl
            self.log.info("Using fallback rendition: %s with url: %s" % (media, path))

        if path.startswith("rtmp"):
            path = path.replace("&mp4:", " playpath=mp4:")
            path += " swfVfy=true swfUrl=%s pageUrl=%s" % (SWF_URL, PAGE_URL)

        # Set the resolved url, and include media stream info
        item = ListItem.from_dict(path=path)
        item.add_stream_info(
            "video", {"codec": media.videoCodec, "width": media.frameWidth, "height": media.frameHeight}
        )
        self.plugin.set_resolved_url(path)
  def play(self, videoId):
    api = NetworkTenVideo()
    media = api.get_media_for_video(videoId)
    self.log.debug('Found media renditions for video: %s', repr(media))
    if len(media):
        # Blindly go for the highest bitrate for now.
        # Later versions could include a customisable setting of which stream to use
        media_sorted = sorted(media, key=lambda m: m.encodingRate, reverse=True)
        media = media_sorted[0]
        path = media.url
        self.log.info('Using rendition: %s with url: %s' % (media, path))
    else:
        # Fallback to API FLVFullLength (e.g. for live streams)
        media = api.get_fallback_media_for_video(videoId)
        if media.remoteUrl:
          path = media.remoteUrl
          self.log.info('Using fallback rendition: %s with url: %s' % (media, path))
        else:
          # attempt to deal with DRM'd content by falling back to mobile HLS stream
          path = "http://c.brightcove.com/services/mobile/streaming/index/master.m3u8?videoId=%s" % videoId
          self.log.info('Using fallback rendition unavailable - falling back to mobile HLS stream: %s' % path)

    if path.startswith('rtmp'):
      path = path.replace('&mp4:', ' playpath=mp4:')
      path += ' swfVfy=true swfUrl=%s pageUrl=%s' % (SWF_URL, PAGE_URL)

    # Set the resolved url, and include media stream info
    item = ListItem.from_dict(path=path)
    item.add_stream_info('video', {'codec': media.videoCodec, 'width': media.frameWidth, 'height': media.frameHeight})
    self.plugin.set_resolved_url(path)
  def videolist(self, query, page='0'):
    api = NetworkTenVideo(self.plugin.cached(TTL=config.CACHE_TTL))
    if query == 'featured':
      homepage = api.get_homepage()
      videoIds = []
      for item in homepage:
        videoIds.append(item['brightcoveid'])
      videos = api.find_videos_by_ids(video_ids = videoIds)
    else:
      querystring = query
      query = urlparse.parse_qs(query)
      query['page_number'] = page
      videos = api.search_videos(**query)

    fanart_url = None
    if 'fanart' in self.request.args:
      fanart_url = self.request.args['fanart'][0]

    update_listing = False
    if 'update' in self.request.args and self.request.args['update'][0]:
      update_listing = True

    videoItems = []
    for video in videos.items:
      item = ListItem.from_dict(
        label=htmlparser.unescape(video.name),
        thumbnail=video.videoStillURL,
        is_playable=True,
        path=self.url_for('play.play', explicit=True, videoId=video.id)
      )
      item.set_info( "video", self.get_item_info(video))
      item.add_stream_info('video', {
        'codec': 'h264',
        'width': 944,
        'height': 528,
        'duration': float(video.length / 1000)
      })
      item.add_stream_info('audio', {
        'codec': 'aac',
        'language': 'en',
        'channels': 2
      })

      if fanart_url:
        item.set_property('fanart_image', fanart_url)
      videoItems.append(item)

    if videos.total_count > (videos.page_size * (int(page) + 1)):
      item = ListItem.from_dict(
        label='Next >>',
        path=self.url_for('videolist.videolist', query=querystring, page=str(int(page) + 1), fanart=fanart_url, update=True)
      )
      if fanart_url:
        item.set_property('fanart_image', fanart_url)
      videoItems.insert(0, item)

    if int(page) > 0:
      item = ListItem.from_dict(
        label='<< Previous',
        path=self.url_for('videolist.videolist', query=querystring, page=str(int(page) - 1), fanart=fanart_url, update=True)
      )
      if fanart_url:
        item.set_property('fanart_image', fanart_url)
      videoItems.insert(0, item)

    self.set_content('episodes')
    self.plugin.finish(
      items=videoItems,
      update_listing=update_listing,
      sort_methods=[SortMethod.UNSORTED, SortMethod.EPISODE, SortMethod.VIDEO_TITLE, SortMethod.VIDEO_RUNTIME])
    def showlist(self, type):
        api = NetworkTenVideo(self.plugin.cached(TTL=config.CACHE_TTL))
        shows = []
        if "news" == type:
            for news in api.get_news():
                fanart_url = api.get_fanart(news)

                item = ListItem.from_dict(
                    label=news["Title"],
                    path=self.url_for(
                        "videolist.videolist",
                        explicit=True,
                        query=news["BCQueryForVideoListing"],
                        page="0",
                        fanart=fanart_url,
                    ),
                )

                if fanart_url:
                    item.set_property("fanart_image", fanart_url)

                if "Thumbnail" in news:
                    url = news["Thumbnail"]
                    if url.startswith("//"):
                        url = "http:" + url
                    item.set_thumbnail(url)
                shows.append(item)
        elif "sport" == type:
            for sport in api.get_sports():
                item = ListItem.from_dict(
                    label=sport["Title"],
                    path=self.url_for(
                        "videolist.videolist", explicit=True, query=sport["BCQueryForVideoListing"], page="0"
                    ),
                )
                shows.append(item)
        elif "live" == type:
            for category in api.get_live_categories():
                fanart_url = None

                if "fanart" in category:
                    fanart_url = category["fanart"]

                item = ListItem.from_dict(
                    label=category["title"],
                    path=self.url_for(
                        "videolist.videolist", explicit=True, query=category["query"], page="0", fanart=fanart_url
                    ),
                )

                if fanart_url:
                    item.set_property("fanart_image", fanart_url)

                if "thumbnail" in category:
                    item.set_thumbnail(category["thumbnail"])

                shows.append(item)
        else:  # tvshows
            for show in api.get_shows():
                info_dict = {}
                if show["IsLongFormAvailable"] is not True:  # todo: make this a setting
                    continue
                if "Genres" in show and len(show["Genres"]):
                    info_dict["genre"] = show["Genres"][0]["Name"]
                if "Description" in show:
                    info_dict["plot"] = show["Description"]
                if "CurrentSeasonFirstEpisodeAirDateTime" in show:
                    try:
                        date = time.strptime(show["CurrentSeasonFirstEpisodeAirDateTime"], "%d-%m-%Y %H:%M:%S %p")
                        info_dict["aired"] = time.strftime("%Y-%m-%d", date)
                        info_dict["premiered"] = time.strftime("%Y-%m-%d", date)
                        info_dict["year"] = time.strftime("%Y", date)
                    except Exception, e:
                        pass
                if "Channel" in show:
                    info_dict["studio"] = show["Channel"]
                if "NumberOfVideosFromBCQuery" in show:
                    # not technically correct as this also returns the number of short form as well but close enough
                    info_dict["episode"] = show["NumberOfVideosFromBCQuery"]

                if "BCQueryForVideoListing" in show and len(show["BCQueryForVideoListing"]):
                    query = urlparse.parse_qs(show["BCQueryForVideoListing"], True)
                    if "all" not in query:
                        query["all"] = []
                    elif not isinstance(query["all"], list):
                        query["all"] = [query["all"]]

                    query["all"].append("video_type_long_form:Full Episode")

                    # some shows (Australian Survivor) have typos in the query, which break with exact matching
                    if "video_type_long_form:Full Episodes" in query["all"]:
                        query["all"].remove("video_type_long_form:Full Episodes")
                else:
                    continue

                fanart_url = api.get_fanart(show)

                item = ListItem.from_dict(
                    label=show["Title"],
                    path=self.url_for(
                        "videolist.videolist", explicit=True, query=urllib.urlencode(query, True), fanart=fanart_url
                    ),  # ShowPageItemId=show['ShowPageItemId']
                    info=info_dict,
                )

                if fanart_url:
                    item.set_property("fanart_image", fanart_url)

                if "Thumbnail" in show:
                    url = show["Thumbnail"]
                    if url.startswith("//"):
                        url = "http:" + url
                    item.set_thumbnail(url)
                shows.append(item)
 def __init__(self, plugin=None):
   self.api = NetworkTenVideo()
   self.log = plugin.log
   self.log.debug('Cache TTL set to %d minutes', config.CACHE_TTL)
   self.cache = plugin.get_storage('showlist', TTL=config.CACHE_TTL)
   print repr(self.cache)
class APICache:
  def __init__(self, plugin=None):
    self.api = NetworkTenVideo()
    self.log = plugin.log
    self.log.debug('Cache TTL set to %d minutes', config.CACHE_TTL)
    self.cache = plugin.get_storage('showlist', TTL=config.CACHE_TTL)
    print repr(self.cache)

  def get_show(self, show, bypassCache=False):
    if not bypassCache and 'showlist' in self.cache and show in self.cache['showlist']:
      self.log.debug('Retrieving show data for show "%s" from cache...', show)
      show_data = self.cache['showlist'][show]
    else:
      self.log.debug('Retrieving show data for show "%s" from api ...', show)
      show_data = self.api.get_show(show)
      if not 'showlist' in self.cache:
        self.cache['showlist'] = {}
      self.cache['showlist'][show_data.showName] = show_data
      self.cache.sync()

    self.log.debug('Show data: %s', repr(show_data))

    return show_data

  def get_shows(self, bypassCache=False):
    if not bypassCache and 'showlist' in self.cache:
      self.log.debug('Retrieving show list from cache...')
      shows = self.cache['showlist'].values()
    else:
      self.log.debug('Retrieving show list from api...')
      shows = self.api.get_shows().items
      if not 'showlist' in self.cache:
        self.cache['showlist'] = {}
      for show in shows:
        self.cache['showlist'][show.showName] = show
      self.cache.sync()

    self.log.debug('Shows: %s', repr(shows))

    return shows

  def get_playlists(self, show, bypassCache=False):
    if not bypassCache and 'showlist' in self.cache and show in self.cache['showlist'] and self.cache['showlist'][show].playlists and len(self.cache['showlist'][show].playlists) > 0:
      self.log.debug('Retrieving playlists for show "%s" from cache...', show)
      playlists = self.cache['showlist'][show].playlists
    else:
      self.log.debug('Retrieving playlists for show "%s" from api...', show)
      playlists = self.api.get_playlists_for_show(show).items
      if show in cache['showlist']:
        self.cache['showlist'][show].playlists = playlists
        self.cache.sync()

    self.log.debug('Playlists: %s', repr(playlists.items))

    return playlists

  def search_videos(self, bypassCache=False, **kwargs):
    key = json.dumps(kwargs)
    print repr(key)
    if not bypassCache and 'searches' in self.cache and key in self.cache['searches']:
      self.log.debug('Using search results from cache...')
      result = self.cache['searches'][key]
    else:
      self.log.debug('Using search results from api...')
      result = self.api.search_videos(**kwargs)
      if not 'searches' in self.cache:
        self.cache['searches'] = {}
      self.cache['searches'][key] = result
      self.cache.sync()
    return result
  def showlist(self, type):
    api = NetworkTenVideo(self.plugin.cached(TTL=config.CACHE_TTL))
    shows = []
    if 'news' == type:
      for news in api.get_news():
        fanart_url = api.get_fanart(news)

        item = ListItem.from_dict(
          label=news['Title'],
          path=self.url_for('videolist.videolist', explicit=True, query=news['BCQueryForVideoListing'], page='0', fanart=fanart_url),
        )

        if fanart_url:
          item.set_property('fanart_image', fanart_url)

        if 'Thumbnail' in news:
          url = news['Thumbnail']
          if url.startswith('//'):
            url = 'http:' + url
          item.set_thumbnail(url)
        shows.append(item)
    elif 'sport' == type:
      for sport in api.get_sports():
        item = ListItem.from_dict(
          label=sport['Title'],
          path=self.url_for('videolist.videolist', explicit=True, query=sport['BCQueryForVideoListing'], page='0'),
        )
        shows.append(item)
    elif 'live' == type:
      for category in api.get_live_categories():
        fanart_url = None

        if 'fanart' in category:
          fanart_url = category['fanart']

        item = ListItem.from_dict(
          label=category['title'],
          path=self.url_for('videolist.videolist', explicit=True, query=category['query'], page='0', fanart=fanart_url),
        )

        if fanart_url:
          item.set_property('fanart_image', fanart_url)

        if 'thumbnail' in category:
          item.set_thumbnail(category['thumbnail'])

        shows.append(item)
    else: #tvshows
      for show in api.get_shows():
        info_dict = {}
        if show['IsLongFormAvailable'] is not True: #todo: make this a setting
          continue
        if 'Genres' in show and len(show['Genres']):
          info_dict['genre'] = show['Genres'][0]['Name']
        if 'Description' in show:
          info_dict['plot'] = show['Description']
        if 'CurrentSeasonFirstEpisodeAirDateTime' in show:
          try:
            date = time.strptime(show['CurrentSeasonFirstEpisodeAirDateTime'],'%d-%m-%Y %H:%M:%S %p')
            info_dict['aired'] = time.strftime('%Y-%m-%d', date)
            info_dict['premiered'] = time.strftime('%Y-%m-%d', date)
            info_dict['year'] = time.strftime('%Y', date)
          except Exception, e:
            pass
        if 'Channel' in show:
          info_dict['studio'] = show['Channel']
        if 'NumberOfVideosFromBCQuery' in show:
          # not technically correct as this also returns the number of short form as well but close enough
          info_dict['episode'] = show['NumberOfVideosFromBCQuery']

        if 'BCQueryForVideoListing' in show and len(show['BCQueryForVideoListing']):
          query = urlparse.parse_qs(show['BCQueryForVideoListing'], True)
          if 'all' not in query:
            query['all'] = []
          elif not isinstance(query['all'], list):
            query['all'] = [ query['all'] ]
          query['all'].append('video_type_long_form:Full Episode')
        else:
          continue

        fanart_url = api.get_fanart(show)

        item = ListItem.from_dict(
          label=show['Title'],
          path=self.url_for('videolist.videolist', explicit=True, query=urllib.urlencode(query, True), fanart=fanart_url), #ShowPageItemId=show['ShowPageItemId']
          info=info_dict
        )

        if fanart_url:
          item.set_property('fanart_image', fanart_url)

        if 'Thumbnail' in show:
          url = show['Thumbnail']
          if url.startswith('//'):
            url = 'http:' + url
          item.set_thumbnail(url)
        shows.append(item)