Exemplo n.º 1
0
def play(url):
    resolved = ''
    stream_url = ''
    item = None
    try:
        import urlresolver
        resolved = urlresolver.HostedMediaFile(url).resolve()
        if not resolved or resolved == False or len(resolved) < 1:
            resolved = urlresolver.resolve(url)
            if resolved is None or len(resolved) < 1:
                resolved = urlresolver.resolve(urllib.unquote(url))
        if len(resolved) > 1:
            plugin.notify(msg="PLAY {0}".format(resolved.partition('.')[-1]), title="URLRESOLVER", delay=1000)
            plugin.set_resolved_url(resolved)
            item = ListItem.from_dict(path=resolved)
            item.add_stream_info('video', stream_values={})
            item.set_is_playable(True)
            return item
    except:
        resolved = ''
        plugin.notify(msg="FAILED {0}".format(url.partition('.')[-1]), title="URLRESOLVER", delay=1000)
    try:
        import YDStreamExtractor
        info = YDStreamExtractor.getVideoInfo(url, resolve_redirects=True)
        resolved = info.streamURL()
        for s in info.streams():
            try:
                stream_url = s['xbmc_url'].encode('utf-8', 'ignore')
                xbmc.log(msg="**YOUTUBE-DL Stream found: {0}".format(stream_url))
            except:
                pass
        if len(stream_url) > 1:
            resolved = stream_url
        if len(resolved) > 1:
            plugin.notify(msg="Playing: {0}".format(resolved.partition('.')[-1]), title="YOUTUBE-DL", delay=1000)
            plugin.set_resolved_url(resolved)
            item = ListItem.from_dict(path=resolved)
            item.add_stream_info('video', stream_values={})
            item.set_is_playable(True)
            return item
    except:
        plugin.notify(msg="Failed: {0}".format(resolved.partition('.')[-1]), title="YOUTUBE-DL", delay=1000)

    if len(resolved) > 1:
        plugin.set_resolved_url(resolved)
        item = ListItem.from_dict(path=resolved)
        return item
    else:
        plugin.set_resolved_url(url) #url)
        #plugurl = 'plugin://plugin.video.live.streamspro/?url={0}'.format(urllib.quote_plus(url))
        #item = ListItem.from_dict(path=plugurl)
        #item.add_stream_info('video', stream_values={})
        #item.set_is_playable(True)
        #plugin.notify(msg="RESOLVE FAIL: {0}".format(url.split('.', 1)[-1]),title="Trying {0}".format(item.path.split('.', 1)[-1]), delay=2000)
        return None
Exemplo n.º 2
0
    def test_from_dict_props(self):
        dct = {
            'properties': {'StartOffset': '256.4'},
        }
        item = ListItem.from_dict(**dct)
        self.assertEqual(item.get_property('StartOffset'), '256.4')

        dct = {
            'properties': [('StartOffset', '256.4')],
        }
        item = ListItem.from_dict(**dct)
        self.assertEqual(item.get_property('StartOffset'), '256.4')
Exemplo n.º 3
0
    def test_from_dict_props(self):
        dct = {
            'properties': {
                'StartOffset': '256.4'
            },
        }
        item = ListItem.from_dict(**dct)
        self.assertEqual(item.get_property('StartOffset'), '256.4')

        dct = {
            'properties': [('StartOffset', '256.4')],
        }
        item = ListItem.from_dict(**dct)
        self.assertEqual(item.get_property('StartOffset'), '256.4')
Exemplo n.º 4
0
def episode_makeitem(episodename, episodelink):
    '''
    Will return a ListItem for the given link to an episode and it's full linked name.
    Name will be sent to format show to attempt to parse out a date or season from the title.
    Infolabels are populated with any details that can be parsed from the title as well.
    Should be used anytime an item needs to be created that is an item for one specific episode of a show.
    Latest 350, Saved Show, Category (Show listing of all episodes for that series) would all use this.
    '''
    infolbl = {}
    spath = plugin.url_for(episode, name=episodename, url=episodelink)
    img = "DefaultVideoFolder.png"
    seasonstr = ''
    try:
        eptitle, epdate, epnum = formatshow(episodename)
        eplbl = formatlabel(eptitle, epdate, epnum)
        plotstr = "{0} ({1}): {2} {3}".format(epdate, epnum, eptitle, episodelink)
        infolbl = {'Date': epdate, 'Title': eptitle, 'Plot': plotstr}
        if len(epnum) > 0:
            showS, showE = findepseason(epnum)
            dictshow = {'Episode': showE, 'Season': showS}
            infolbl.update(dictshow)
            snum = int(showS)
            epnum = int(showE)
            if snum > 0 and epnum > 0:
                epdate = "S{0}e{1}".format(snum, epnum)
        item = {'label': eplbl, 'label2': epdate, 'icon': img, 'thumbnail': img, 'path': spath}
        item.setdefault(item.keys()[0])
        li = ListItem.from_dict(**item)
        li.set_info(type='video', info_labels=infolbl)
        li.add_context_menu_items([('Search [B]{0}[/B]'.format(eptitle), 'RunPlugin({0})'.format(plugin.url_for(query, searchquery=eptitle)),)])
    except:
        li = ListItem(label=episodename, label2=episodelink, icon=img, thumbnail=img, path=spath)
    return li
Exemplo n.º 5
0
    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)
Exemplo n.º 6
0
def episode(name='', url=''):
    waserror = False
    linklist = []
    if len(url) == '':
        waserror = True
    else:
        html = DL(url)
        litems = []
        linklist = findvidlinks(html)
        itemparent = None
    if len(linklist) > 0:
        for name, link in linklist:
            itempath = plugin.url_for(play, url=link)
            item = dict(label=name, label2=link, icon='DefaultFolder.png', thumbnail='DefaultFolder.png', path=itempath)
            item.setdefault(item.keys()[0])
            litems.append(item)
        vitems = sortSourceItems(litems)
        litems = []
        for li in vitems:
            item = ListItem.from_dict(**li)
            item.set_is_playable(True)
            item.set_info(type='video', info_labels={'Title': item.label, 'Plot': item.label2})
            item.add_stream_info(stream_type='video', stream_values={})
            litems.append(item)
    else:
        waserror = True
    if waserror:
        plugin.notify(title="ERROR No links: {0}".format(name), msg=url)
        return []
    return litems
Exemplo n.º 7
0
def interactive(plugin):
    '''A run mode for the CLI that runs the plugin in a loop based on user
    input.
    '''
    items = [item for item in once(plugin) if not item.get_played()]
    parent_stack = []  # Keep track of parents so we can have a '..' option

    selected_item = get_user_choice(items)
    while selected_item is not None:
        if parent_stack and selected_item == parent_stack[-1]:
            # User selected the parent item, remove from list
            parent_stack.pop()
        else:
            # User selected non parent item, add current url to parent stack
            parent_stack.append(
                ListItem.from_dict(label='..', path=plugin.request.url))
        patch_plugin(plugin, selected_item.get_path())

        # If we have parent items, include the top of the stack in the list
        # item display
        parent_item = None
        if parent_stack:
            parent_item = parent_stack[-1]
        items = [
            item for item in once(plugin, parent_item=parent_item)
            if not item.get_played()
        ]
        selected_item = get_user_choice(items)
Exemplo n.º 8
0
 def test_from_dict(self):
     dct = {
         'label': 'foo',
         'label2': 'bar',
         'icon': 'icon',
         'thumbnail': 'thumbnail',
         'path': 'plugin://my.plugin.id/',
         'selected': True,
         'info': {'title': 'My title'},
         'info_type': 'pictures',
         'properties': [('StartOffset', '256.4')],
         'context_menu': [('label', 'action')],
         'is_playable': True}
     with patch.object(ListItem, 'set_info', spec=True) as mock_set_info:
         item = ListItem.from_dict(**dct)
     self.assertEqual(item.label, 'foo')
     self.assertEqual(item.label2, 'bar')
     self.assertEqual(item.icon, 'icon')
     self.assertEqual(item.thumbnail, 'thumbnail')
     self.assertEqual(item.path, 'plugin://my.plugin.id/')
     self.assertEqual(item.selected, True)
     mock_set_info.assert_called_with('pictures', {'title': 'My title'})
     self.assertEqual(item.get_property('StartOffset'), '256.4')
     self.assertEqual(item.get_context_menu_items(), [('label', 'action')]) 
     self.assertEqual(item.get_property('isPlayable'), 'true')
     self.assertEqual(item.is_folder, False)
Exemplo n.º 9
0
    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)
Exemplo n.º 11
0
def interactive(plugin):
    '''A run mode for the CLI that runs the plugin in a loop based on user
    input.
    '''
    items = [item for item in once(plugin) if not item.get_played()]
    parent_stack = []  # Keep track of parents so we can have a '..' option

    selected_item = get_user_choice(items)
    while selected_item is not None:
        if parent_stack and selected_item == parent_stack[-1]:
            # User selected the parent item, remove from list
            parent_stack.pop()
        else:
            # User selected non parent item, add current url to parent stack
            parent_stack.append(ListItem.from_dict(label='..',
                                                   path=plugin.request.url))
        patch_plugin(plugin, selected_item.get_path())

        # If we have parent items, include the top of the stack in the list
        # item display
        parent_item = None
        if parent_stack:
            parent_item = parent_stack[-1]
        items = [item for item in once(plugin, parent_item=parent_item)
                 if not item.get_played()]
        selected_item = get_user_choice(items)
Exemplo n.º 12
0
 def test_from_dict(self):
     dct = {
         'label': 'foo',
         'label2': 'bar',
         'icon': 'icon',
         'thumbnail': 'thumbnail',
         'path': 'plugin://my.plugin.id/',
         'selected': True,
         'info': {
             'title': 'My title'
         },
         'info_type': 'pictures',
         'properties': [('StartOffset', '256.4')],
         'context_menu': [('label', 'action')],
         'is_playable': True
     }
     with patch.object(ListItem, 'set_info', spec=True) as mock_set_info:
         item = ListItem.from_dict(**dct)
     self.assertEqual(item.label, 'foo')
     self.assertEqual(item.label2, 'bar')
     self.assertEqual(item.icon, 'icon')
     self.assertEqual(item.thumbnail, 'thumbnail')
     self.assertEqual(item.path, 'plugin://my.plugin.id/')
     self.assertEqual(item.selected, True)
     mock_set_info.assert_called_with('pictures', {'title': 'My title'})
     self.assertEqual(item.get_property('StartOffset'), '256.4')
     self.assertEqual(item.get_context_menu_items(), [('label', 'action')])
     self.assertEqual(item.get_property('isPlayable'), 'true')
     self.assertEqual(item.is_folder, False)
Exemplo n.º 13
0
def index():
    json_query = get_movie_list()
    if not json_query:
        return
    for item in json_query['data']['videos']:
        movie_id = item['MovieID']
        year = "20" + movie_id[4:6]
        image = IMAGE_API + year + "/" + movie_id + "/popu.jpg"
        listitem = ListItem.from_dict(
            **{
                'label': item['Title'],
                'path': PLAY_API + movie_id + "/hls/index.m3u8",
                'icon': image,
                'info': {
                    "Title": item['Title'],
                    "OriginalTitle": item['Title'],
                    "Year": int(year),
                    "Country": "Japan",
                    "Plot": item['Desc'],
                    "Rating": str(item['AvgRating'] * 2.0),
                    "MPAA": "R",
                    "Cast": item['ActressesJa'],
                    "CastAndRole": item['ActressesEn'],
                    "Duration": item['Duration'],
                    "premiered": year + "-" + movie_id[:2] + "-" +
                    movie_id[2:4],
                    "mediatype": "movie"
                },
                'is_playable': True,
            })
        yield listitem
Exemplo n.º 14
0
def playurl():
    url = ''
    url = plugin.keyboard(default='', heading='Video Page URL')
    if url != '' and len(url) > 0:
        item = ListItem.from_dict(path=plugin.url_for(endpoint=play, url=url))
        item.set_is_playable(True)
        item.set_info(type='video', info_labels={'Title': url, 'Plot': url})
        item.add_stream_info(stream_type='video', stream_values={})
        return play(url)
Exemplo n.º 15
0
def playfirst(url=''):
    idx = 0
    if len(url) < 1:
        return None
    thispath = plugin.url_for(endpoint=play, url=url)
    selItem = None
    outtxt = "Not Found"
    try:
        for fitem in plugin.added_items:
            if fitem.selected == True or fitem.path.find(thispath) != -1:
                try:
                    plugin.set_resolved_url(fitem)
                    fitem.is_playable(True)
                    fitem.played(True)
                except:
                    pass
                selItem = fitem
                plugin.notify(msg=selItem.label, title="Found item")
                break
    except:
        selItem = None
    if selItem is not None:
        try:
            selItem.set_is_playable(True)
            selItem.set_played(was_played=True)
            outtxt = selItem.label + " " + selItem.label2
        except:
            outtxt = str(repr(selItem))
    plugin.notify(msg=outtxt, title=str(idx))
    html = DL(url)
    prefhost = ''
    sourceslist = []
    stext = plugin.get_setting('topSources')
    if len(stext) < 1:
        prefhost = 'thevideo'
    else:
        sourceslist = stext.split(',')
        prefhost = sourceslist[0]
    litems = []
    linklist = findvidlinks(html, findhost=prefhost)
    if len(linklist) > 0:
        name, link = linklist[0]
        itempath = plugin.url_for(play, url=link)
        sitem = dict(label=name, label2=link, icon='DefaultFolder.png', thumbnail='DefaultFolder.png', path=itempath)
        sitem.setdefault(sitem.keys()[0])
        item = ListItem.from_dict(**sitem)
        item.set_is_playable(True)
        item.set_info(type='video', info_labels={'Title': item.label, 'Plot': item.label2})
        item.add_stream_info(stream_type='video', stream_values={})
        plugin.notify(msg=link, title=name)
        # plugin.add_items([item])
        item.set_played(was_played=True)
        # plugin.add_items([plugin.set_resolved_url(link)])#.as_tuple())])
        plugin.play_video(item)
        return [plugin.set_resolved_url(item)]
Exemplo n.º 16
0
def makecatitem(name, link, removelink=False):
    item = {}
    ctxitem = {}
    itempath = plugin.url_for(category, name=name, url=link)
    item = {'label': name, 'label2': link, 'icon': 'DefaultFolder.png', 'thumbnail': 'DefaultFolder.png', 'path': itempath}
    item.setdefault(item.keys()[0])
    litem = ListItem.from_dict(**item)
    #if removelink:
    #    litem.add_context_menu_items([('Remove Saved Show', 'RunPlugin("{0}")'.format(plugin.url_for(removeshow, name=name, link=itempath)),)])
    #else:
    litem.add_context_menu_items([('Save Show', 'RunPlugin("{0}")'.format(plugin.url_for(saveshow, name=name, link=link)),)])
    return litem
Exemplo n.º 17
0
def playlist_play_all(playlist_id):
    data = api.request('playlist.getInfo', {
        'id': playlist_id,
        'video_sources': _get_supported_sources(),
        'video_status': 1
    })
    items = [_make_video_item(video) for video in data['playlist']['videos']['video']]
    playlist = xbmc.PlayList(xbmc.PLAYLIST_VIDEO)
    playlist.clear()
    for item in items:
        listitem = ListItem.from_dict(**item)
        playlist.add(item['path'], listitem.as_xbmc_listitem())
    player = xbmc.Player()
    player.playPlaylist(playlist)
Exemplo n.º 18
0
    def _listitemify(self, item):
        '''Creates an xbmcswift2.ListItem if the provided value for item is a
        dict. If item is already a valid xbmcswift2.ListItem, the item is
        returned unmodified.
        '''
        info_type = self.info_type if hasattr(self, 'info_type') else 'video'

        # Create ListItems for anything that is not already an instance of
        # ListItem
        if not hasattr(item, 'as_tuple'):
            if 'info_type' not in item.keys():
                item['info_type'] = info_type
            item = ListItem.from_dict(**item)
        return item
Exemplo n.º 19
0
def disc_play_all(disc_id):
    data = api.request(
        'disc.getInfo', {
            'id': disc_id,
            'video_sources': _get_supported_sources(),
            'video_status': 1
        })
    items = [
        _make_video_item(video) for video in data['disc']['videos']['video']
    ]
    playlist = xbmc.PlayList(xbmc.PLAYLIST_VIDEO)
    playlist.clear()
    for item in items:
        listitem = ListItem.from_dict(**item)
        playlist.add(item['path'], listitem.as_xbmc_listitem())
    player = xbmc.Player()
    player.playPlaylist(playlist)
Exemplo n.º 20
0
def loadsaved():
    sitems = []
    litems = []
    items = []
    savedpath = ''
    try:
        savedpath = path.join(__datadir__, "saved.json")
        if path.exists(savedpath):
            fpin = file(savedpath)
            rawjson = fpin.read()
            sitems = json.loads(rawjson)
            fpin.close()
        else:
            return []
        for item in sitems:
            li = ListItem.from_dict(**item)
            litems.append(li)
    except:
        pass
    return litems
Exemplo n.º 21
0
def episode(name, url):
    html = DL(url)
    litems = []
    linklist = findvidlinks(html)
    if len(linklist) > 0:
        for name, link in linklist:
            itempath = plugin.url_for(play, url=link)
            item = dict(label=name, label2=link, icon='DefaultFolder.png', thumbnail='DefaultFolder.png', path=itempath)
            item.setdefault(item.keys()[0])
            litems.append(item)
        vitems = sortSourceItems(litems)
        litems = []
        for li in vitems:
            item = ListItem.from_dict(**li)
            item.set_is_playable(True)
            item.set_info(type='video', info_labels={'Title': item.label, 'Plot': item.label2})
            item.add_stream_info(stream_type='video', stream_values={})
            litems.append(item)
    else:
        plugin.notify(msg="ERROR No links found for {0}".format(name), title=url)
    return litems
    def playlist(self, show):
        api = APICache(self.plugin)
        show_data = api.get_show(show)

        if len(show_data.playlists) > 0:
            playlists = show_data.playlists
        else:
            playlists = api.get_playlists(show)

        playlistItems = []
        for playlist in playlists:
            item = ListItem.from_dict(
                label=playlist.name,
                path=self.url_for("videolist.videolist", explicit=True, query=playlist.query, show=show),
            )
            if show_data.fanart:
                item.set_property("fanart_image", show_data.fanart)
            if playlist.type == "season":
                item.set_info("video", {season: playlist.season})
            playlistItems.append(item)

        self.plugin.finish(items=playlistItems, sort_methods=[SortMethod.UNSORTED, SortMethod.LABEL_IGNORE_THE])
Exemplo n.º 23
0
def loadsaved():
    sitems = []
    litems = []
    items = []
    savedpath = ''
    try:
        savedpath = path.join(__datadir__, "saved.json")
        if path.exists(savedpath):
            fpin = file(savedpath)
            rawjson = fpin.read()
            sitems = json.loads(rawjson)
            fpin.close()
        else:
            return []
        for item in sitems:
            li = ListItem.from_dict(**item)
            li.add_context_menu_items(
                [('Remove Saved Show', 'RunPlugin("{0}")'.format(plugin.url_for(removeshow, name=li.label, link=li.path)),)])
            litems.append(li)
    except:
        pass
    return litems
Exemplo n.º 24
0
def episode_makeitem(episodename, episodelink, dateadded=None):
    '''
    Will return a ListItem for the given link to an episode and it's full linked name.
    Name will be sent to format show to attempt to parse out a date or season from the title.
    Infolabels are populated with any details that can be parsed from the title as well.
    Should be used anytime an item needs to be created that is an item for one specific episode of a show.
    Latest 350, Saved Show, Category (Show listing of all episodes for that series) would all use this.
    '''
    infolbl = {}
    spath = plugin.url_for(episode, name=episodename, url=episodelink)
    img = "DefaultVideoFolder.png"
    seasonstr = ''
    try:
        eptitle, epdate, epnum = formatshow(episodename)
        eplbl = formatlabel(eptitle, epdate, epnum)
        plotstr = "{0} ({1}): {2} {3}".format(epdate, epnum, eptitle, episodelink)
        infolbl = {'EpisodeName': epdate, 'Title': eptitle, 'Plot': plotstr}
        if len(epnum) > 0:
            showS, showE = findepseason(epnum)
            snum = int(showS)
            epnum = int(showE)
            infolbl.update({'Episode': showE, 'Season': showS})
            if snum > 0 and epnum > 0:
                epdate = "S{0}e{1}".format(snum, epnum)
                infolbl.update({'PlotOutline': epdate})
        if dateadded is not None:
            dateout = str(dateadded.replace(' ', '-')).strip()
            infolbl.update({"Date": dateout})
        item = {'label': eplbl, 'label2': epdate, 'icon': img, 'thumbnail': img, 'path': spath}
        item.setdefault(item.keys()[0])
        li = ListItem.from_dict(**item)
        li.set_is_playable(is_playable=True)
        li.is_folder = True
        li.set_info(type='video', info_labels=infolbl)
        li.add_context_menu_items(
            [('Autoplay', 'RunPlugin("{0}")'.format(plugin.url_for(endpoint=playfirst, url=episodelink)),)])
    except:
        li = ListItem(label=episodename, label2=episodelink, icon=img, thumbnail=img, path=spath)
    return li
Exemplo n.º 25
0
  def playlist(self, show):
    api = APICache(self.plugin)
    show_data = api.get_show(show)

    if len(show_data.playlists) > 0:
      playlists = show_data.playlists
    else:
      playlists = api.get_playlists(show)

    playlistItems = []
    for playlist in playlists:
      item = ListItem.from_dict(
        label=playlist.name,
        path=self.url_for('videolist.videolist', explicit=True, query=playlist.query, show=show)
      )
      if show_data.fanart:
        item.set_property('fanart_image', show_data.fanart)
      if playlist.type == "season":
        item.set_info('video', {season: playlist.season})
      playlistItems.append(item)

    self.plugin.finish(items=playlistItems, sort_methods=[SortMethod.UNSORTED, SortMethod.LABEL_IGNORE_THE])
Exemplo n.º 26
0
    def add_to_playlist(self, items, playlist='video'):
        '''Adds the provided list of items to the specified playlist.
        Available playlists include *video* and *music*.
        '''
        playlists = {'music': 0, 'video': 1}
        assert playlist in playlists.keys(), ('Playlist "%s" is invalid.' %
                                              playlist)
        selected_playlist = xbmc.PlayList(playlists[playlist])

        _items = []
        for item in items:
            if not hasattr(item, 'as_xbmc_listitem'):
                if 'info_type' in item.keys():
                    log.warning('info_type key has no affect for playlist '
                                'items as the info_type is inferred from the '
                                'playlist type.')
                # info_type has to be same as the playlist type
                item['info_type'] = playlist
                item = ListItem.from_dict(**item)
            _items.append(item)
            selected_playlist.add(item.get_path(), item.as_xbmc_listitem())
        return _items
Exemplo n.º 27
0
def episode_makeitem(episodename, episodelink, dateadded=None):
    '''
    Will return a ListItem for the given link to an episode and it's full linked name.
    Name will be sent to format show to attempt to parse out a date or season from the title.
    Infolabels are populated with any details that can be parsed from the title as well.
    Should be used anytime an item needs to be created that is an item for one specific episode of a show.
    Latest 350, Saved Show, Category (Show listing of all episodes for that series) would all use this.
    '''
    infolbl = {}
    spath = plugin.url_for(episode, name=episodename, url=episodelink)
    img = "DefaultVideoFolder.png"
    seasonstr = ''
    try:
        eptitle, epdate, epnum = formatshow(episodename)
        eplbl = formatlabel(eptitle, epdate, epnum)
        plotstr = "{0} ({1}): {2} {3}".format(epdate, epnum, eptitle, episodelink)
        infolbl = {'EpisodeName': epdate, 'Title': eptitle, 'Plot': plotstr}
        if len(epnum) > 0:
            showS, showE = findepseason(epnum)
            snum = int(showS)
            epnum = int(showE)
            infolbl.update({'Episode': showE, 'Season': showS})
            if snum > 0 and epnum > 0:
                epdate = "S{0}e{1}".format(snum, epnum)
                infolbl.update({'PlotOutline': epdate})
        if dateadded is not None:
            dateout = dateadded.replace(' ', '-').trim()
            eplbl += " [I][B][LIGHT]{0}[/LIGHT][/B][/I]".format(dateout)
            infolbl.update({"Date": dateout})
        item = {'label': eplbl, 'label2': epdate, 'icon': img, 'thumbnail': img, 'path': spath}
        item.setdefault(item.keys()[0])
        li = ListItem.from_dict(**item)
        li.set_info(type='video', info_labels=infolbl)
    except:
        li = ListItem(label=episodename, label2=episodelink, icon=img, thumbnail=img, path=spath)
    return li
Exemplo n.º 28
0
 def test_from_dict_info_default_info_type(self):
     dct = {'info': {'title': 'My title'}}
     with patch.object(ListItem, 'set_info', spec=True) as mock_set_info:
         item = ListItem.from_dict(**dct)
     mock_set_info.assert_called_with('video', {'title': 'My title'})
Exemplo n.º 29
0
 def test_from_dict_info_default_info_type(self):
     dct = {'info': {'title': 'My title'}}
     with patch.object(ListItem, 'set_info', spec=True) as mock_set_info:
         item = ListItem.from_dict(**dct)
     mock_set_info.assert_called_with('video', {'title': 'My title'})
  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 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)