def play_song(url, thumb, ep_title, show_name, speakers):
    play_item = xbmcgui.ListItem(path=url)
    play_item.setThumbnailImage(thumb)
    play_item.setInfo('music', {'title': ep_title,
                                'album': show_name,
                                'artist': speakers})
    xbmcplugin.setResolvedUrl(ADDON_HANDLE, True, listitem=play_item)
Esempio n. 2
0
 def resolve_url(self, stream_url):
     '''
     Tell XBMC that you have resolved a URL (or not!).
     
     This method should be called as follows:
     
     #. The user selects a list item that has previously had ``isPlayable``
        set (this is true for items added with :meth:`add_item`, 
        :meth:`add_music_item` or :meth:`add_music_item`)
     #. Your code resolves the item requested by the user to a media URL
     #. Your addon calls this method with the resolved URL
     
     Args:
         stream_url (str or ``False``): If a string, tell XBMC that the 
         media URL ha been successfully resolved to stream_url. If ``False`` 
         or an empty string tell XBMC the resolving failed and pop up an 
         error messsage.
     '''
     if stream_url:
         self.log_debug('resolved to: %s' % stream_url)
         xbmcplugin.setResolvedUrl(self.handle, True, 
                                   xbmcgui.ListItem(path=stream_url))
     else:
         self.show_error_dialog(['sorry, failed to resolve URL :('])
         xbmcplugin.setResolvedUrl(self.handle, False, xbmcgui.ListItem())
Esempio n. 3
0
def get_free_movies():
	html2 = make_request(url)
	html = json.loads(html2)
	content_id=''
	for r in html['contents']:
		if '1' in r['content_type_id']:
			content_id = r['content_id']
			name = r['title']
	if content_id:
		userurl = 'https://erosnow.com/secured/dologin'
		req = make_request_post(userurl)
		movieurl2 = 'http://erosnow.com/profiles/'+str(content_id)+'?platform=2&q=auto'
		html3 = make_request(movieurl2)
		html4 = json.loads(html3)
		req2 = json.loads(req)
		item2 = xbmcgui.ListItem(name)
		if (str(req2['success']['plan']) == 'False'):
			movie_link = html4['profiles']['ADAPTIVE_SD'][0]
		else:
			movie_link = html4['profiles']['ADAPTIVE_ALL'][0]
			subYes = Addon.getSetting('subType')
			if (subYes=='true') and (html4.get('subtitles')):
				closedcaption=[]
				closedcaption.append(html4['subtitles']['eng']['url'])
				subpath = convert_subtitles(closedcaption)
				item2.setSubtitles([subpath])
		
		item2.setProperty('IsPlayable', 'true')
		item2.setPath(movie_link['url'])
		xbmcplugin.setResolvedUrl(int(sys.argv[1]), True, item2)
	else:
		dialog.notification('Error', 'Movie may not be released yet.', xbmcgui.NOTIFICATION_INFO, 6000)
Esempio n. 4
0
 def getAddonVideo(self,url):
     html = self.getRequest('http://www.snagfilms.com/embed/player?filmId=%s' % uqp(url))
     url = re.compile('file: "(.+?)"', re.DOTALL).findall(html)
     u = ''
     for x in url: 
         if '6912k' in x: u = x
     if u == '' :
         u = url[-1]
     bspeed = self.addon.getSetting('bitrate')
     if bspeed == '0':
         u = url[0]
     elif bspeed == '2':
         u = url[-1]
     liz = xbmcgui.ListItem(path=u)
     infoList ={}
     infoList['mediatype'] = xbmc.getInfoLabel('ListItem.DBTYPE')
     infoList['Title'] = xbmc.getInfoLabel('ListItem.Title')
     infoList['TVShowTitle'] = xbmc.getInfoLabel('ListItem.TVShowTitle')
     infoList['Year'] = xbmc.getInfoLabel('ListItem.Year')
     infoList['Premiered'] = xbmc.getInfoLabel('Premiered')
     infoList['Plot'] = xbmc.getInfoLabel('ListItem.Plot')
     infoList['Studio'] = xbmc.getInfoLabel('ListItem.Studio')
     infoList['Genre'] = xbmc.getInfoLabel('ListItem.Genre')
     infoList['Duration'] = xbmc.getInfoLabel('ListItem.Duration')
     infoList['MPAA'] = xbmc.getInfoLabel('ListItem.Mpaa')
     infoList['Aired'] = xbmc.getInfoLabel('ListItem.Aired')
     infoList['Season'] = xbmc.getInfoLabel('ListItem.Season')
     infoList['Episode'] = xbmc.getInfoLabel('ListItem.Episode')
     liz.setInfo('video', infoList)
     xbmcplugin.setResolvedUrl(int(sys.argv[1]), True, liz)
Esempio n. 5
0
def Play(
    resolved_url,
    addon_id,
    video_type,
    title,
    season,
    episode,
    year,
    watch_percent=0.9,
    watchedCallback=None,
    watchedCallbackwithParams=None,
    imdb_id=None,
):
    player = Player()
    common.addon.log("-" + HELPER + "- -" + resolved_url)
    player.set(
        addon_id,
        video_type,
        title,
        season,
        episode,
        year,
        watch_percent,
        watchedCallback,
        watchedCallbackwithParams,
        imdb_id,
    )
    xbmcplugin.setResolvedUrl(int(sys.argv[1]), True, xbmcgui.ListItem(path=resolved_url))
    return player
Esempio n. 6
0
def PLAY(params):
    # -- get filter parameters
    par = Get_Parameters(params)

    # -- if requested continious play
    if Addon.getSetting("continue_play") == "true":
        # create play list
        pl = xbmc.PlayList(1)
        pl.clear()
        # -- get play list
        playlist = Get_PlayList(par.playlist)
        is_found = False
        for rec in playlist:
            name = rec["comment"].encode("utf-8")
            s_url = rec["file"]
            # -- add item to play list
            if s_url == par.url:
                is_found = True

            if is_found:
                i = xbmcgui.ListItem(name, path=urllib.unquote(s_url), thumbnailImage=par.img)
                i.setProperty("IsPlayable", "true")
                pl.add(s_url, i)

        xbmc.Player().play(pl)
    # -- play only selected item
    else:
        i = xbmcgui.ListItem(par.name, path=urllib.unquote(par.url), thumbnailImage=par.img)
        i.setProperty("IsPlayable", "true")
        xbmcplugin.setResolvedUrl(h, True, i)
Esempio n. 7
0
 def run(self, oGuiElement, sTitle, sUrl):
     sPluginHandle = cPluginHandler().getPluginHandle();
     #meta = oGuiElement.getInfoLabel()
     meta = {'label': sTitle, 'title': sTitle}
     item = xbmcgui.ListItem(path=sUrl, iconImage="DefaultVideo.png",  thumbnailImage=self.sThumbnail)
     
     item.setInfo( type="Video", infoLabels= meta )
                 
     if (cConfig().getSetting("playerPlay") == '0'):   
                         
         sPlayerType = self.__getPlayerType()
         xbmcPlayer = xbmc.Player(sPlayerType)
         xbmcPlayer.play( sUrl, item )
         xbmcplugin.endOfDirectory(sPluginHandle, True, False, False) 
         
     else:
         xbmcplugin.setResolvedUrl(sPluginHandle, True, item)
     
     timer = int(cConfig().getSetting('param_timeout'))
     xbmc.sleep(timer)
     
     while not xbmc.abortRequested:
         try: 
            self.currentTime = self.getTime()
            self.totalTime = self.getTotalTime()
         except: break
         xbmc.sleep(1000)
def panPlay():
    li = xbmcgui.ListItem(_station[0])
    li.setPath("special://home/addons/%s/silent.m4a" % _plugin)
    li.setProperty(_plugin, _stamp)
    li.setProperty('mimetype', 'audio/aac')

    _lock.acquire()
    start = time.time()
    panFill()

    while not _play:
        time.sleep(0.01)
        xbmc.sleep(1000)

        if xbmc.abortRequested:
            _lock.release()
            exit()

        if (threading.active_count() == 1) or ((time.time() - start) >= 60):
            if _play: break	# check one last time before we bail

            xbmc.log("%s.Play BAD (%13s, %ds)" % (_plugin, _stamp, time.time() - start))
            xbmcgui.Dialog().ok(_name, 'No Tracks Received', '', 'Try again later')
            exit()

    _playlist.clear()
    _lock.release()
    time.sleep(0.01)	# yield to the song threads
    xbmc.sleep(1000)	# might return control to xbmc and skip the other threads ?

    xbmcplugin.setResolvedUrl(_handle, True, li)
    _player.play(_playlist)
    xbmc.executebuiltin('ActivateWindow(10500)')

    xbmc.log("%s.Play  OK (%13s)           '%s - %s'" % (_plugin, _stamp, _station.id[-4:], _station.name))
Esempio n. 9
0
    def __init__(self):
        self._parse_argv()

        self.tokens = {}
        sortLetterList = list()
        # 0 if false, 1 if true
        hasParentItem = xbmc.getCondVisibility('System.GetBool(filelists.showparentdiritems)')
        ignoreArticles = xbmc.getCondVisibility('System.GetBool(filelists.ignorethewhensorting)')
        wid = xbmcgui.getCurrentWindowId()
        currentWindow = xbmcgui.Window(wid)

        # get sort tokens from advancedsettings.xml
        f = xbmcvfs.File(xbmc.translatePath('special://userdata/advancedsettings.xml'))
        advancedsettings = f.read()
        f.close()

        if advancedsettings:
            root = ET.fromstring(advancedsettings)
            sorttokens = root.find('sorttokens')
            # user specified tokens, proceed to create dictionary
            if sorttokens is not None:
                self.tokens = { token.text.encode('utf-8') : u'' for token in sorttokens.findall('token') }

        if self.TYPE == "scroll":
            xbmcplugin.setResolvedUrl(handle=self.handle, succeeded=False, listitem=xbmcgui.ListItem())
            containerId = self._get_view_mode()
            targetList = currentWindow.getControl(containerId)
            targetList.selectItem(int(self.pos))
            currentWindow.setFocus(targetList)
        elif self.path:
            xbmcplugin.setContent(self.handle, 'files')
            self._parse_files(sortLetterList, hasParentItem, ignoreArticles)
            xbmcplugin.addDirectoryItems(self.handle, sortLetterList)
            xbmcplugin.endOfDirectory(handle=self.handle)
        return
Esempio n. 10
0
    def LOAD_AND_PLAY_VIDEO(self, url, title, icon,year='',plot=''):
        progress = xbmcgui.DialogProgress()
        progress.create('Postęp', '')
        message = ptv.getLocalizedString(30406)
        progress.update( 10, "", message, "" )
        xbmc.sleep( 1000 )
        progress.update( 30, "", message, "" )
        progress.update( 50, "", message, "" )
        VideoLink = ''
        VideoLink = self.pp.getVideoLink(url)

        videoUrl = VideoLink
        progress.update( 70, "", message, "" )
        pluginhandle = int(sys.argv[1])
        if videoUrl == '':
            progress.close()
            d = xbmcgui.Dialog()
            d.ok('Nie znaleziono streamingu', 'Mo�e to chwilowa awaria.', 'Spr�buj ponownie za jaki� czas')
            return False
        if icon == '' or  icon == 'None':
            icon = "DefaultVideo.png"
        if plot == '' or plot == 'None':
            plot = ''
        liz=xbmcgui.ListItem(title, iconImage=icon, thumbnailImage=icon, path=videoUrl )
        liz.setInfo( type="video", infoLabels={ "Title": title} )
        xbmcPlayer = xbmc.Player()

        progress.update( 90, "", message, "" )
        progress.close()
        #listitem = xbmcgui.ListItem(path=videoUrl)
        xbmcplugin.setResolvedUrl(int(sys.argv[1]), True, liz)
def GET_VIDEO_FILE(name, url):
	url="http://www.panet.co.il/Ext/vplayer_lib.php?media="+str(url)+'&start=false'
	req = urllib2.Request(url)
	req.add_header('User-Agent', 'Mozilla/5.0 (Windows; U; Windows NT 5.1; en-GB; rv:1.9.0.3) Gecko/2008092417 Firefox/3.0.3')
	req.add_header('Host',' fms-eu0.panet.co.il')
	req.add_header('Accept',' text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8')
	req.add_header('Accept-Language',' en-US,en;q=0.5')
	req.add_header('Accept-Encoding', 'deflate')
	req.add_header('Referer',' http://www.panet.co.il/Ext/players/flv5/player.swf')
	req.add_header('Cookie',' __auc=82d7ffe213cb1b4ce1d273c7ba1; __utma=31848767.848342890.1360191082.1360611183.1360620657.4; __utmz=31848767.1360191082.1.1.utmcsr=(direct)|utmccn=(direct)|utmcmd=(none); __utmb=31848767.4.10.1360620660; __utmc=31848767; __asc=169c084d13ccb4fa36df421055e')
	req.add_header('Connection',' keep-alive')
	response = urllib2.urlopen(req)
	link=response.read()
	response.close()
	match_url_thumb=(re.compile('<link rel="video_src" href="(.+?)"/>').findall(link))
	match_url_thumb=str(match_url_thumb).replace("['", "")
	match_url_thumb=str(match_url_thumb).replace("']", "").strip()
	match_url_thumb=match_url_thumb.replace('%3A',':')
	match_url_thumb=match_url_thumb.replace('%2F','/')
	match_url_thumb=match_url_thumb.replace('http://','')
	match_url_thumb=match_url_thumb.replace('file=','file=http://')
	match_url_thumb=match_url_thumb.replace("www.panet.co.il/Ext/players/flv/playern.swf?type=http&streamer=start&file=","")
	match_url_thumb=match_url_thumb+'|Referer=http://www.panet.co.il/Ext/players/flv5/player.swf'
	listItem = xbmcgui.ListItem(path=str(match_url_thumb))
	xbmcplugin.setResolvedUrl(_thisPlugin, True, listItem)
Esempio n. 12
0
def resolve_url(url):
    content = make_request(url)
    if "chiasenhac" in url:
        try:
            media_url = (
                re.compile('"hd-2".+?"([^"]+)"')
                .findall(content)[0]
                .replace("%3A", ":")
                .replace("%2F", "/")
                .replace("%2520", "%20")
            )
        except:
            media_url = (
                re.compile('"file".*?"([^"]*)"')
                .findall(content)[-1]
                .replace("%3A", ":")
                .replace("%2F", "/")
                .replace("%2520", "%20")
            )
    elif "nhaccuatui" in url:
        media_url = re.compile('title=".+?" href="([^"]*)"').findall(content)[0]
    elif "timkaraoke" in url:
        media_url = re.compile('source src="(.+?)"').findall(content)[0].replace(" ", "%20")
    elif "thuynga" in url:
        media_url = re.compile("var iosUrl = '(.+?)'").findall(content)[0]
    else:
        media_url = url
    item = xbmcgui.ListItem(name, path=media_url)
    xbmcplugin.setResolvedUrl(int(sys.argv[1]), True, item)
    return
Esempio n. 13
0
def play(params):
    referer = urllib.unquote_plus(params['referer'])
    file = urllib.unquote_plus(params['file'])
    headers['Referer'] = referer

    i = xbmcgui.ListItem(path=getFile(file))
    xbmcplugin.setResolvedUrl(h, True, i)
Esempio n. 14
0
def BGPlayvid(url, name, download=None):
    videopage = utils.getHtml2(url)
    videopage = json.loads(videopage)
    
    if not videopage["240p"] == None:
        url = videopage["240p"].encode("utf8")
    if not videopage["480p"] == None:
        url = videopage["480p"].encode("utf8")
    if not videopage["720p"] == None:
        url = videopage["720p"].encode("utf8")

    url = url.replace("{DATA_MARKERS}","data=pc.XX")
    if not url.startswith("http:"): url = "http:" + url
    videourl = url

    if download == 1:
        utils.downloadVideo(videourl, name)
    else:
        iconimage = xbmc.getInfoImage("ListItem.Thumb")
        listitem = xbmcgui.ListItem(name, iconImage="DefaultVideo.png", thumbnailImage=iconimage)
        listitem.setInfo('video', {'Title': name, 'Genre': 'P**n'})
        listitem.setProperty("IsPlayable","true")
        if int(sys.argv[1]) == -1:
            pl = xbmc.PlayList(xbmc.PLAYLIST_VIDEO)
            pl.clear()
            pl.add(videourl, listitem)
            xbmc.Player().play(pl)
        else:
            listitem.setPath(str(videourl))
            xbmcplugin.setResolvedUrl(utils.addon_handle, True, listitem)
Esempio n. 15
0
def playVideo(url):
    global quality
    try:
        if ',sesamstrasse' in url:
            regex_suffix_id = ',sesamstrasse(.+?).html'
            try: suffix_id = re.findall(regex_suffix_id, url)[0]
            except: suffix_id = '3000'
        else: suffix_id = '3000'
        content = opener.open(url).read()
        json_uuid = re.findall('player_image-(.+?)_', content)[0]
        json_url = 'http://www.sesamstrasse.de/sendungsinfos/sesamstrasse%s-ppjson_image-%s.json' % (suffix_id, json_uuid)
        json = opener.open(json_url).read()
        regex_qualities = '\.,(.+?),\.'
        qualities = re.findall(regex_qualities, json)[-1].split(',')
        if not (quality in qualities): quality = qualities[-1]
        regex_url = '"src": "http://(.+?)"'
        urls = re.findall(regex_url, json)
        stream_url = ''
        for url in urls:
            if url.endswith('.mp4'):
                stream_url = 'http://' + url[:-6] + quality + '.mp4'
                break
        if not stream_url: return
    except: return
    listitem = xbmcgui.ListItem(path=stream_url)
    xbmcplugin.setResolvedUrl(pluginhandle, True, listitem)
def PlayStream(name, url, iconimage, description, subtitles_url):
    if iconimage == '':
        iconimage = 'DefaultVideo.png'
    html = OpenURL(url)
    check_geo = re.search(
        '<H1>Access Denied</H1>', html)
    if check_geo or not html:
        # print "Geoblock detected, raising error message"
        dialog = xbmcgui.Dialog()
        dialog.ok(translation(30400), translation(30401))
        raise
    liz = xbmcgui.ListItem(name, iconImage='DefaultVideo.png', thumbnailImage=iconimage)
    liz.setInfo(type='Video', infoLabels={'Title': name})
    liz.setProperty("IsPlayable", "true")
    liz.setPath(url)
    if subtitles_url and ADDON.getSetting('subtitles') == 'true':
        subtitles_file = download_subtitles(subtitles_url)
    xbmcplugin.setResolvedUrl(int(sys.argv[1]), True, liz)
    if subtitles_url and ADDON.getSetting('subtitles') == 'true':
        # Successfully started playing something?
        while True:
            if xbmc.Player().isPlaying():
                break
            else:
                xbmc.sleep(500)
        xbmc.Player().setSubtitles(subtitles_file)
Esempio n. 17
0
def add_streams(streams, name=None, logo=None):
    log_debug('add_streams', 2)
    log_debug('streams: %s' % streams, 3)
    log_debug('name: %s' % name, 3)
    log_debug('logo: %s' % logo, 3)

    pDialog = xbmcgui.DialogProgress()
    pDialog.create(__addonname__, 'Creating playlist')
    playlist = xbmc.PlayList(xbmc.PLAYLIST_MUSIC)
    playlist.clear()
    for count, stream in enumerate(streams):
        log_debug('Adding stream %s to playlist.' % stream, 1)
        pDialog.update(50, 'Adding stream %d of %d to playlist' % (count + 1, len(streams)), stream)

        if name:
            liz = xbmcgui.ListItem(name, iconImage=logo, thumbnailImage=logo)
            liz.setInfo('music', {'Title': name})
            playlist.add(url=stream, listitem=liz)
        else:
            playlist.add(url=stream)
    pDialog.close()
    if len(playlist) > 0:
        xbmcplugin.setResolvedUrl(handle=int(__settings__.get_argv(1)), succeeded=True, listitem=playlist[0])
    else:
        xbmcplugin.setResolvedUrl(handle=int(__settings__.get_argv(1)), succeeded=False, listitem=None)
Esempio n. 18
0
def _json(url):
    with closing(urllib2.urlopen(url)) as response:
        if response.code >= 300 and response.code <= 307:
            item = xbmcgui.ListItem(
                path=response.geturl(),
                label=xbmc.getInfoLabel("ListItem.Label"),
                label2=xbmc.getInfoLabel("ListItem.label2"),
                thumbnailImage=xbmc.getInfoLabel("ListItem.Art(thumb)"))
            _infoLabels = {
                "Title": xbmc.getInfoLabel("ListItem.Title"),
                "OriginalTitle": xbmc.getInfoLabel("ListItem.OriginalTitle"),
                "TVShowTitle": xbmc.getInfoLabel("ListItem.TVShowTitle"),
                "Season": xbmc.getInfoLabel("ListItem.Season"),
                "Episode": xbmc.getInfoLabel("ListItem.Episode"),
                # "Date": xbmc.getInfoLabel("ListItem.Date"),
                "VideoCodec": xbmc.getInfoLabel("ListItem.VideoCodec"),
                "VideoResolution": xbmc.getInfoLabel("ListItem.VideoResolution"),
                "VideoAspect": xbmc.getInfoLabel("ListItem.VideoAspect"),
                "DBID": xbmc.getInfoLabel("ListItem.DBID"),
                "DBTYPE": xbmc.getInfoLabel("ListItem.DBTYPE"),
            }
            infoLabels = {}
            for key, value in _infoLabels.iteritems():
                if value:
                    infoLabels[key] = value

            item.setInfo(type='Video', infoLabels=infoLabels)
            xbmcplugin.setResolvedUrl(HANDLE, True, item)
            return

        payload = response.read()

        if payload:
            return json.loads(payload)
def play(url):
    try:
        videoId = getVideoLink(url)
        listitem = xbmcgui.ListItem(name,iconImage='DefaultVideo.png',thumbnailImage=iconimage)
        listitem.setPath(videoId)
        xbmcplugin.setResolvedUrl(int(sys.argv[1]), True, listitem)
    except:pass
def GETMULTI(name,url,iconimage):
        streamurl=[]
        streamname=[]
        streamicon=[]
        link=open_url(url)
        link=re.sub(r'\(.*\)', '', link)
        name=re.sub(r'\(.*\)', '', name)
        urls=re.compile('<item>.+?<title>'+name+'</title>(.+?)</item>',re.DOTALL).findall(link)[0]
        iconimage=re.compile('<thumbnail>(.+?)</thumbnail>').findall(urls)[0]
        links=re.compile('<link>(.+?)</link>').findall(urls)
        i=1
        for sturl in links:
                streamurl.append( sturl )
                streamname.append( 'Link '+str(i) )
                dialog = xbmcgui.Dialog()
                i=i+1
        select = dialog.select(name,streamname)
        if select == -1:
                quit()
        else:
                url = streamurl[select]
                ok=True
                liz=xbmcgui.ListItem(name, iconImage=iconimage,thumbnailImage=iconimage); liz.setInfo( type="Video", infoLabels={ "Title": name } )
                ok=xbmcplugin.addDirectoryItem(handle=int(sys.argv[1]),url=url,listitem=liz)
                liz.setPath(url)
                xbmcplugin.setResolvedUrl(int(sys.argv[1]), True, liz)
Esempio n. 21
0
def gozlan_play_video(url):
	try:
		url = GetMediaUrl(url)
		url = urlresolver.HostedMediaFile(url=url).resolve()
		if not url or len(url) < 1:
			raise
	except:
		print "Cannot play {0}.".format(url)
		xbmc.executebuiltin('Notification({0}, {1}, {2}, {3})'.format(__plugin__,  "Cannot play this source.", 5000, __icon__))
		return
	
	
	print "Playing {0}.".format(url)
	name = url
	if ("name" in params):
		name=params["name"]
	image=""
	if ("image" in params):
		image=params["image"]
	description=""
	if "description" in params:  
		description=params["description"]

	listItem = xbmcgui.ListItem(name, image, image, path=url)
	listItem.setInfo(type='Video', infoLabels={ "Title": name})
	listItem.setProperty('IsPlayable', 'true')
	xbmcplugin.setResolvedUrl(handle=int(sys.argv[1]), succeeded=True, listitem=listItem)
Esempio n. 22
0
def PLAY(name,url):
	listitem = xbmcgui.ListItem(path=url)
	xbmc.log('### SETRESOLVEDURL ###')
	listitem.setProperty('IsPlayable', 'true')
	xbmcplugin.setResolvedUrl(int(sys.argv[1]), True, listitem)
	xbmc.log('URL: ' + str(url), level=xbmc.LOGDEBUG)
	xbmcplugin.endOfDirectory(addon_handle)
Esempio n. 23
0
def set_resolved_url(stream_url, subtitle_url):
	h1 = '|User-Agent=' + urllib.quote_plus('HDViet/2.0.1 CFNetwork/711.2.23 Darwin/14.0.0')
	h2 = '&Accept=' + urllib.quote_plus('*/*')
	xbmcplugin.setResolvedUrl(addon_handle, succeeded=True, listitem=xbmcgui.ListItem(label = '', path = stream_url))
	
	datapath=xbmc.translatePath(xbmcaddon.Addon().getAddonInfo('profile')).decode("utf-8")
	subtitlePath = os.path.join(datapath,'subs')
	try:
		if subtitle_url != '':
			sublink = subtitle_url.split('/')
			subfile = os.path.join(subtitlePath, sublink[len(sublink)-1])
			if not os.path.exists(subtitlePath):os.mkdir(subtitlePath)
			for file in os.listdir(subtitlePath):
				if os.path.isfile(os.path.join(subtitlePath,file)):
					try:os.remove(os.path.join(subtitlePath,file))
					except:pass
			f = urllib2.urlopen(subtitle_url)
			with open(subfile, "wb") as code:
				code.write(f.read())
			xbmc.sleep(1000)
			timeout = 0
			while not xbmc.Player().isPlaying() and timeout < 60:
				xbmc.sleep(500)
				timeout += 1
			if timeout < 60:
				xbmc.Player().setSubtitles(subfile)
				xbmc.executebuiltin((u'XBMC.Notification(%s,%s,%s)'%('HDViet','[COLOR green]Subtitle Loaded ![/COLOR]',2000)).encode("utf-8"))
			else:xbmc.executebuiltin((u'XBMC.Notification(%s,%s,%s)'%('HDViet','[COLOR red]Connection timed out ![/COLOR]',2000)).encode("utf-8"))
	except:
		pass
Esempio n. 24
0
def play_video(url):

	if 'parser.php?surl=' in url: # case for cCloudTv redirecting parser
		try:
			#print 'URL: ' + str(url)
			if '|' in url:
				urls = url.split('|')
				rurl = str(urls[0])
				purl = urls[1]
			else:
				rurl = url
			req = urllib2.Request(rurl)
			res = urllib2.urlopen(req)
			furl = res.geturl()
			if '|' in url:
				url = furl + '|' + purl
			else:
				url = furl
			#print 'RedirectorURL: ' + str(url)
		except:
			pass
			
	media_url = url
	item = xbmcgui.ListItem(name, path = media_url)
	xbmcplugin.setResolvedUrl(int(sys.argv[1]), True, item)
	return
Esempio n. 25
0
def playvideo(param): # Gets the stream from the selected video and plays it
    try:
        stream = gethighspotsstreamurl(param)
        listitem = xbmcgui.ListItem(path=stream)
        xbmcplugin.setResolvedUrl(pluginhandle, True, listitem)
    except:
        xbmcgui.Dialog().ok('Highspots.TV', 'Highspots.TV subscribers you will need to purchase access to view this event.')
Esempio n. 26
0
def playItem(vodItemURL, vodItemId):
    # obtain a ticket for the video item
    ticketLoader = MakoTicketLoader.MakoTicketLoader(__properties, vodItemURL, vodItemId)
    ticketLoader.loadURL()
    urlEncodedTicket = ticketLoader.getTicket()
    if urlEncodedTicket == '':
        xbmc.log('***** Mako: unable to find ticket for vod item %s' % vodItemURL, xbmc.LOGERROR)
    else:
        # create final URL
	_url = vodItemURL
	if _url.find('?') == -1:
	    _url = _url + '?' + urlEncodedTicket
	else:
	    _url = _url + '&' + urlEncodedTicket
	xbmc.log('***** Mako: final video URL with ticket: %s' % _url, xbmc.LOGDEBUG)
	title = ''
	summary = ''
	thumbnail = ''

        # falsify a user agent
        _user_agent = '|User-Agent=' + urllib.quote_plus('stagefright/1.2 (Linux; Android 4.2.2)')
        _acceptHeader = '&Accept-Language=en-US'

        listItem = xbmcgui.ListItem(title, iconImage = thumbnail, thumbnailImage = thumbnail, path=_url + _user_agent + _acceptHeader)
        listItem.setInfo(type='Video', infoLabels={ "Title": urllib.unquote(title), "Plot": urllib.unquote(summary)})
        listItem.setProperty('IsPlayable', 'true')

        # Gotham properly probes the mime type
        xbmcplugin.setResolvedUrl(handle=int(sys.argv[1]), succeeded=True, listitem=listItem)
Esempio n. 27
0
def resolveUrl(url):
  if 'fptplay' in url:
    req=urllib2.Request(url)
    req.add_header('User-Agent', 'Mozilla/5.0 (Windows NT 6.1; WOW64; rv:19.0) Gecko/20100101 Firefox/19.0')
    req.add_header('Referer', fptplay)	
    response=urllib2.urlopen(req)
    link=response.read()
    response.close()
    mediaUrl='plugin://plugin.video.f4mTester/?url='+re.compile('"adapt_hds": "(.+?)"').findall(link)[0]
  elif 'htvonline' in url:
    content=makeRequest(url)
    mediaUrl=re.compile("file: \"([^\"]*)\"").findall(content)[0]
  elif 'hplus' in url:
    content=makeRequest(url)  
    mediaUrl=re.compile("var iosUrl = \"(.+?)\"").findall(content)[0]	
  elif 'tv24' in url:
    content=makeRequest(url)  
    videoUrl=re.compile('\'file\': \'http([^\']*)\/playlist.m3u8').findall(content)[0]
    mediaUrl='rtmpe' + videoUrl + ' swfUrl=http://tv24.vn/getflash.ashx pageUrl=http://tv24.vn/ ' + token   
  elif 'zui' in url:
    content=makeRequest(url)  
    mediaUrl=re.compile('livetv_play\(\'player\', \'1\', \'(.+?)\'\)').findall(content)[0]	
  elif 'wezatv' in url or 'giniko' in url:
    content=makeRequest(url)  
    mediaUrl=re.compile('file: "(.+?)"').findall(content)[0]  
  else:
    mediaUrl=url  
  item=xbmcgui.ListItem(path=mediaUrl)
  xbmcplugin.setResolvedUrl(int(sys.argv[1]), True, item)	  
  return
Esempio n. 28
0
def PlayVideo(id):
    import xbmcgui
    import sys

    video, links = GetVideoInformation(id)

    if 'best' not in video:
        return False

    url   = video['best']          
    title = video['title']
    image = video['thumbnail']

    liz = xbmcgui.ListItem(title, iconImage=image, thumbnailImage=image)

    liz.setInfo( type="Video", infoLabels={ "Title": title} )
    liz.setProperty("IsPlayable","true")

    if int(sys.argv[1]) == -1:
        import xbmc
        pl = xbmc.PlayList(xbmc.PLAYLIST_VIDEO)
        pl.clear()
        pl.add(url, liz)
        xbmc.Player().play(pl)
    else:
        import xbmcplugin
        liz.setPath(url)
        xbmcplugin.setResolvedUrl(int(sys.argv[1]), True, liz)

    return True
Esempio n. 29
0
def gozlan_play_video(url):
    name = url
    if ("name" in params):
      name=params["name"]
    image=""
    if ("image" in params):
      image=params["image"]
    description=""
    if "description" in params:  
      description=params["description"]
    
    ''' page=getData(base_domain+"/"+url,7)
    # <iframe src="http://www.putlocker.com/embed/F4988CE321910D0D" id='iframeinner'
    regexp='<iframe src="http://anonymouse.org/cgi-bin/anon-www.cgi/(.*?)"'
    media_url=re.compile('iframe src="http://anonymouse.org/cgi-bin/anon-www.cgi/(.*?)"',re.M+re.I+re.S).findall(page)[0]
    #addDir('test',media_url,9)
    print "Resolving URL: " + media_url
    videoPlayListUrl = urlresolver.HostedMediaFile(url=media_url).resolve()
    if not videoPlayListUrl:
      print "URL " + media_url + " could not have been resolved to a movie.\n"
      return'''
    #addon.resolve_url(stream_url)
    #videoPlayListUrl = urllib.unquote(videoUrl[0])
    listItem = xbmcgui.ListItem(name, image, image, path=url) # + '|' + 'Mozilla/5.0 (Windows; U; Windows NT 5.1; en-GB; rv:1.9.0.3) Gecko/2008092417 Firefox/3.0.3')
    listItem.setInfo(type='Video', infoLabels={ "Title": name})
    listItem.setProperty('IsPlayable', 'true')
    print "video url " + url
    #xbmc.Player(xbmc.PLAYER_CORE_MPLAYER).play(videoPlayListUrl)
    xbmcplugin.setResolvedUrl(handle=int(sys.argv[1]), succeeded=True, listitem=listItem)
Esempio n. 30
0
def BGPlayvid(url, name, download=None):
    videopage = utils.getHtml(url, "")
    videopage = json.loads(videopage)

    if not videopage["240p"] == None:
        url = videopage["240p"].encode("utf8")
    if not videopage["480p"] == None:
        url = videopage["480p"].encode("utf8")
    if not videopage["720p"] == None:
        url = videopage["720p"].encode("utf8")

    url = url.replace("{DATA_MARKERS}", "data=pc.DE")
    if not url.startswith("http:"):
        url = "https:" + url

    key = re.compile("/key=(.*?)%2Cend", re.DOTALL | re.IGNORECASE).findall(url)[0]
    decryptedkey = decrypt_key(key)

    videourl = url.replace(key, decryptedkey)

    if download == 1:
        utils.downloadVideo(videourl, name)
    else:
        iconimage = xbmc.getInfoImage("ListItem.Thumb")
        listitem = xbmcgui.ListItem(name, iconImage="DefaultVideo.png", thumbnailImage=iconimage)
        listitem.setInfo("video", {"Title": name, "Genre": "P**n"})
        listitem.setProperty("IsPlayable", "true")
        if int(sys.argv[1]) == -1:
            pl = xbmc.PlayList(xbmc.PLAYLIST_VIDEO)
            pl.clear()
            pl.add(videourl, listitem)
            xbmc.Player().play(pl)
        else:
            listitem.setPath(str(videourl))
            xbmcplugin.setResolvedUrl(utils.addon_handle, True, listitem)
Esempio n. 31
0
def set_player(item, xlistitem, mediaurl, view, strm):
    logger.info()
    logger.debug("item:\n" + item.tostring('\n'))

    # Movido del conector "torrent" aqui
    if item.server == "torrent":
        play_torrent(item, xlistitem, mediaurl)
        return

    # Si es un fichero strm no hace falta el play
    elif strm:
        xbmcplugin.setResolvedUrl(int(sys.argv[1]), True, xlistitem)
        if item.subtitle != "":
            xbmc.sleep(2000)
            xbmc.Player().setSubtitles(item.subtitle)

    else:
        logger.info("player_mode=%s" % config.get_setting("player_mode"))
        logger.info("mediaurl=" + mediaurl)
        if config.get_setting(
                "player_mode") == 3 or "megacrypter.com" in mediaurl:
            import download_and_play
            download_and_play.download_and_play(
                mediaurl, "download_and_play.tmp",
                config.get_setting("downloadpath"))
            return

        elif config.get_setting("player_mode") == 0 or \
                (config.get_setting("player_mode") == 3 and mediaurl.startswith("rtmp")):
            # Añadimos el listitem a una lista de reproducción (playlist)
            playlist = xbmc.PlayList(xbmc.PLAYLIST_VIDEO)
            playlist.clear()
            playlist.add(mediaurl, xlistitem)

            # Reproduce
            playersettings = config.get_setting('player_type')
            logger.info("playersettings=%s" % playersettings)

            if config.get_system_platform() == "xbox":
                player_type = xbmc.PLAYER_CORE_AUTO
                if playersettings == 0:
                    player_type = xbmc.PLAYER_CORE_AUTO
                    logger.debug("PLAYER_CORE_AUTO")
                elif playersettings == 1:
                    player_type = xbmc.PLAYER_CORE_MPLAYER
                    logger.debug("PLAYER_CORE_MPLAYER")
                elif playersettings == 2:
                    player_type = xbmc.PLAYER_CORE_DVDPLAYER
                    logger.debug("PLAYER_CORE_DVDPLAYER")

                xbmc_player = xbmc.Player(player_type)
            else:
                xbmc_player = xbmc.Player()

            xbmc_player.play(playlist, xlistitem)

        elif config.get_setting("player_mode") == 1:
            logger.info("mediaurl :" + mediaurl)
            logger.info("Tras setResolvedUrl")
            xbmcplugin.setResolvedUrl(int(sys.argv[1]), True,
                                      xbmcgui.ListItem(path=mediaurl))

        elif config.get_setting("player_mode") == 2:
            xbmc.executebuiltin("PlayMedia(" + mediaurl + ")")

    # TODO MIRAR DE QUITAR VIEW
    if item.subtitle != "" and view:
        logger.info("Subtítulos externos: " + item.subtitle)
        xbmc.sleep(2000)
        xbmc.Player().setSubtitles(item.subtitle)

    # si es un archivo de la biblioteca enviar a marcar como visto
    if strm or item.strm_path:
        from platformcode import xbmc_library
        xbmc_library.mark_auto_as_watched(item)
Esempio n. 32
0
def PlayUrl(name, url, iconimage=None):
    print '--- Playing "{0}". {1}'.format(name, url)
    listitem = xbmcgui.ListItem(path=url, thumbnailImage=iconimage)
    listitem.setInfo(type="Video", infoLabels={"Title": name})
    xbmcplugin.setResolvedUrl(int(sys.argv[1]), True, listitem)
Esempio n. 33
0
def play_video(provider, context):
    try:
        video_id = context.get_param('video_id')

        client = provider.get_client(context)
        settings = context.get_settings()

        ask_for_quality = None
        if video_id and context.get_ui().get_home_window_property('ask_for_quality') == video_id:
            ask_for_quality = True
        context.get_ui().clear_home_window_property('ask_for_quality')

        screensaver = False
        if context.get_param('screensaver', None) and str(context.get_param('screensaver')).lower() == 'true':
            ask_for_quality = False
            screensaver = True

        audio_only = None
        if video_id and context.get_ui().get_home_window_property('audio_only') == video_id:
            ask_for_quality = False
            audio_only = True
        context.get_ui().clear_home_window_property('audio_only')

        try:
            video_streams = client.get_video_streams(context, video_id)
        except YouTubeException as e:
            context.get_ui().show_notification(message=e.get_message())
            context.log_error(traceback.print_exc())
            return False

        if len(video_streams) == 0:
            message = context.localize(provider.LOCAL_MAP['youtube.error.no_video_streams_found'])
            context.get_ui().show_notification(message, time_milliseconds=5000)
            return False

        video_stream = kodion.utils.select_stream(context, video_streams, ask_for_quality=ask_for_quality, audio_only=audio_only)

        if video_stream is None:
            return False

        is_video = True if video_stream.get('video') else False
        is_live = video_stream.get('Live') is True

        if is_video and video_stream['video'].get('rtmpe', False):
            message = context.localize(provider.LOCAL_MAP['youtube.error.rtmpe_not_supported'])
            context.get_ui().show_notification(message, time_milliseconds=5000)
            return False

        play_suggested = settings.get_bool('youtube.suggested_videos', False)
        if play_suggested and not screensaver:
            utils.add_related_video_to_playlist(provider, context, client, v3, video_id)

        metadata = video_stream.get('meta', {})

        title = metadata.get('video', {}).get('title', '')
        video_item = VideoItem(title, video_stream['url'])

        incognito = str(context.get_param('incognito', False)).lower() == 'true'
        use_history = not is_live and not screensaver and not incognito
        playback_history = use_history and settings.use_playback_history()

        video_item = utils.update_play_info(provider, context, video_id, video_item, video_stream,
                                            use_play_data=playback_history)

        seek_time = None
        play_count = 0
        playback_stats = video_stream.get('playback_stats')

        if use_history:
            major_version = context.get_system_version().get_version()[0]
            if video_item.get_start_time() and video_item.use_dash() and major_version > 17:
                seek_time = video_item.get_start_time()
            play_count = video_item.get_play_count() if video_item.get_play_count() is not None else '0'

        item = to_playback_item(context, video_item)
        item.setPath(video_item.get_uri())

        try:
            seek = float(context.get_param('seek', None))
            if seek:
                seek_time = seek
        except (ValueError, TypeError):
            pass

        playback_json = {
            "video_id": video_id,
            "channel_id": metadata.get('channel', {}).get('id', ''),
            "video_status": metadata.get('video', {}).get('status', {}),
            "playing_file": video_item.get_uri(),
            "play_count": play_count,
            "use_history": use_history,
            "playback_history": playback_history,
            "playback_stats": playback_stats,
            "seek_time": seek_time,
            "refresh_only": screensaver
        }

        context.get_ui().set_home_window_property('playback_json', json.dumps(playback_json))
        context.send_notification('PlaybackInit', {
            'video_id': video_id,
            'channel_id': playback_json.get('channel_id', ''),
            'status': playback_json.get('video_status', {})
        })
        xbmcplugin.setResolvedUrl(handle=context.get_handle(), succeeded=True, listitem=item)

    except YouTubeException as ex:
        message = ex.get_message()
        message = kodion.utils.strip_html_from_text(message)
        context.get_ui().show_notification(message, time_milliseconds=15000)
Esempio n. 34
0
    #android.cat()
    xbmc.executebuiltin('ActivateWindow(10025,"plugin://plugin.video.exodus/?action=tvNavigator",return)')
    
elif mode==5006:
    #from resources.root import android
    #android.cat()
    xbmc.executebuiltin('ActivateWindow(10025,"plugin://script.module.streamhublive/?description&iconimage=http%3a%2f%2fwww.broadbandtvnews.com%2fwp-content%2fuploads%2f2017%2f04%2fTVPlayer.png&mode=1&name=%5bCOLOR%20white%5d%5bB%5dTv%20Player%5b%2fCOLOR%5d%5b%2fB%5d&url=tvplayer",return)')

elif mode==5007:
    #from resources.root import android
    #android.cat()
    xbmc.executebuiltin('ActivateWindow(10025,"plugin://plugin.video.showboxarize2/?action=movieNavigator",return)')
    
elif mode==5008:
    #from resources.root import android
    #android.cat()
    xbmc.executebuiltin('ActivateWindow(10025,"plugin://plugin.video.showboxarize2/?action=tvNavigator",return)')
    
elif mode==9999:
    import xbmcgui,xbmcplugin
    from resources.modules import resolvers
    url = resolvers.resolve(url)
    liz = xbmcgui.ListItem(name, iconImage=iconimage, thumbnailImage=iconimage)
    liz.setInfo(type='Video', infoLabels='')
    liz.setProperty("IsPlayable","true")
    liz.setPath(url)
    xbmcplugin.setResolvedUrl(int(sys.argv[1]), True, liz)
    

import xbmcplugin
xbmcplugin.endOfDirectory(int(sys.argv[1]))
Esempio n. 35
0
def playVideo(url):
    debug(
        "(playVideo) ------------------------------------------------ START = playVideo -----------------------------------------------"
    )
    # Übergabe des Abspiellinks von anderem Video-ADDON: plugin://plugin.video.tyl0re.arte/?mode=playVideo&url=048256-000-A oder: plugin://plugin.video.tyl0re.arte/?mode=playVideo&url=https://www.arte.tv/de/videos/048256-000-A/wir-waren-koenige/
    DATA = {}
    DATA['media'] = []
    finalURL = False
    try:
        if url[:4] == "http":
            idd = re.compile('/videos/(.+?)/', re.DOTALL).findall(url)[0]
        else:
            idd = url
        debug("----->")
        debug("(playVideo) ### IDD : {0} ###".format(str(idd)))
        if COUNTRY == "de":
            SHORTCUTS = [
                'DE', 'OmU', 'OV', 'VO'
            ]  # "DE" = Original deutsch | "OmU" = Original mit deutschen Untertiteln | "OV" = Stumm oder Originalversion
        elif COUNTRY == "fr":
            SHORTCUTS = [
                'VOF', 'VF', 'VOSTF', 'VO'
            ]  # "VOF" = Original französisch | "VF" = französisch vertont | "VOSTF" = Stumm oder Original mit französischen Untertiteln
        content = getUrl(
            'https://api.arte.tv/api/player/v1/config/' + COUNTRY + '/' +
            str(idd) + '?autostart=0&lifeCycle=1', 'GET', False, False, False,
            __HEADERS)
        stream = json.loads(content)['videoJsonPlayer']
        stream_offer = stream['VSR']
        for element in stream_offer:
            if int(
                    stream['VSR'][element]['versionProg']
            ) == 1 and stream['VSR'][element]['mediaType'].lower() == "mp4":
                debug("(playVideo) ### Stream-Element : {0} ###".format(
                    str(stream['VSR'][element])))
                for found in SHORTCUTS:
                    if stream['VSR'][element][
                            'versionShortLibelle'] == found and stream['VSR'][
                                element]['height'] == prefQUALITY:
                        DATA['media'].append(
                            {'streamURL': stream['VSR'][element]['url']})
                        finalURL = DATA['media'][0]['streamURL']
                if not finalURL:
                    if stream['VSR'][element]['height'] == prefQUALITY:
                        finalURL = stream['VSR'][element]['url']
        debug("(playVideo) ### Quality-Setting : {0} ###".format(
            str(prefQUALITY)))
        log("(playVideo) StreamURL : {0}".format(str(finalURL)))
        debug("<-----")
        if finalURL:
            listitem = xbmcgui.ListItem(path=finalURL)
            listitem.setContentLookup(False)
            xbmcplugin.setResolvedUrl(pluginhandle, True, listitem)
        else:
            xbmcgui.Dialog().notification(
                addon.getAddonInfo('id') +
                " : [COLOR red]!!! STREAM - URL - ERROR !!![/COLOR]",
                "ERROR = [COLOR red]KEINE passende *Stream-Url* auf ARTE gefunden ![/COLOR]",
                xbmcgui.NOTIFICATION_ERROR, 6000)
    except:
        xbmcgui.Dialog().notification(
            addon.getAddonInfo('id') +
            " : [COLOR red]!!! VIDEO - URL - ERROR !!![/COLOR]",
            "ERROR = [COLOR red]Der übertragene *Video-Abspiel-Link* ist FEHLERHAFT ![/COLOR]",
            xbmcgui.NOTIFICATION_ERROR, 6000)
Esempio n. 36
0
 def LinkPlay(self, name, url):
     listitem = xbmcgui.ListItem(name, path=url)
     xbmcplugin.setResolvedUrl(int(sys.argv[1]), True, listitem)
Esempio n. 37
0
def play_resolved_url(url):
    _log("play_resolved_url [" + url + "]")

    listitem = xbmcgui.ListItem(path=url)
    listitem.setProperty('IsPlayable', 'true')
    return xbmcplugin.setResolvedUrl(int(sys.argv[1]), True, listitem)
Esempio n. 38
0
def play_youtube(id):
    url = 'plugin://plugin.video.youtube/play/?video_id=%s' % id
    item = xbmcgui.ListItem(path=url)
    xbmcplugin.setResolvedUrl(int(sys.argv[1]), True, item)
Esempio n. 39
0
    def play_item(self, esn, video_id, start_offset=-1, infoLabels={}):
        """Plays a video

        Parameters
        ----------
        esn : :obj:`str`
            ESN needed for Widevine/Inputstream

        video_id : :obj:`str`
            ID of the video that should be played

        start_offset : :obj:`str`
            Offset to resume playback from (in seconds)
        
        infoLabels : :obj:`str`
            the listitem's infoLabels

        Returns
        -------
        bool
            List could be build
        """
        self.set_esn(esn)
        addon = self.get_addon()
        inputstream_addon = self.get_inputstream_addon()
        if inputstream_addon == None:
            self.show_missing_inputstream_addon_notification()
            self.log(msg='Inputstream addon not found')
            return False

        # track play event
        self.track_event('playVideo')

        # check esn in settings
        settings_esn = str(addon.getSetting('esn'))
        if len(settings_esn) == 0:
            addon.setSetting('esn', str(esn))

        # inputstream addon properties
        msl_service_url = 'http://localhost:' + str(
            addon.getSetting('msl_service_port'))
        play_item = xbmcgui.ListItem(path=msl_service_url + '/manifest?id=' +
                                     video_id)
        play_item.setContentLookup(False)
        play_item.setMimeType('application/dash+xml')
        play_item.setProperty(
            inputstream_addon + '.stream_headers',
            'user-agent=' + get_user_agent_for_current_platform())
        play_item.setProperty(inputstream_addon + '.license_type',
                              'com.widevine.alpha')
        play_item.setProperty(inputstream_addon + '.manifest_type', 'mpd')
        play_item.setProperty(
            inputstream_addon + '.license_key',
            msl_service_url + '/license?id=' + video_id + '||b{SSM}!b{SID}|')
        play_item.setProperty(
            inputstream_addon + '.server_certificate',
            'Cr0CCAMSEOVEukALwQ8307Y2+LVP+0MYh/HPkwUijgIwggEKAoIBAQDm875btoWUbGqQD8eAGuBlGY+Pxo8YF1LQR+Ex0pDONMet8EHslcZRBKNQ/09RZFTP0vrYimyYiBmk9GG+S0wB3CRITgweNE15cD33MQYyS3zpBd4z+sCJam2+jj1ZA4uijE2dxGC+gRBRnw9WoPyw7D8RuhGSJ95OEtzg3Ho+mEsxuE5xg9LM4+Zuro/9msz2bFgJUjQUVHo5j+k4qLWu4ObugFmc9DLIAohL58UR5k0XnvizulOHbMMxdzna9lwTw/4SALadEV/CZXBmswUtBgATDKNqjXwokohncpdsWSauH6vfS6FXwizQoZJ9TdjSGC60rUB2t+aYDm74cIuxAgMBAAE6EHRlc3QubmV0ZmxpeC5jb20SgAOE0y8yWw2Win6M2/bw7+aqVuQPwzS/YG5ySYvwCGQd0Dltr3hpik98WijUODUr6PxMn1ZYXOLo3eED6xYGM7Riza8XskRdCfF8xjj7L7/THPbixyn4mULsttSmWFhexzXnSeKqQHuoKmerqu0nu39iW3pcxDV/K7E6aaSr5ID0SCi7KRcL9BCUCz1g9c43sNj46BhMCWJSm0mx1XFDcoKZWhpj5FAgU4Q4e6f+S8eX39nf6D6SJRb4ap7Znzn7preIvmS93xWjm75I6UBVQGo6pn4qWNCgLYlGGCQCUm5tg566j+/g5jvYZkTJvbiZFwtjMW5njbSRwB3W4CrKoyxw4qsJNSaZRTKAvSjTKdqVDXV/U5HK7SaBA6iJ981/aforXbd2vZlRXO/2S+Maa2mHULzsD+S5l4/YGpSt7PnkCe25F+nAovtl/ogZgjMeEdFyd/9YMYjOS4krYmwp3yJ7m9ZzYCQ6I8RQN4x/yLlHG5RH/+WNLNUs6JAZ0fFdCmw='
        )
        play_item.setProperty('inputstreamaddon', inputstream_addon)

        # check if we have a bookmark e.g. start offset position
        if int(start_offset) > 0:
            play_item.setProperty('StartOffset', str(start_offset) + '.0')
        # set infoLabels
        if len(infoLabels) > 0:
            play_item.setInfo('video', infoLabels)
        return xbmcplugin.setResolvedUrl(self.plugin_handle,
                                         True,
                                         listitem=play_item)
Esempio n. 40
0
def set_opcion(item, seleccion, opciones, video_urls):
    logger.info()
    # logger.debug(item.tostring('\n'))
    salir = False
    # No ha elegido nada, lo más probable porque haya dado al ESC
    # TODO revisar
    if seleccion == -1:
        # Para evitar el error "Uno o más elementos fallaron" al cancelar la selección desde fichero strm
        listitem = xbmcgui.ListItem(item.title,
                                    iconImage="DefaultVideo.png",
                                    thumbnailImage=item.thumbnail)
        xbmcplugin.setResolvedUrl(int(sys.argv[1]), False, listitem)

    # "Enviar a JDownloader"
    if opciones[seleccion] == config.get_localized_string(30158):
        from core import scrapertools

        # TODO comprobar que devuelve 'data'
        if item.subtitle != "":
            data = scrapertools.cachePage(
                config.get_setting("jdownloader") +
                "/action/add/links/grabber0/start1/web=" + item.url + " " +
                item.thumbnail + " " + item.subtitle)
        else:
            data = scrapertools.cachePage(
                config.get_setting("jdownloader") +
                "/action/add/links/grabber0/start1/web=" + item.url + " " +
                item.thumbnail)
        salir = True

    # "Descargar"
    elif opciones[seleccion] == config.get_localized_string(30153):
        from channels import descargas
        if item.contentType == "list" or item.contentType == "tvshow":
            item.contentType = "video"
        item.play_menu = True
        descargas.save_download(item)
        salir = True

    # "Quitar de favoritos"
    elif opciones[seleccion] == config.get_localized_string(30154):
        from channels import favoritos
        favoritos.delFavourite(item)
        salir = True

    # "Añadir a favoritos":
    elif opciones[seleccion] == config.get_localized_string(30155):
        from channels import favoritos
        item.from_channel = "favoritos"
        favoritos.addFavourite(item)
        salir = True

    # "Añadir a Biblioteca":  # Library
    elif opciones[seleccion] == config.get_localized_string(30161):
        titulo = item.fulltitle
        if titulo == "":
            titulo = item.title

        new_item = item.clone(title=titulo,
                              action="play_from_library",
                              category="Cine",
                              fulltitle=item.fulltitle,
                              channel=item.channel)

        from core import library
        library.add_pelicula_to_library(new_item)

        salir = True
Esempio n. 41
0
def VIDEO(url):
    urlogin = '******'
    cookiejar = cookielib.LWPCookieJar()
    cookiejar = urllib2.HTTPCookieProcessor(cookiejar)
    opener = urllib2.build_opener(cookiejar)
    urllib2.install_opener(opener)
    values = {
        'ref': 'http://veehd.com/',
        'uname': uname,
        'pword': pwd,
        'submit': 'Login',
        'terms': 'on'
    }
    user_agent = 'Mozilla/4.0 (compatible; MSIE 5.5; Windows NT)'
    headers = {'User-Agent': user_agent}
    data = urllib.urlencode(values)
    req = urllib2.Request(urlogin, data, headers)
    response = urllib2.urlopen(req)
    if url.find('flv') > 0:
        req = urllib2.Request(url)
        req.add_header(
            'User-Agent',
            'Mozilla/5.0 (Windows; U; Windows NT 5.1; en-GB; rv:1.9.0.3) Gecko/2008092417 Firefox/3.0.3'
        )
        response = urllib2.urlopen(req)
        link = response.read()
        vpi = re.compile('"/vpi.+?h=(.+?)"').findall(link)[0]
        req = urllib2.Request('http://veehd.com/vpi?h=' + vpi)
        req.add_header(
            'User-Agent',
            'Mozilla/5.0 (Windows; U; Windows NT 5.1; en-GB; rv:1.9.0.3) Gecko/2008092417 Firefox/3.0.3'
        )
        response = urllib2.urlopen(req)
        link = response.read()
        swap = re.compile('"url":"(.+?)"').findall(link)[0]
        finalurl = swap.replace('%2F', '/').replace('%3F', '?').replace(
            '%3D',
            '=').replace('%25',
                         '%').replace('%2F',
                                      '/').replace('%26',
                                                   '&').replace('%3A', ':')
        if (vhd.getSetting('download') == '0'):
            dia = xbmcgui.Dialog()
            ret = dia.select('Streaming Options', ['Play', 'Download'])
            if (ret == 0):
                item = xbmcgui.ListItem(path=finalurl)
                xbmcplugin.setResolvedUrl(pluginhandle, True, item)
            elif (ret == 1):
                path = xbmc.translatePath(
                    os.path.join(vhd.getSetting('download_path'), name))
                Download(finalurl, path + name + '.avi')
            else:
                return
        elif (vhd.getSetting('download') == '1'):
            item = xbmcgui.ListItem(path=finalurl)
            xbmcplugin.setResolvedUrl(pluginhandle, True, item)
        elif (vhd.getSetting('download') == '2'):
            path = xbmc.translatePath(
                os.path.join(vhd.getSetting('download_path'), name))
            Download(finalurl, path + name + '.avi')
        else:
            return

    if url.find('flv') < 0:
        req = urllib2.Request(url)
        req.add_header(
            'User-Agent',
            'Mozilla/5.0 (Windows; U; Windows NT 5.1; en-GB; rv:1.9.0.3) Gecko/2008092417 Firefox/3.0.3'
        )
        response = urllib2.urlopen(req)
        link = response.read()
        vpi = re.compile('"/vpi.+?h=(.+?)"').findall(link)[0]
        req = urllib2.Request('http://veehd.com/vpi?h=' + vpi)
        req.add_header(
            'User-Agent',
            'Mozilla/5.0 (Windows; U; Windows NT 5.1; en-GB; rv:1.9.0.3) Gecko/2008092417 Firefox/3.0.3'
        )
        response = urllib2.urlopen(req)
        link = response.read()
        finalurl = re.compile('param name="src" value="(.+?)"').findall(
            link)[0]
        item = xbmcgui.ListItem(path=finalurl)
        xbmcplugin.setResolvedUrl(pluginhandle, True, item)

        if (vhd.getSetting('download') == '0'):
            dia = xbmcgui.Dialog()
            ret = dia.select('Streaming Options', ['Play', 'Download'])
            if (ret == 0):
                item = xbmcgui.ListItem(path=finalurl)
                xbmcplugin.setResolvedUrl(pluginhandle, True, item)
            elif (ret == 1):
                path = xbmc.translatePath(
                    os.path.join(vhd.getSetting('download_path'), name))
                Download(finalurl, path + name + '.avi')
            else:
                return
        elif (vhd.getSetting('download') == '1'):
            item = xbmcgui.ListItem(path=finalurl)
            xbmcplugin.setResolvedUrl(pluginhandle, True, item)
        elif (vhd.getSetting('download') == '2'):
            path = xbmc.translatePath(
                os.path.join(vhd.getSetting('download_path'), name))
            Download(finalurl, path + name + '.avi')
        else:
            return
Esempio n. 42
0
def play(url):
    resolved = url + '|User-Agent=TVCatchup/1.0.1 (samsung/SM-J7008; Android 4.4.2/KOT49H)'
    item = xbmcgui.ListItem(path=resolved)
    xbmcplugin.setResolvedUrl(int(sys.argv[1]), True, item)
Esempio n. 43
0
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
import xbmcaddon
import sys

addon = xbmcaddon.Addon(id='plugin.video.zattoo_com')
SESSION = addon.getSetting('session')
params = dict(
    part.split('=') for part in sys.argv[2][1:].split('&')
    if len(part.split('=')) == 2)
mode = params.get('mode', '')

if mode == 'watch':
    from resources.lib.watch import get_stream_url
    import xbmcplugin
    import xbmcgui
    cid = params.get('id', '')
    stream_url = get_stream_url(cid, SESSION)
    xbmcplugin.setResolvedUrl(int(sys.argv[1]), True,
                              xbmcgui.ListItem(path=stream_url))
elif mode == 'epg':
    from resources.lib.epg import list_epg_item
    pid = params.get('id', '')
    pg_hash = addon.getSetting('pg_hash')
    list_epg_item(pid, SESSION, pg_hash)
else:
    from resources.lib.channels import list_channels
    USE_FANARTS = addon.getSetting('showFanart') == 'true'
    pg_hash = addon.getSetting('pg_hash')
    list_channels(SESSION, pg_hash, USE_FANARTS)
 def play_resolved_url(self, url=""):
     """This method plays the video file pointed by the URL passed as argument."""
     self._log("play_resolved_url pluginhandle = [%s] url = [%s]" %
               (self.pluginhandle, url))
     listitem = xbmcgui.ListItem(path=url)
     return xbmcplugin.setResolvedUrl(self.pluginhandle, True, listitem)
Esempio n. 45
0
def play(d, external=None, download_dir=None):
    """
	if 'lang' in d['media'][0]:
		url = _chooseBitrate(d['media'])
		#""
		languageFound = False
		l = []
		lsubtitles = []
		for lang in prefererdLang:
			for item in d['media']:
				if lang == item['lang']:
					if 'subtitlelang' in item:
						lsubtitles.append(item)
					else:
						l.append(item)
					languageFound = True
			if languageFound:
				log('###############')
				if subtitleenabled and len(lsubtitles) > 0:
					url = _chooseBitrate(lsubtitles)
				elif len(l) == 0 and len(lsubtitles) > 0:
					url = _chooseBitrate(lsubtitles)
				elif lang != prefererdLang and len(lsubtitles) > 0:
					url = _chooseBitrate(lsubtitles)
				else:
					url = _chooseBitrate(l)
				break
		#""
		if not languageFound:
			url = _chooseBitrate(d['media'])
	else:
		url = _chooseBitrate(d['media'])
	"""

    #listitem = xbmcgui.ListItem(path=url)
    listitem, url = _chooseBitrate(d['media'], force_MP4=bool(download_dir))

    i = 0
    if 'subtitle' in d:
        subs = []
        for subtitle in d['subtitle']:
            if subtitle['type'] == 'srt':
                subs.append(subtitle['url'])
            elif subtitle['type'] == 'ttml':
                subFile = ttml2Srt(subtitle['url'])
                subs.append(subFile)
            elif subtitle['type'] == 'webvtt':
                subFile = webvtt2Srt(subtitle['url'])
                subs.append(subFile)
            else:
                log('Subtitle format not supported: ' + subtitle['type'])
        listitem.setSubtitles(subs)

    if 'metadata' in d:
        ilabels = {}
        if 'plot' in d['metadata']:
            ilabels['Plot'] = d['metadata']['plot']
        if 'name' in d['metadata']:
            ilabels['Title'] = d['metadata']['name']
        listitem.setInfo(type="Video", infoLabels=ilabels)

        art = {}
        if 'thumb' in d['metadata']:
            art['thumb'] = d['metadata']['thumb']
        listitem.setArt(art)

    if 'header' in d['media']:
        #listitem.setProperty('media_headers',d['media']['header'])
        #listitem.setProperty('inputstream.adaptive.media_headers',d['media']['header'])
        listitem.setProperty('inputstream.adaptive.stream_headers',
                             d['media']['header'])

    if download_dir:
        filename = datetime.today().strftime('%Y-%m-%d-%H%M%S.mp4')
        title = d.get('metadata', filename).get('name', filename)
        addon_icon = os.path.join(addon.getAddonInfo('path'), 'icon.png')
        if url:
            if title != filename:
                filename = title + ' - ' + filename
                valid_chars = frozenset('-_.() %s%s' %
                                        (string.ascii_letters, string.digits))
                filename = ''.join(c for c in filename if c in valid_chars)
            filename = 'DL - ' + filename
            tuple = (addon.getAddonInfo('name'), addon_icon, title,
                     os.path.abspath(os.path.join(download_dir,
                                                  filename)), url)
            arg = None
            for item in tuple:
                if sys.version_info[0] < 3:
                    item = item.decode('utf-8')
                if arg is None: arg = item
                else: arg = arg + '\0' + item
            if sys.version_info[0] < 3:  # for Python 2
                base64str = arg.encode('utf-8').encode('base64').strip()
                path = os.path.join(xbmc.translatePath('special://home'),
                                    'addons', libmediathek3_addonid, 'lib',
                                    'download.py')
            else:  # for Python 3
                import base64
                base64str = base64.b64encode(
                    arg.encode('utf-8')).decode('ascii').strip()
                path = os.path.join(xbmcvfs.translatePath('special://home'),
                                    'addons', libmediathek3_addonid, 'lib',
                                    'download.py')
            xbmc.executebuiltin('RunScript(%s, %s)' % (path, base64str))
        else:
            xbmcgui.Dialog().notification(getTranslation(31044), title,
                                          addon_icon)
    elif external:
        xbmc.Player().play(url, listitem)
    else:
        pluginhandle = int(sys.argv[1])
        xbmcplugin.setResolvedUrl(pluginhandle, True, listitem)
Esempio n. 46
0
 def play(self, links):
     link = self.extractLink(links)
     listItem = xbmcgui.ListItem(path=link.basePath)
     xbmcplugin.setResolvedUrl(int(sys.argv[1]), True, listitem=listItem)
Esempio n. 47
0
def play_episode(url):
    xbmc.log('URL: ' + str(url), level=log_level)
    item = xbmcgui.ListItem(path=url)
    item.setProperty('IsPlayable', 'true')
    return xbmcplugin.setResolvedUrl(int(sys.argv[1]), True, item)
Esempio n. 48
0
    def play(self, path):
        url = "https://%s:%[email protected]%s" % (self.client.username, self.client.password, path)

        item = xbmcgui.ListItem(path=url)
        xbmcplugin.setResolvedUrl(self.handle, True, item)
        xbmcplugin.endOfDirectory(self.handle, True)
Esempio n. 49
0
def play(name, url):
    stream_url = url
    liz = xbmcgui.ListItem(name, path=stream_url)
    xbmcplugin.setResolvedUrl(int(sys.argv[1]), True, liz)
def resolve_url(url):
    item = xbmcgui.ListItem(path=url)
    xbmcplugin.setResolvedUrl(int(sys.argv[1]), True, item)
    return
Esempio n. 51
0
def PlayStream(name, url):
    item = xbmcgui.ListItem(name, path=url)
    xbmcplugin.setResolvedUrl(int(sys.argv[1]), True, item)
    return
Esempio n. 52
0
def playResolvedUrl(url):
    li = xbmcgui.ListItem(path=url)
    xbmcplugin.setResolvedUrl(addon_handle, True, li)
Esempio n. 53
0
 def play(self, url):
     print "*** play URL %s" % url
     item = xbmcgui.ListItem(path=url, iconImage=self.icover, thumbnailImage=self.icover)
     # item.setProperty('mimetype', 'audio/mpeg')
     xbmcplugin.setResolvedUrl(self.handle, True, item)
Esempio n. 54
0
File: main.py Progetto: pyro999/kodi
                                                    qualityList)
                if selection > -1:
                    stream_url = cdaresolver.getVideoUrls(
                        stream_url[selection][1])
                else:
                    stream_url = ''
        elif link:
            try:
                stream_url = urlresolver.resolve(link)
            except Exception, e:
                stream_url = ''
                s = xbmcgui.Dialog().ok('[COLOR red]Problem[/COLOR]', str(e))

    print 'stream_url', stream_url
    if stream_url:
        xbmcplugin.setResolvedUrl(addon_handle, True,
                                  xbmcgui.ListItem(path=stream_url))
    else:
        xbmcplugin.setResolvedUrl(addon_handle, False,
                                  xbmcgui.ListItem(path=''))


## Historia wyszukiwania
def HistoryLoad():
    return cache.get('history').split(';')


def HistoryAdd(entry):
    history = HistoryLoad()
    if history == ['']:
        history = []
    history.insert(0, entry)
Esempio n. 55
0
def playVideo(url):
    content = getUrl(url)
    match = re.compile('data-mp4="(.+?)"', re.DOTALL).findall(content)
    url = match[0]
    listitem = xbmcgui.ListItem(path=url)
    return xbmcplugin.setResolvedUrl(pluginhandle, True, listitem)
Esempio n. 56
0
    def LOAD_AND_PLAY_VIDEO(self, url, title, icon, year='', plot=''):
        mrknow_pCommon.mystat(url)
        progress = xbmcgui.DialogProgress()
        progress.create('Postęp', '')
        message = ptv.getLocalizedString(30406)
        progress.update(10, "", message, "")
        xbmc.sleep(1000)
        progress.update(30, "", message, "")
        progress.update(50, "", message, "")
        VideoLink = ''
        subs = ''
        if url is not None:
            if url.startswith('rtmp'):
                VideoLink = url
            else:
                alina = mrknow_Pageparser.mrknow_Pageparser()
                VideoLink = alina.getVideoLink(url)
            print("Type", type(VideoLink))
        if type(VideoLink) is dict:
            videoUrl = VideoLink[0]
            subs = VideoLink[1]
        elif type(VideoLink) is bool:
            videoUrl = ''
        else:
            videoUrl = VideoLink
        progress.update(70, "", message, "")
        pluginhandle = int(sys.argv[1])
        if videoUrl == '' or videoUrl == None:
            progress.close()
            d = xbmcgui.Dialog()
            d.ok('Nie znaleziono streamingu', 'Może to chwilowa awaria.',
                 'Spróbuj ponownie za jakiś czas')
            return False
        if icon == '' or icon == 'None':
            icon = "DefaultVideo.png"
        if plot == '' or plot == 'None':
            plot = ''
        liz = xbmcgui.ListItem(title,
                               iconImage=icon,
                               thumbnailImage=icon,
                               path=videoUrl)
        liz.setInfo(type="video", infoLabels={"Title": title})
        xbmcPlayer = xbmc.Player()

        if subs != '':
            subsdir = os.path.join(ptv.getAddonInfo('path'), "subs")
            if not os.path.isdir(subsdir):
                os.mkdir(subsdir)
            query_data = {
                'url': subs,
                'use_host': False,
                'use_header': False,
                'use_cookie': False,
                'use_post': False,
                'return_data': True
            }
            progress.update(80, "", message, "")
            data = self.cm.getURLRequestData(query_data)
            output = open((os.path.join(subsdir, "napisy.txt")), "w+")
            progress.update(90, "", message, "")
            output.write(data)
            output.close()
            progress.update(100, "", message, "")
            progress.close()
            xbmcplugin.setResolvedUrl(int(sys.argv[1]), True, liz)

            for _ in xrange(30):
                if xbmcPlayer.isPlaying():
                    break
                time.sleep(1)
            else:
                raise Exception('No video playing. Aborted after 30 seconds.')
            xbmcPlayer.setSubtitles((os.path.join(subsdir, "napisy.txt")))
            xbmcPlayer.showSubtitles(True)

        else:
            progress.update(90, "", message, "")
            progress.close()
            #listitem = xbmcgui.ListItem(path=videoUrl)
            xbmcplugin.setResolvedUrl(int(sys.argv[1]), True, liz)
Esempio n. 57
0
    def __init__(self, *args, **kwargs):
        print "==============================="
        print "  FranceTV Pluzz - Version: %s" % __version__
        print "==============================="
        print
        self.set_debug_mode()
        if self.debug_mode:
            print "Python version:"
            print sys.version_info
            print "ROOTDIR: %s" % ROOTDIR
            print "ADDON_DATA: %s" % ADDON_DATA
            print "CACHEDIR: %s" % CACHEDIR
            print "FANART_PATH: %s" % FANART_PATH
        params = self.get_params()
        url = None
        name = None
        mode = None
        iconimage = None
        cat = ''
        try:
            url = urllib.unquote_plus(params["url"])
        except:
            pass
        try:
            name = urllib.unquote_plus(params["name"])
        except:
            pass
        try:
            mode = int(params["mode"])
        except:
            pass
        try:
            iconimage = urllib.unquote_plus(params["iconimage"])
        except:
            pass
        try:
            cat = urllib.unquote_plus(params["cat"])
        except:
            pass

        if self.debug_mode:
            print "Mode: " + str(mode)
            print "URL: " + str(url)
            print "Name: " + str(name)
            print "Iconimage: " + str(iconimage)
            print "Catégorie : " + str(cat)

        # Check if directories in user data exist
        for i in range(len(dirCheckList)):
            self.checkfolder(dirCheckList[i])

        if mode == None or url == None or len(url) < 1:
            self.download_catalog()
            self.addDir("Replays", "message_FT.json", 1,
                        os.path.join(MEDIA_PATH, 'replay.png'), '')
            self.addDir("Directs", "message_FT.json", 100,
                        os.path.join(MEDIA_PATH, 'live.png'), '')
            self.clean_thumbnail(str(url))
            xbmcplugin.setPluginCategory(handle=int(sys.argv[1]),
                                         category=__language__(30000))
            xbmcplugin.endOfDirectory(int(sys.argv[1]))
            xbmcplugin.addSortMethod(
                handle=int(sys.argv[1]),
                sortMethod=xbmcplugin.SORT_METHOD_UNSORTED)
            xbmcplugin.addSortMethod(handle=int(sys.argv[1]),
                                     sortMethod=xbmcplugin.SORT_METHOD_LABEL)

        elif mode == 1:
            self.addDir("France 1ère", "catch_up_france1.json", 2,
                        os.path.join(MEDIA_PATH, 'france1.png'), '')
            self.addDir("France 2", "catch_up_france2.json", 2,
                        os.path.join(MEDIA_PATH, 'france2.png'), '')
            self.addDir("France 3", "catch_up_france3.json", 2,
                        os.path.join(MEDIA_PATH, 'france3.png'), '')
            self.addDir("France 4", "catch_up_france4.json", 2,
                        os.path.join(MEDIA_PATH, 'france4.png'), '')
            self.addDir("France 5", "catch_up_france5.json", 2,
                        os.path.join(MEDIA_PATH, 'france5.png'), '')
            self.addDir("France Ô", "catch_up_franceo.json", 2,
                        os.path.join(MEDIA_PATH, 'franceO.png'), '')
            self.clean_thumbnail(str(url))
            xbmcplugin.setPluginCategory(handle=int(sys.argv[1]),
                                         category=__language__(30000))
            xbmcplugin.endOfDirectory(int(sys.argv[1]))
            xbmcplugin.addSortMethod(
                handle=int(sys.argv[1]),
                sortMethod=xbmcplugin.SORT_METHOD_UNSORTED)
            xbmcplugin.addSortMethod(handle=int(sys.argv[1]),
                                     sortMethod=xbmcplugin.SORT_METHOD_LABEL)

        elif mode == 2:
            zf = zipfile.ZipFile(CATALOG_PATH)
            data = zf.read(catalogcatfilename)
            jsoncat = json.loads(data.decode('iso-8859-1'))
            categories = jsoncat['categories']
            for cat in categories:
                cat_name = cat['titre'].encode('utf-8')
                cat_infos = {}
                cat_infos['Plot'] = cat['accroche'].encode('utf-8')
                self.addDir(cat_name, url, 3, '', '', cat_infos, cat_name)
            self.clean_thumbnail(str(url))
            xbmcplugin.setPluginCategory(handle=int(sys.argv[1]),
                                         category=__language__(30000))
            xbmcplugin.endOfDirectory(int(sys.argv[1]))
            xbmcplugin.addSortMethod(
                handle=int(sys.argv[1]),
                sortMethod=xbmcplugin.SORT_METHOD_UNSORTED)
            xbmcplugin.addSortMethod(handle=int(sys.argv[1]),
                                     sortMethod=xbmcplugin.SORT_METHOD_LABEL)

        elif mode == 3:
            xbmcplugin.setContent(int(sys.argv[1]), 'tvshows')
            zf = zipfile.ZipFile(CATALOG_PATH)
            data = zf.read(url)
            jsoncatalog = json.loads(data)
            if self.debug_mode:
                print "JSON :"
                print json.dumps(jsoncatalog,
                                 sort_keys=True,
                                 indent=4,
                                 separators=(',', ': '))
            programmes = jsoncatalog['programmes']
            prog_list = []
            for programme in programmes:
                video_cat = programme['rubrique'].encode("utf-8")
                if video_cat == cat:
                    video_name = programme['titre'].encode("utf-8")
                    if video_name not in prog_list:
                        video_url = url
                        video_image = self.get_catalog_configuration(
                            catalogconffilename
                        )[1] + programme['url_image_racine'].encode(
                            "utf-8"
                        ) + '.' + programme['extension_image'].encode("utf-8")
                        video_infos = {}
                        if programme['accroche']:
                            video_infos['Plot'] = programme['accroche'].encode(
                                "utf-8")
                        if programme['realisateurs']:
                            video_infos['Cast'] = programme['acteurs'].encode(
                                "utf-8")
                        if programme['realisateurs']:
                            video_infos['Director'] = programme[
                                'realisateurs'].encode("utf-8")
                        if programme['format']:
                            video_infos['Genre'] = programme['format'].encode(
                                "utf-8")
                        if self.debug_mode:
                            print 'Programme Name       : ' + video_name
                            print 'Programme video URL  : ' + video_url
                            print 'Programme image_url  : ' + video_image
                            print '------------------------------------------'
                        self.addDir(video_name, video_url, 4, video_image,
                                    video_image, video_infos, cat)
                        prog_list.append(video_name)
            self.clean_thumbnail(str(url))
            xbmcplugin.setPluginCategory(handle=int(sys.argv[1]),
                                         category=__language__(30000))
            xbmcplugin.endOfDirectory(int(sys.argv[1]))
            xbmcplugin.addSortMethod(
                handle=int(sys.argv[1]),
                sortMethod=xbmcplugin.SORT_METHOD_UNSORTED)
            xbmcplugin.addSortMethod(handle=int(sys.argv[1]),
                                     sortMethod=xbmcplugin.SORT_METHOD_LABEL)
            xbmcplugin.addSortMethod(handle=int(sys.argv[1]),
                                     sortMethod=xbmcplugin.SORT_METHOD_DATE)

        elif mode == 4:
            xbmcplugin.setContent(int(sys.argv[1]), 'tvshows')
            zf = zipfile.ZipFile(CATALOG_PATH)
            data = zf.read(url)
            jsoncatalog = json.loads(data)
            if self.debug_mode:
                print "JSON :"
                print json.dumps(jsoncatalog,
                                 sort_keys=True,
                                 indent=4,
                                 separators=(',', ': '))
            programmes = jsoncatalog['programmes']
            for programme in programmes:
                video_cat = programme['rubrique'].encode("utf-8")
                if video_cat == cat:
                    video_name = programme['titre'].encode("utf-8")
                    if video_name == name:
                        if programme['sous_titre'] != "":
                            video_name = video_name + ' : ' + programme[
                                'sous_titre'].encode("utf-8")
                        video_url = self.get_catalog_configuration(
                            catalogconffilename
                        )[0] + programme['url_video'].encode("utf-8")
                        video_image = self.get_catalog_configuration(
                            catalogconffilename
                        )[1] + programme['url_image_racine'].encode(
                            "utf-8"
                        ) + '.' + programme['extension_image'].encode("utf-8")
                        video_infos = {}
                        if programme['accroche']:
                            video_infos['Plot'] = programme['accroche'].encode(
                                "utf-8")
                        if programme['realisateurs']:
                            video_infos['Cast'] = programme['acteurs'].encode(
                                "utf-8")
                        if programme['realisateurs']:
                            video_infos['Director'] = programme[
                                'realisateurs'].encode("utf-8")
                        video_infos['Genre'] = cat
                        if programme['format'] != '':
                            video_infos['Genre'] = video_infos[
                                'Genre'] + ' - ' + programme['format'].encode(
                                    "utf-8")
                        if programme['genre_simplifie'] != '':
                            video_infos['Genre'] = video_infos[
                                'Genre'] + ' - ' + programme[
                                    'genre_simplifie'].encode("utf-8")
                        if programme['duree']:
                            video_infos['Duration'] = programme[
                                'duree'].encode("utf-8")
                        if programme['date']:
                            video_infos['Year'] = int(programme['date'].split(
                                '-')[0].encode("utf-8"))
                            video_infos['Date'] = str(
                                programme['date'].split('-')[2]) + '-' + str(
                                    programme['date'].split('-')[1]
                                ) + '-' + str(programme['date'].split('-')[0])
                            video_infos['Premiered'] = video_infos['Date']
                            video_name = video_name + " : " + video_infos[
                                'Date']
                        if self.debug_mode:
                            print 'Programme Name       : ' + video_name
                            print 'Programme video URL  : ' + video_url
                            print 'Programme image_url  : ' + video_image
                            print '------------------------------------------'
                        self.addLink(video_name, video_url, 5, video_image,
                                     video_image, video_infos)
                        print "ADDLINK"
            self.clean_thumbnail(str(url))
            xbmcplugin.setPluginCategory(handle=int(sys.argv[1]),
                                         category=__language__(30000))
            xbmcplugin.endOfDirectory(int(sys.argv[1]))
            xbmcplugin.addSortMethod(
                handle=int(sys.argv[1]),
                sortMethod=xbmcplugin.SORT_METHOD_UNSORTED)
            xbmcplugin.addSortMethod(handle=int(sys.argv[1]),
                                     sortMethod=xbmcplugin.SORT_METHOD_LABEL)
            xbmcplugin.addSortMethod(handle=int(sys.argv[1]),
                                     sortMethod=xbmcplugin.SORT_METHOD_DATE)

        elif mode == 5:
            item = xbmcgui.ListItem(path=url)
            xbmcplugin.setResolvedUrl(handle=int(sys.argv[1]),
                                      succeeded=True,
                                      listitem=item)

        elif mode == 100:
            zf = zipfile.ZipFile(CATALOG_PATH)
            data = zf.read(url)
            jsoncatalog = json.loads(data)
            if self.debug_mode:
                print "JSON :"
                print json.dumps(jsoncatalog,
                                 sort_keys=True,
                                 indent=4,
                                 separators=(',', ': '))
            configuration = jsoncatalog['configuration']
            directs = configuration['directs']
            for direct in directs:
                direct_name = direct['nom'].encode('utf-8')
                direct_video = direct['video_ipad'].encode('utf-8')
                direct_image = os.path.join(MEDIA_PATH, direct_name + '.png')
                infos = {}
                infos['Title'] = 'Direct :' + direct_name
                infos['Plot'] = ''
                self.addLink(direct_name, direct_video, 5, direct_image, '',
                             infos)
            xbmcplugin.setPluginCategory(handle=int(sys.argv[1]),
                                         category=__language__(30000))
            xbmcplugin.endOfDirectory(int(sys.argv[1]))
            xbmcplugin.addSortMethod(
                handle=int(sys.argv[1]),
                sortMethod=xbmcplugin.SORT_METHOD_UNSORTED)
            xbmcplugin.addSortMethod(handle=int(sys.argv[1]),
                                     sortMethod=xbmcplugin.SORT_METHOD_LABEL)
            xbmcplugin.addSortMethod(handle=int(sys.argv[1]),
                                     sortMethod=xbmcplugin.SORT_METHOD_DATE)
Esempio n. 58
0
def getVideo(vid):
    url = 'https://secure.brightcove.com/services/viewer/htmlFederated?&width=1280&height=720&flashID=BrightcoveExperience&bgcolor=%23FFFFFF&playerID=756015080001&playerKey=AQ~~,AAAABDk7A3E~,xYAUE9lVY9-LlLNVmcdybcRZ8v_nIl00&isVid=true&isUI=true&dynamicStreaming=true&%40videoPlayer=' + vid + '&secureConnections=true&secureHTMLConnections=true'
    html = getRequest(url)
    m = re.compile('experienceJSON = (.+?)\};', re.DOTALL).search(html)
    a = json.loads(html[m.start(1):m.end(1) + 1])
    try:
        b = a['data']['programmedContent']['videoPlayer']['mediaDTO'][
            'IOSRenditions']
        u = ''
        rate = 0
        for c in b:
            if c['encodingRate'] > rate:
                rate = c['encodingRate']
                u = c['defaultURL']
        b = a['data']['programmedContent']['videoPlayer']['mediaDTO'][
            'renditions']
        for c in b:
            if c['encodingRate'] > rate:
                rate = c['encodingRate']
                u = c['defaultURL']
        if rate == 0:
            try:
                u = a['data']['programmedContent']['videoPlayer']['mediaDTO'][
                    'FLVFullLengthURL']
            except:
                u = ''
        xbmcplugin.setResolvedUrl(int(sys.argv[1]), True,
                                  xbmcgui.ListItem(path=u))

        try:
            suburl = a['data']['programmedContent']['videoPlayer']['mediaDTO'][
                'captions'][0]['URL']
        except:
            suburl = ''

        if (suburl != "") and ('dfxp'
                               in suburl) and (addon.getSetting('sub_enable')
                                               == "true"):
            profile = addon.getAddonInfo('profile').decode(UTF8)
            subfile = xbmc.translatePath(
                os.path.join(profile, 'TVOSubtitles.srt'))
            prodir = xbmc.translatePath(os.path.join(profile))
            if not os.path.isdir(prodir):
                os.makedirs(prodir)

            pg = getRequest(suburl)
            if pg != "":
                ofile = open(subfile, 'w+')
                captions = re.compile('<p begin="(.+?)" end="(.+?)">(.+?)</p>',
                                      re.DOTALL).findall(pg)
                idx = 1
                for cstart, cend, caption in captions:
                    cstart = cstart.replace('.', ',')
                    cend = cend.replace('.', ',').split('"', 1)[0]
                    caption = caption.replace('<br/>', '\n').replace(
                        '&gt;', '>').replace('&apos;',
                                             "'").replace('&quot;', '"')
                    ofile.write('%s\n%s --> %s\n%s\n\n' %
                                (idx, cstart, cend, caption))
                    idx += 1
                ofile.close()
                xbmc.sleep(5000)
                xbmc.Player().setSubtitles(subfile)

    except:
        xbmc.executebuiltin('XBMC.Notification("%s", "%s", %s)' %
                            (__addonname__, __language__(30011), 10000))
Esempio n. 59
0
def start_info_actions(info, params):
    if "artistname" in params:
        params["artistname"] = params.get("artistname",
                                          "").split(" feat. ")[0].strip()
        if not params.get("artist_mbid"):
            params["artist_mbid"] = utils.fetch_musicbrainz_id(
                params["artistname"])
    utils.log(info)
    utils.pp(params)
    if "prefix" in params and not params["prefix"].endswith('.'):
        params["prefix"] = params["prefix"] + '.'

    # Audio
    if info == 'discography':
        discography = AudioDB.get_artist_discography(params["artistname"])
        if not discography:
            discography = LastFM.get_artist_albums(params.get("artist_mbid"))
        return discography
    elif info == 'mostlovedtracks':
        return AudioDB.get_most_loved_tracks(params["artistname"])
    elif info == 'trackdetails':
        return AudioDB.get_track_details(params.get("id", ""))
    elif info == 'topartists':
        return LastFM.get_top_artists()
    #  The MovieDB
    elif info == 'incinemamovies':
        return tmdb.get_movies("now_playing")
    elif info == 'upcomingmovies':
        return tmdb.get_movies("upcoming")
    elif info == 'topratedmovies':
        return tmdb.get_movies("top_rated")
    elif info == 'popularmovies':
        return tmdb.get_movies("popular")
    elif info == 'ratedmovies':
        return tmdb.get_rated_media_items("movies")
    elif info == 'starredmovies':
        return tmdb.get_fav_items("movies")
    elif info == 'accountlists':
        account_lists = tmdb.handle_lists(tmdb.get_account_lists())
        for item in account_lists:
            item.set_property("directory", True)
        return account_lists
    elif info == 'listmovies':
        return tmdb.get_movies_from_list(params["id"])
    elif info == 'airingtodaytvshows':
        return tmdb.get_tvshows("airing_today")
    elif info == 'onairtvshows':
        return tmdb.get_tvshows("on_the_air")
    elif info == 'topratedtvshows':
        return tmdb.get_tvshows("top_rated")
    elif info == 'populartvshows':
        return tmdb.get_tvshows("popular")
    elif info == 'ratedtvshows':
        return tmdb.get_rated_media_items("tv")
    elif info == 'ratedepisodes':
        return tmdb.get_rated_media_items("tv/episodes")
    elif info == 'starredtvshows':
        return tmdb.get_fav_items("tv")
    elif info == 'similarmovies':
        movie_id = params.get("id")
        if not movie_id:
            movie_id = tmdb.get_movie_tmdb_id(imdb_id=params.get("imdb_id"),
                                              dbid=params.get("dbid"))
        if movie_id:
            return tmdb.get_similar_movies(movie_id)
    elif info == 'similartvshows':
        tvshow_id = None
        dbid = params.get("dbid")
        name = params.get("name")
        tmdb_id = params.get("tmdb_id")
        tvdb_id = params.get("tvdb_id")
        imdb_id = params.get("imdb_id")
        if tmdb_id:
            tvshow_id = tmdb_id
        elif dbid and int(dbid) > 0:
            tvdb_id = local_db.get_imdb_id("tvshow", dbid)
            if tvdb_id:
                tvshow_id = tmdb.get_show_tmdb_id(tvdb_id)
        elif tvdb_id:
            tvshow_id = tmdb.get_show_tmdb_id(tvdb_id)
        elif imdb_id:
            tvshow_id = tmdb.get_show_tmdb_id(imdb_id, "imdb_id")
        elif name:
            tvshow_id = tmdb.search_media(media_name=name,
                                          year="",
                                          media_type="tv")
        if tvshow_id:
            return tmdb.get_similar_tvshows(tvshow_id)
    elif info == 'studio':
        if params.get("id"):
            return tmdb.get_company_data(params["id"])
        elif params.get("studio"):
            company_data = tmdb.search_companies(params["studio"])
            if company_data:
                return tmdb.get_company_data(company_data[0]["id"])
    elif info == 'set':
        if params.get("dbid"):
            name = local_db.get_set_name(params["dbid"])
            if name:
                params["setid"] = tmdb.get_set_id(name)
        if params.get("setid"):
            set_data, _ = tmdb.get_set_movies(params["setid"])
            return set_data
    elif info == 'movielists':
        movie_id = params.get("id")
        if not movie_id:
            movie_id = tmdb.get_movie_tmdb_id(imdb_id=params.get("imdb_id"),
                                              dbid=params.get("dbid"))
        if movie_id:
            return tmdb.get_movie_lists(movie_id)
    elif info == 'keywords':
        movie_id = params.get("id")
        if not movie_id:
            movie_id = tmdb.get_movie_tmdb_id(imdb_id=params.get("imdb_id"),
                                              dbid=params.get("dbid"))
        if movie_id:
            return tmdb.get_keywords(movie_id)
    elif info == 'trailers':
        movie_id = params.get("id")
        if not movie_id:
            movie_id = tmdb.get_movie_tmdb_id(imdb_id=params.get("imdb_id"),
                                              dbid=params.get("dbid"))
        if movie_id:
            return tmdb.handle_videos(tmdb.get_movie_videos(movie_id))
    elif info == 'popularpeople':
        return tmdb.get_popular_actors()
    elif info == 'personmovies':
        person = tmdb.get_person_info(person_label=params.get("person"),
                                      skip_dialog=True)
        if person and person.get("id"):
            movies = tmdb.get_person_movies(person["id"])
            if not movies:
                return None
            for item in movies:
                del item["credit_id"]
            return movies.reduce(key="department")
    elif info == 'traktsimilarmovies':
        if params.get("id") or params.get("dbid"):
            if params.get("dbid"):
                movie_id = local_db.get_imdb_id("movie", params["dbid"])
            else:
                movie_id = params["id"]
            return Trakt.get_similar("movie", movie_id)
    elif info == 'traktsimilartvshows':
        if params.get("id") or params.get("dbid"):
            if params.get("dbid"):
                if params.get("type") == "episode":
                    tvshow_id = local_db.get_tvshow_id_by_episode(
                        params["dbid"])
                else:
                    tvshow_id = local_db.get_imdb_id(media_type="tvshow",
                                                     dbid=params["dbid"])
            else:
                tvshow_id = params["id"]
            return Trakt.get_similar("show", tvshow_id)
    elif info == 'airingepisodes':
        return Trakt.get_episodes("shows")
    elif info == 'premiereepisodes':
        return Trakt.get_episodes("premieres")
    elif info == 'trendingshows':
        return Trakt.get_shows("trending")
    elif info == 'popularshows':
        return Trakt.get_shows("popular")
    elif info == 'anticipatedshows':
        return Trakt.get_shows("anticipated")
    elif info == 'mostcollectedshows':
        return Trakt.get_shows_from_time("collected")
    elif info == 'mostplayedshows':
        return Trakt.get_shows_from_time("played")
    elif info == 'mostwatchedshows':
        return Trakt.get_shows_from_time("watched")
    elif info == 'trendingmovies':
        return Trakt.get_movies("trending")
    elif info == 'traktpopularmovies':
        return Trakt.get_movies("popular")
    elif info == 'mostplayedmovies':
        return Trakt.get_movies_from_time("played")
    elif info == 'mostwatchedmovies':
        return Trakt.get_movies_from_time("watched")
    elif info == 'mostcollectedmovies':
        return Trakt.get_movies_from_time("collected")
    elif info == 'mostanticipatedmovies':
        return Trakt.get_movies("anticipated")
    elif info == 'traktboxofficemovies':
        return Trakt.get_movies("boxoffice")
    elif info == 'similarartistsinlibrary':
        return local_db.get_similar_artists(params.get("artist_mbid"))
    elif info == 'trackinfo':
        addon.clear_global('%sSummary' % params.get("prefix", ""))
        if params["artistname"] and params["trackname"]:
            track_info = LastFM.get_track_info(
                artist_name=params["artistname"], track=params["trackname"])
            addon.set_global('%sSummary' % params.get("prefix", ""),
                             track_info["summary"])
    elif info == 'topartistsnearevents':
        artists = local_db.get_artists()
        import BandsInTown
        return BandsInTown.get_near_events(artists[0:49])
    elif info == 'youtubesearchvideos':
        addon.set_global('%sSearchValue' % params.get("prefix", ""),
                         params.get("id", ""))
        if params.get("id"):
            return youtube.search(search_str=params.get("id", ""),
                                  hd=params.get("hd"),
                                  orderby=params.get("orderby", "relevance"))
    elif info == 'youtubeplaylistvideos':
        return youtube.get_playlist_videos(params.get("id", ""))
    elif info == 'youtubeusersearchvideos':
        user_name = params.get("id")
        if user_name:
            playlists = youtube.get_user_playlists(user_name)
            return youtube.get_playlist_videos(playlists["uploads"])
    elif info == 'favourites':
        if params.get("id"):
            items = favs.get_favs_by_type(params["id"])
        else:
            items = favs.get_favs()
            addon.set_global('favourite.count', str(len(items)))
            if items:
                addon.set_global('favourite.1.name', items[-1]["label"])
        return items
    elif info == "addonsbyauthor":
        items = favs.get_addons_by_author(params.get("id"))
    elif info == 'similarlocalmovies' and "dbid" in params:
        return local_db.get_similar_movies(params["dbid"])
    elif info == 'iconpanel':
        return favs.get_icon_panel(int(
            params["id"])), "IconPanel" + str(params["id"])
    # ACTIONS
    if params.get("handle"):
        xbmcplugin.setResolvedUrl(handle=int(params.get("handle")),
                                  succeeded=False,
                                  listitem=xbmcgui.ListItem())
    if info in [
            'playmovie', 'playepisode', 'playmusicvideo', 'playalbum',
            'playsong'
    ]:
        kodijson.play_media(media_type=info.replace("play", ""),
                            dbid=params.get("dbid"),
                            resume=params.get("resume", "true"))
    elif info == "openinfodialog":
        if xbmc.getCondVisibility("System.HasActiveModalDialog"):
            container_id = ""
        else:
            container_id = "Container(%s)" % utils.get_infolabel(
                "System.CurrentControlId")
        dbid = utils.get_infolabel("%sListItem.DBID" % container_id)
        db_type = utils.get_infolabel("%sListItem.DBType" % container_id)
        if db_type == "movie":
            params = {
                "dbid": dbid,
                "id":
                utils.get_infolabel("%sListItem.Property(id)" % container_id),
                "name": utils.get_infolabel("%sListItem.Title" % container_id)
            }
            start_info_actions("extendedinfo", params)
        elif db_type == "tvshow":
            params = {
                "dbid":
                dbid,
                "tvdb_id":
                utils.get_infolabel("%sListItem.Property(tvdb_id)" %
                                    container_id),
                "id":
                utils.get_infolabel("%sListItem.Property(id)" % container_id),
                "name":
                utils.get_infolabel("%sListItem.Title" % container_id)
            }
            start_info_actions("extendedtvinfo", params)
        elif db_type == "season":
            params = {
                "tvshow":
                utils.get_infolabel("%sListItem.TVShowTitle" % container_id),
                "season":
                utils.get_infolabel("%sListItem.Season" % container_id)
            }
            start_info_actions("seasoninfo", params)
        elif db_type == "episode":
            params = {
                "tvshow":
                utils.get_infolabel("%sListItem.TVShowTitle" % container_id),
                "season":
                utils.get_infolabel("%sListItem.Season" % container_id),
                "episode":
                utils.get_infolabel("%sListItem.Episode" % container_id)
            }
            start_info_actions("extendedepisodeinfo", params)
        elif db_type in ["actor", "director"]:
            params = {
                "name": utils.get_infolabel("%sListItem.Label" % container_id)
            }
            start_info_actions("extendedactorinfo", params)
        else:
            utils.notify("Error", "Could not find valid content type")
    elif info == "ratedialog":
        if xbmc.getCondVisibility("System.HasModalDialog"):
            container_id = ""
        else:
            container_id = "Container(%s)" % utils.get_infolabel(
                "System.CurrentControlId")
        dbid = utils.get_infolabel("%sListItem.DBID" % container_id)
        db_type = utils.get_infolabel("%sListItem.DBType" % container_id)
        if db_type == "movie":
            params = {
                "dbid": dbid,
                "id":
                utils.get_infolabel("%sListItem.Property(id)" % container_id),
                "type": "movie"
            }
            start_info_actions("ratemedia", params)
        elif db_type == "tvshow":
            params = {
                "dbid": dbid,
                "id":
                utils.get_infolabel("%sListItem.Property(id)" % container_id),
                "type": "tv"
            }
            start_info_actions("ratemedia", params)
        if db_type == "episode":
            params = {
                "tvshow":
                utils.get_infolabel("%sListItem.TVShowTitle" % container_id),
                "season":
                utils.get_infolabel("%sListItem.Season" % container_id),
                "type":
                "episode"
            }
            start_info_actions("ratemedia", params)
    elif info == 'youtubebrowser':
        wm.open_youtube_list(search_str=params.get("id", ""))
    elif info == 'moviedbbrowser':
        if addon.get_global('infodialogs.active'):
            return None
        addon.set_global('infodialogs.active', "true")
        search_str = params.get("id", "")
        if not search_str and params.get("search"):
            result = xbmcgui.Dialog().input(heading=addon.LANG(16017),
                                            type=xbmcgui.INPUT_ALPHANUM)
            if result and result > -1:
                search_str = result
            else:
                addon.clear_global('infodialogs.active')
                return None
        wm.open_video_list(search_str=search_str, mode="search")
        addon.clear_global('infodialogs.active')
    elif info == 'extendedinfo':
        if addon.get_global('infodialogs.active'):
            return None
        addon.set_global('infodialogs.active', "true")
        wm.open_movie_info(movie_id=params.get("id"),
                           dbid=params.get("dbid"),
                           imdb_id=params.get("imdb_id"),
                           name=params.get("name"))
        addon.clear_global('infodialogs.active')
    elif info == 'extendedactorinfo':
        if addon.get_global('infodialogs.active'):
            return None
        addon.set_global('infodialogs.active', "true")
        wm.open_actor_info(actor_id=params.get("id"), name=params.get("name"))
        addon.clear_global('infodialogs.active')
    elif info == 'extendedtvinfo':
        if addon.get_global('infodialogs.active'):
            return None
        addon.set_global('infodialogs.active', "true")
        wm.open_tvshow_info(tmdb_id=params.get("id"),
                            tvdb_id=params.get("tvdb_id"),
                            dbid=params.get("dbid"),
                            imdb_id=params.get("imdb_id"),
                            name=params.get("name"))
        addon.clear_global('infodialogs.active')
    elif info == 'seasoninfo':
        if addon.get_global('infodialogs.active'):
            return None
        addon.set_global('infodialogs.active', "true")
        wm.open_season_info(tvshow=params.get("tvshow"),
                            dbid=params.get("dbid"),
                            season=params.get("season"))
        addon.clear_global('infodialogs.active')
    elif info == 'extendedepisodeinfo':
        if addon.get_global('infodialogs.active'):
            return None
        addon.set_global('infodialogs.active', "true")
        wm.open_episode_info(tvshow=params.get("tvshow"),
                             tvshow_id=params.get("tvshow_id"),
                             dbid=params.get("dbid"),
                             episode=params.get("episode"),
                             season=params.get("season"))
        addon.clear_global('infodialogs.active')
    elif info == 'albuminfo':
        if params.get("id"):
            album_details = AudioDB.get_album_details(params.get("id"))
            utils.dict_to_windowprops(album_details, params.get("prefix", ""))
    elif info == 'artistdetails':
        artist_details = AudioDB.get_artist_details(params["artistname"])
        utils.dict_to_windowprops(artist_details, params.get("prefix", ""))
    elif info == 'ratemedia':
        media_type = params.get("type")
        if not media_type:
            return None
        if params.get("id"):
            tmdb_id = params["id"]
        elif media_type == "movie":
            tmdb_id = tmdb.get_movie_tmdb_id(imdb_id=params.get("imdb_id"),
                                             dbid=params.get("dbid"),
                                             name=params.get("name"))
        elif media_type == "tv" and params.get("dbid"):
            tvdb_id = local_db.get_imdb_id(media_type="tvshow",
                                           dbid=params["dbid"])
            tmdb_id = tmdb.get_show_tmdb_id(tvdb_id=tvdb_id)
        else:
            return False
        rating = utils.input_userrating()
        if rating == -1:
            return None
        tmdb.set_rating(media_type=media_type,
                        media_id=tmdb_id,
                        rating=rating,
                        dbid=params.get("dbid"))
    elif info == 'action':
        for builtin in params.get("id", "").split("$$"):
            xbmc.executebuiltin(builtin)
    elif info == "youtubevideo":
        xbmc.executebuiltin("Dialog.Close(all,true)")
        wm.play_youtube_video(params.get("id", ""))
    elif info == 'playtrailer':
        busy.show_busy()
        if params.get("id"):
            movie_id = params["id"]
        elif int(params.get("dbid", -1)) > 0:
            movie_id = local_db.get_imdb_id(media_type="movie",
                                            dbid=params["dbid"])
        elif params.get("imdb_id"):
            movie_id = tmdb.get_movie_tmdb_id(params["imdb_id"])
        else:
            movie_id = ""
        if movie_id:
            trailers = tmdb.get_movie_videos(movie_id)
            busy.hide_busy()
            time.sleep(0.1)
            if trailers:
                wm.play_youtube_video(trailers[0]["key"])
            elif params.get("title"):
                wm.open_youtube_list(search_str=params["title"])
            else:
                busy.hide_busy()
    elif info == 'deletecache':
        addon.clear_globals()
        for rel_path in os.listdir(addon.DATA_PATH):
            path = os.path.join(addon.DATA_PATH, rel_path)
            try:
                if os.path.isdir(path):
                    shutil.rmtree(path)
            except Exception as e:
                utils.log(e)
        utils.notify("Cache deleted")
    elif info == 'tmdbpassword':
        addon.set_password_prompt("tmdb_password")
    elif info == 'syncwatchlist':
        pass
Esempio n. 60
0
def play_video(video_url = common.args.url):
	logged_in = login(video_url)
	try:
		qbitrate = common.args.quality
	except:
		qbitrate = None
	closedcaption = None
	if 'http://' in video_url:
		pid = lookup_meta(video_url)
	else:
		pid = video_url
	video_url = EPISODE % pid
	video_data = connection.getURL(video_url)
	video_tree = BeautifulSoup(video_data, 'html.parser')
	if  video_tree.find('param', attrs = {'name' : 'isException', 'value' : 'true'}) is None:
		video_rtmp = video_tree.meta
		playpath_url = None
		if video_rtmp is not None:
			base_url = video_rtmp['base']
			if qbitrate is None:
				video_url2 = video_tree.switch.find_all('video')
				lbitrate = -1
				hbitrate = -1
				sbitrate = int(addon.getSetting('quality')) * 1024
				for video_index in video_url2:
					bitrate = int(video_index['system-bitrate'])
					if bitrate < lbitrate or lbitrate == -1:
						lbitrate = bitrate
						lplaypath_url = video_index['src']
					if bitrate > hbitrate and bitrate <= sbitrate:
						hbitrate = bitrate
						playpath_url = video_index['src']
				if playpath_url is None:
					playpath_url = lplaypath_url
			else:
				bitrate = qbitrate
				playpath_url = video_tree.switch.find('video', attrs = {'system-bitrate' : qbitrate})['src']
			if '.mp4' in playpath_url:
				playpath_url = 'mp4:' + playpath_url
			else:
				playpath_url = playpath_url.replace('.flv', '')
			try:
				closedcaption = video_tree.find('param', attrs = {'name' : 'ClosedCaptionURL'})['value']
				if closedcaption == '':
					closedcaption = None
			except:
				pass
			if (addon.getSetting('enablesubtitles') == 'true') and (closedcaption is not None):
					convert_subtitles(closedcaption)
			finalurl = base_url + ' playpath=' + playpath_url + ' swfurl=' + SWFURL + ' swfvfy=true'
		item = xbmcgui.ListItem( path = finalurl)
		try:
			item.setThumbnailImage(common.args.thumb)
		except:
			pass
		try:
			item.setInfo('Video', {	'title' : common.args.name,
									'season' : common.args.season_number,
									'episode' : common.args.episode_number})
		except:
			pass
		xbmcplugin.setResolvedUrl(pluginHandle, True, item)
		if (addon.getSetting('enablesubtitles') == 'true') and (closedcaption is not None):
			while not xbmc.Player().isPlaying():
				xbmc.sleep(100)
			xbmc.Player().setSubtitles(ustvpaths.SUBTITLE)
	else:
		common.show_exception(video_tree.ref['title'], video_tree.ref['abstract'])