Example #1
0
def Playvid(url, name, download=None):
	videopage = utils.getHtml(url, '')
	videourl = re.compile('video_url="([^"]+)"').findall(videopage)[0]
	videourl += re.compile('video_url\+="([^"]+)"').findall(videopage)[0]	
	partes = videourl.split('||')
	videourl = decode_url(partes[0])
	videourl = re.sub('/get_file/\d+/[0-9a-z]{32}/', partes[1], videourl)
	videourl += '&' if '?' in videourl else '?'
	videourl += 'lip=' + partes[2] + '&lt=' + partes[3]		
	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:
			iconimage = xbmc.getInfoImage("ListItem.Thumb")
			listitem = xbmcgui.ListItem(name, iconImage="DefaultVideo.png", thumbnailImage=iconimage)
			listitem.setInfo('video', {'Title': name, 'Genre': 'P**n'})
			xbmc.Player().play(videourl, listitem)
Example #2
0
def playClip():
    import xbmc
    title = unicode( xbmc.getInfoLabel( "ListItem.Title" ), "utf-8" )
    thumb = unicode( xbmc.getInfoImage( "ListItem.Thumb" ), "utf-8" )
    #
    listitem = xbmcgui.ListItem( title, '', 'DefaultVideo.png', thumb )
    #
    infoLabels = {
        'title': title,
        'plot': unicode( xbmc.getInfoLabel( "ListItem.Plot" ), "utf-8" ),
        "episode": int( xbmc.getInfoImage( "ListItem.episode" ) or "-1" ),
        }
    infoLabels.update( b_infoLabels )
    listitem.setInfo( 'video', infoLabels )
    #
    if ADDON.getSetting( "full" ) == "false":
        from resources.lib.scraper import getClip
        srt, hd, sd = getClip( xbmc.getInfoLabel( "ListItem.Property(id)" ) )
    else:
        srt, hd, sd = xbmc.getInfoLabel( "ListItem.Property(srt_url)" ), xbmc.getInfoLabel( "ListItem.Property(hd_url)" ), xbmc.getInfoLabel( "ListItem.Property(sd_url)" )
    #
    media = ( hd, sd )[ int( ADDON.getSetting( "quality" ) ) ]
    #
    xbmc.Player().play( media, listitem )
    #
    print "playClip(%r)" % media
    #
    if ADDON.getSetting( "subtitle" ) == "true":
        from resources.lib.scraper import getSubtitle
        srt = getSubtitle( srt, os.path.splitext( os.path.basename( media ) )[ 0 ] )
        if not xbmc.Player().isPlaying():
            xbmc.sleep( 5000 )
        xbmc.Player().setSubtitles( srt )
        xbmc.Player().showSubtitles( True )
Example #3
0
 def __init__(self, nfo_path = None):
     info_labels = {
         'size' : unicode(xbmc.getInfoLabel( "ListItem.Size" ), 'utf-8'),
         'tvshowtitle': unicode(xbmc.getInfoLabel( "ListItem.TvShowTitle" ), 'utf-8'),
         'title': unicode(xbmc.getInfoLabel( "ListItem.Title" ), 'utf-8'),
         'genre': unicode(xbmc.getInfoLabel( "ListItem.Genre" ), 'utf-8'),
         'plot': unicode(xbmc.getInfoLabel( "ListItem.Plot" ), 'utf-8'),
         'aired': unicode(xbmc.getInfoLabel( "ListItem.Premiered" ), 'utf-8'),
         'mpaa': unicode(xbmc.getInfoLabel( "ListItem.MPAA" ), 'utf-8'),
         'duration': unicode(xbmc.getInfoLabel( "ListItem.DUration" ), 'utf-8'),
         'studio': unicode(xbmc.getInfoLabel( "ListItem.Studio" ), 'utf-8'),
         'cast': unicode(xbmc.getInfoLabel( "ListItem.Cast" ), 'utf-8'),
         'writer': unicode(xbmc.getInfoLabel( "ListItem.Writer" ), 'utf-8'),
         'director': unicode(xbmc.getInfoLabel( "ListItem.Director" ), 'utf-8'),
         'season': int(xbmc.getInfoLabel( "ListItem.Season" ) or "-1"),
         'episode': int(xbmc.getInfoLabel( "ListItem.Episode" ) or "-1"),
         'year': int(xbmc.getInfoLabel( "ListItem.Year" ) or "-1"),
         }
     # Clear empty keys
     for key in info_labels.keys():
         if(info_labels[key] == -1):
             del info_labels[key]
         try:
             if (len(info_labels[key])<1):
                 del info_labels[key]
         except:
             pass
     try:
         info_labels['size'] = self._size_to_bytes(info_labels['size'])
     except:
        pass
     try:
         code = self._code_from_plot(info_labels['plot'])
         if code:
             info_labels['code'] = code
     except:
         pass
     try:
         info_labels['cast'] = info_labels['cast'].split('\n')
     except:
         pass
     if not 'title' in info_labels:
         if nfo_path:
             info_labels['title'] = os.path.basename(nfo_path)
         else:
             info_labels['title'] = 'Unknown'
     self.info_labels = info_labels
     self.fanart = unicode(xbmc.getInfoImage( "Listitem.Property(Fanart_Image)" ), 'utf-8')
     self.thumbnail = unicode(xbmc.getInfoImage( "ListItem.Thumb" ), 'utf-8')
     self.nfo_path = nfo_path
 def play(self):
   if Debug: self.LOG('Play Video')
   # Get current list item details...
   title = unicode(xbmc.getInfoLabel("ListItem.Title"), "utf-8")
   thumbnail = xbmc.getInfoImage("ListItem.Thumb")
   plot = unicode(xbmc.getInfoLabel("ListItem.Plot"), "utf-8")
   director = unicode(xbmc.getInfoLabel("ListItem.Director"), "utf-8")
   date = unicode(xbmc.getInfoLabel("ListItem.Date"), "utf-8")
   year = unicode(xbmc.getInfoLabel("ListItem.Year"), "utf-8")
   studio = unicode(xbmc.getInfoLabel("ListItem.Studio"), "utf-8")
   # Parse HTML results page...
   html = urllib.urlopen(self.Arguments('url')).read()
   # Get FLV video...
   match = re.compile('so.addVariable\(\'file\'\,\'(.+?)\'\)\;').findall(html)
   for _url in match:
     video_url = _url
   # Create video playlist...
   playlist = xbmc.PlayList(1)
   playlist.clear()
   # only need to add label, icon and thumbnail, setInfo() and addSortMethod() takes care of label2
   listitem = xbmcgui.ListItem(title, iconImage="DefaultVideo.png", thumbnailImage=thumbnail)
   # set the key information
   listitem.setInfo("Video", {"Title": title,
                              "Label" : title,
                              "Director" : director,
                              "Plot": plot,
                              "PlotOutline": plot,
                              "Date" : date,
                              #"Year" : year,
                              "Studio" : studio })
   # add item to our playlist
   playlist.add(video_url, listitem)
   # Play video...
   xbmcPlayer = xbmc.Player()
   xbmcPlayer.play(playlist)
Example #5
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)
Example #6
0
def getVideo(name,url,cat,plot):
	req=urllib2.Request(url)
	req.add_header('User-Agent', HEADER)
	response=urllib2.urlopen(req)
	data=response.read()
	response.close()
	video=re.compile('<video>(.+?)</video>').findall(data)
	req=urllib2.Request('http://video.nationalgeographic.com/video/cgi-bin/cdn-auth/cdn_tokenized_url.pl?slug='+video[0]+'&siteid=ngcchannelvideos')
	req.add_header('User-Agent', HEADER)
	response=urllib2.urlopen(req)
	data=response.read()
	response.close()
	tokenizedURL=re.compile('<tokenizedURL>(.+?)</tokenizedURL>').findall(data)
	req=urllib2.Request(tokenizedURL[0].replace('&amp;','&'))
	req.add_header('User-Agent', HEADER)
	response=urllib2.urlopen(req)
	data=response.read()
	response.close()
	serverName=re.compile('<serverName>(.+?)</serverName>').findall(data)
	appName=re.compile('<appName><!\[CDATA\[(.+?)\]\]></appName>').findall(data)
	streamName=re.compile('<streamName><!\[CDATA\[(.+?)\]\]></streamName>').findall(data)
	g_thumbnail = xbmc.getInfoImage( "ListItem.Thumb" )
	listitem=xbmcgui.ListItem(name ,iconImage="DefaultVideo.png", thumbnailImage=g_thumbnail)
	listitem.setInfo( type="Video", infoLabels={ "Title": name, "Director": 'National Geographic', "Studio": 'National Geographic', "Genre": cat, "Plot": plot } )
	listitem.setProperty("PlayPath", streamName[0])
	xbmc.Player(xbmc.PLAYER_CORE_DVDPLAYER).play('rtmp://'+serverName[0]+'/'+appName[0], listitem)
Example #7
0
 def __LOAD_AND_PLAY(self, url, title, player=True, pType='video'):
     if url == '':
         d = xbmcgui.Dialog()
         d.ok('Nie znaleziono streamingu', 'Może to chwilowa awaria.', 'Spróbuj ponownie za jakiś czas')
         return False
     thumbnail = xbmc.getInfoImage("ListItem.Thumb")
     liz = xbmcgui.ListItem(title, iconImage="DefaultVideo.png", thumbnailImage=thumbnail)
     liz.setInfo(type="pType", infoLabels={"Title": title})
     try:
         if player != True:
             print "custom player pCommon"
             xbmcPlayer = player
         else:
             print "default player pCommon"
             xbmcPlayer = xbmc.Player()
         xbmcPlayer.play(url, liz)
     except:
         d = self.dialog()
         if pType == "video":
             d.ok('Wystąpił błąd!', 'Błąd przy przetwarzaniu, lub wyczerpany limit czasowy oglądania.',
                  'Zarejestruj się i opłać abonament.', 'Aby oglądać za darmo spróbuj ponownie za jakiś czas.')
         elif pType == "music":
             d.ok('Wystąpił błąd!', 'Błąd przy przetwarzaniu.', 'Aby wysłuchać spróbuj ponownie za jakiś czas.')
         return False
     return True
Example #8
0
def PlayMovie(name, url):
    if 'm3u8' in url:
       PlayStream(name, url)
    else:
       progress.create('Play video', 'Searching videofile')
       progress.update( 30, "", "Loading video page", "Sending it to urlresolver" )
       source = urlresolver.HostedMediaFile(url)
       if source:
          progress.update( 80, "", "Loading video page", "Found the video" )
          streamurl = source.resolve()
          if source.resolve()==False:
             progress.close()
             xbmc.executebuiltin("XBMC.Notification(Oh no!,Link Cannot Be Resolved,5000)")          
             return
       else:
             streamurl = url
       progress.close()
       iconimage = xbmc.getInfoImage("ListItem.Thumb")
       ok = True
       listitem = xbmcgui.ListItem(name, iconImage="DefaultVideo.png", thumbnailImage=iconimage)
       listitem.setInfo(type="Video", infoLabels={ "Title": name })
       ok = xbmcplugin.addDirectoryItem(addon_handle,url=streamurl,listitem=listitem)
       try:
          xbmc.Player().play(streamurl, listitem, False)
          return ok
       except: pass
Example #9
0
def play(params,url,category):
    logger.info("[sonolatino.py] play")

    title = unicode( xbmc.getInfoLabel( "ListItem.Title" ), "utf-8" )
    
    try:
        thumbnail = urllib.unquote_plus( params.get("thumbnail") )
    except:
        thumbnail = xbmc.getInfoImage( "ListItem.Thumb" )
    plot = urllib.unquote_plus( params.get("plot") )
    plot = urllib.unquote_plus( params.get("plot") )

    try:
        plot = unicode( xbmc.getInfoLabel( "ListItem.Plot" ), "utf-8" )
    except:
        plot = xbmc.getInfoLabel( "ListItem.Plot" )

    server = params["server"]
    logger.info("[sonolatino.py] thumbnail="+thumbnail)
    logger.info("[sonolatino.py] server="+server)
    
    if server == "izlesene":
        print server
        data = scrapertools.cachePage(url)
        print data
        patron = 'durl="([^"]+)"'
        matches = re.compile(patron,re.DOTALL).findall(data)
        if len(matches)>0:
            url = matches[0]
            server = "Directo"
    xbmctools.play_video(__channel__,server,url,category,title,thumbnail,plot)
Example #10
0
def playRtmp(params,url,category):
    logger.info("[sonolatino.py] playRtmp")

    title = unicode( xbmc.getInfoLabel( "ListItem.Title" ), "utf-8" )
    
    try:
        thumbnail = urllib.unquote_plus( params.get("thumbnail") )
    except:
        thumbnail = xbmc.getInfoImage( "ListItem.Thumb" )
    plot = urllib.unquote_plus( params.get("plot") )
    plot = urllib.unquote_plus( params.get("plot") )

    try:
        plot = unicode( xbmc.getInfoLabel( "ListItem.Plot" ), "utf-8" )
    except:
        plot = xbmc.getInfoLabel( "ListItem.Plot" )

    server = params["server"]
    logger.info("[sonolatino.py] thumbnail="+thumbnail)
    logger.info("[sonolatino.py] server="+server    )
    
    
    

    item=xbmcgui.ListItem(title, iconImage='', thumbnailImage=thumbnail, path=url)
    item.setInfo( type="Video",infoLabels={ "Title": title})
    xbmcplugin.setResolvedUrl(pluginhandle, True, item)
def Playvid(url, name):
    dp = xbmcgui.DialogProgress()
    dp.create("Searching webcamlink","Searching webcamlink for:",name)
    count = 0
    for videoid in range(491, 340, -1):
        dp.update(int(count))
        videotest = 'false'
        testurl = 'http://video%s.myfreecams.com:1935/NxServer/mfc_%s.f4v_aac/playlist.m3u8' % (videoid, url)
        if videotest == 'false':
            try: videotest = urllib2.urlopen(testurl)
            except: videotest = 'false'
        count = count + 0.7
        if not videotest == 'false':
            dp.update(100)
            dp.close()
            break
        if dp.iscanceled():
            dp.close()
            break
    if not videotest == 'false':
        videourl = testurl
        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)
    else:
        utils.notify('Oh oh','Couldn\'t find a playable webcam link')
Example #12
0
def PlayLiveLink(url, name):
    urlDic = getLiveUrl(url)

    if not urlDic == None:
        line1 = "Url found, Preparing to play"
        time = 2000
        xbmc.executebuiltin("Notification(%s, %s, %d, %s)" % (__addonname__, line1, time, __icon__))

        rtmp = urlDic["rtmp"]
        playPath = urlDic["playpath"]
        swf = urlDic["swf"]

        playfile = "%s playpath=%s swfUrl=%s token=%s live=1 timeout=15 swfVfy=1 pageUrl=%s" % (
            rtmp,
            playPath,
            swf,
            "%bwwpe(nKa@#.",
            url,
        )
        listitem = xbmcgui.ListItem(
            label=str(name), iconImage="DefaultVideo.png", thumbnailImage=xbmc.getInfoImage("ListItem.Thumb")
        )
        print "playing stream name: " + str(name)
        xbmc.Player(xbmc.PLAYER_CORE_AUTO).play(playfile, listitem)
    else:
        line1 = "Stream not found"
        time = 2000
        xbmc.executebuiltin("Notification(%s, %s, %d, %s)" % (__addonname__, line1, time, __icon__))

    return
Example #13
0
def Playvid(username, name):
    try:
       postRequest = {'method' : 'getRoomData', 'args[]' : 'false', 'args[]' : str(username)}
       response = utils.postHtml('http://bongacams.com/tools/amf.php', form_data=postRequest,headers={'X-Requested-With' : 'XMLHttpRequest'},compression=False)
    except:
        utils.notify('Oh oh','Couldn\'t find a playable webcam link')
        return None

    amf_json = json.loads(response)

    if amf_json['localData']['videoServerUrl'].startswith("//mobile"):
       videourl = 'https:' + amf_json['localData']['videoServerUrl'] + '/hls/stream_' + username + '.m3u8'  
    else:
       videourl = 'https:' + amf_json['localData']['videoServerUrl'] + '/hls/stream_' + username + '/playlist.m3u8'

    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)
  def play(self, page, mode=''):
    if Debug: self.LOG('DEBUG: _play()\nurl: %s' % page)
    # Get current list item details...
    title = unicode(xbmc.getInfoLabel("ListItem.Title"), "utf-8")
    thumbnail = xbmc.getInfoImage("ListItem.Thumb")
    plot = unicode(xbmc.getInfoLabel("ListItem.Plot"), "utf-8")

    if mode == 'smil':
      smil = BSS(self._get(page))
      rtmp = smil.meta['base']
      video = smil.video['src']
      swfUrl = 'http://medici.tv/medici.swf'
      # rtmpdump script for console use 
      rtmpdump = "rtmpdump -r %s --swfUrl http://medici.tv/medici.swf --tcUrl '%s' --playpath '%s' -o '%s.mp4'" % \
                  (rtmp, rtmp, saxutils.unescape(video), saxutils.unescape(title))
      # Build rtmp url...
      video_url = rtmp + ' swfUrl=' + swfUrl + ' tcUrl=' + rtmp + ' playpath=' + saxutils.unescape(video)
      if Debug: self.LOG('DEBUG: rtmp link details.\n\trtmp: %s\n\tswfUrl: %s\n\ttcUrl: %s\n\tplaypath: %s\n\trtmpdump: %s' % \
                         (rtmp, swfUrl, rtmp, saxutils.unescape(video), rtmpdump))
    elif mode == 'rtmp_daily':
      video_url = page.split('&rtmp=1')[0]
      if Debug: self.LOG('DEBUG: video link details.\n\turl: %s' % video_url)
    else:
      video_url = ''
      if Debug: self.LOG('DEBUG: no video link!')
      raise
    # only need to add label, icon and thumbnail, setInfo() and addSortMethod() takes care of label2
    listitem = xbmcgui.ListItem(title, iconImage="DefaultVideo.png", thumbnailImage=thumbnail)
    # set listitem information
    listitem.setInfo('video', {'title': title,
                               'label' : title,
                               'plot': plot,
                               'plotoutline': plot, })
    # Play video...
    xbmc.Player().play(video_url , listitem)
Example #15
0
 def _fill_cast( self, listitem ):
     xbmcgui.lock()
     try:
         # clear the cast list
         self.getControl( self.CONTROL_INFO_CAST ).reset()
         # grab the cast from the main lists listitem, we use this for actor thumbs
         cast = xbmc.getInfoLabel( "Container(100).ListItem.Cast" )
         # if cast exists we fill the cast list
         if ( cast ):
             # we set these class variables for the player
             self.title = xbmc.getInfoLabel( "Container(100).ListItem.Title" )
             self.genre = xbmc.getInfoLabel( "Container(100).ListItem.Genre" )
             self.plot = xbmc.getInfoLabel( "Container(100).ListItem.Plot" )
             self.director = xbmc.getInfoLabel( "Container(100).ListItem.Director" )
             self.year = int( xbmc.getInfoLabel( "Container(100).ListItem.Year" ) )
             self.trailer = xbmc.getInfoLabel( "Container(100).ListItem.Trailer" )
             self.thumb = xbmc.getInfoImage( "Container(100).ListItem.Thumb" )
             # we actually use the ListItem.CastAndRole infolabel to fill the list
             role = xbmc.getInfoLabel( "Container(100).ListItem.CastAndRole" ).split( "\n" )
             # enumerate through our cast list and set cast and role
             for count, actor in enumerate( cast.split( "\n" ) ):
                 # create the actor cached thumb
                 actor_path = xbmc.translatePath( os.path.join( "P:\\Thumbnails", "Video", xbmc.getCacheThumbName( "actor" + actor )[ 0 ], xbmc.getCacheThumbName( "actor" + actor ) ) )
                 # if an actor thumb exists use it, else use the default thumb
                 actor_thumbnail = ( "DefaultActorBig.png", actor_path, )[ os.path.isfile( actor_path ) ]
                 # set the default icon
                 actor_icon = "DefaultActorBig.png"
                 # add the item to our cast list
                 self.getControl( self.CONTROL_INFO_CAST ).addItem( xbmcgui.ListItem( role[ count ], iconImage=actor_icon, thumbnailImage=actor_thumbnail ) )
             # set the play trailer buttons status
             self._set_trailer_button( self.trailer )
     except:
         pass
     xbmcgui.unlock()
def PHVideo(url, name):
    progress.create("Play video", "Searching videofile.")
    progress.update(10, "", "Loading video page", "")
    videopage = utils.getHtml(url, "")
    match = re.compile(r'<li id="link-([^"]+).*?xs-12">\s+Watch it on ([\w]+)', re.DOTALL | re.IGNORECASE).findall(
        videopage
    )
    if len(match) > 1:
        sites = []
        for videourl, site in match:
            sites.append(site)
        site = utils.dialog.select("Select video site", sites)
        sitename = match[site][1]
        siteurl = match[site][0]
    else:
        sitename = match[0][1]
        siteurl = match[0][0]
    outurl = "http://www.pornhive.tv/en/out/" + siteurl
    progress.update(20, "", "Getting video page", "")
    if sitename == "StreamCloud":
        progress.update(30, "", "Getting StreamCloud", "")
        playurl = getStreamCloud(outurl)
    elif sitename == "FlashX":
        progress.update(30, "", "Getting FlashX", "")
        playurl = getFlashX(outurl)
    else:
        progress.close()
        utils.dialog.ok("Sorry", "This host is not supported.")
        return
    progress.update(90, "", "Playing video", "")
    iconimage = xbmc.getInfoImage("ListItem.Thumb")
    listitem = xbmcgui.ListItem(name, iconImage="DefaultVideo.png", thumbnailImage=iconimage)
    listitem.setInfo("video", {"Title": name, "Genre": "P**n"})
    xbmc.Player().play(playurl, listitem)
Example #17
0
def Playvid(url, name, download=None):
    listhtml = utils.getHtml2(url)
    listhtml = utils.unescapes(listhtml)
    match480 = re.search(r'[[]480p[]]=([^"]*?)&video_vars', listhtml)
    if match480: videourl = match480.group(1)
    else:
     match360 = re.search(r'[[]360p[]]=([^"]*?)&video_vars', listhtml)
     videourl = match360.group(1)
     
    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)
        return
Example #18
0
def BGPlayvid(url, name, download=None):
    videopage = utils.getHtml(url, '')
    match = re.compile("'720p': '([^']+)'", re.DOTALL | re.IGNORECASE).findall(videopage)
    if not match:
        match = re.compile("'480p': '([^']+)'", re.DOTALL | re.IGNORECASE).findall(videopage)
    if not match:
        match = re.compile("'240p': '([^']+)'", re.DOTALL | re.IGNORECASE).findall(videopage)
    if match:    
        videourl = match[0]
        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)
                #xbmc.Player().play(videourl, listitem)
            else:
                listitem.setPath(str(videourl))
                xbmcplugin.setResolvedUrl(utils.addon_handle, True, listitem)
Example #19
0
 def LOAD_AND_PLAY_VIDEO(self, url, title, player=True):
     if url == "":
         d = xbmcgui.Dialog()
         d.ok("Nie znaleziono streamingu", "Może to chwilowa awaria.", "Spróbuj ponownie za jakiś czas")
         return False
     thumbnail = xbmc.getInfoImage("ListItem.Thumb")
     liz = xbmcgui.ListItem(title, iconImage="DefaultVideo.png", thumbnailImage=thumbnail)
     liz.setInfo(type="Video", infoLabels={"Title": title})
     try:
         if player != True:
             print "custom player pCommon"
             xbmcPlayer = player
         else:
             print "default player pCommon"
             xbmcPlayer = xbmc.Player()
         xbmcPlayer.play(url, liz)
     except:
         d = xbmcgui.Dialog()
         d.ok(
             "BÅ‚Ä…d przy przetwarzaniu, lub wyczerpany limit czasowy oglÄ…dania.",
             "Zarejestruj się i opłać abonament.",
             "Aby oglądać za darmo spróbuj ponownie za jakiś czas",
         )
         return False
     return True
    def playVideo( self, video ) :
        #
        # Get current list item details...
        #
        title     = unicode( xbmc.getInfoLabel( "ListItem.Title"   ), "utf-8" )
        thumbnail =          xbmc.getInfoImage( "ListItem.Thumb"   )
        studio    = unicode( xbmc.getInfoLabel( "ListItem.Studio"  ), "utf-8" )
        plot      = unicode( xbmc.getInfoLabel( "ListItem.Plot"    ), "utf-8" )
        director  = unicode( xbmc.getInfoLabel( "ListItem.Director"), "utf-8" )       

        #    
        # Play video...
        #
        playlist = xbmc.PlayList( xbmc.PLAYLIST_VIDEO )
        playlist.clear()
 
        listitem = xbmcgui.ListItem( title, iconImage="DefaultVideo.png", thumbnailImage=thumbnail )
        listitem.setInfo( "video", { "Title": title, "Studio" : studio, "Plot" : plot, "Director" : director } )
        playlist.add( video, listitem )
        
        # Play video...
        xbmcPlayer = xbmc.Player( self.video_players[ self.video_player ] )
        xbmcPlayer.play(playlist)   

#
# The End
#
Example #21
0
def PlaySEBN(url,name=None):
    iconimage = xbmc.getInfoImage("ListItem.Thumb")
    liz=xbmcgui.ListItem(name, iconImage="DefaultFolder.png", thumbnailImage=iconimage)
    liz.setInfo( type="Video", infoLabels={ "Title": name } )
    dp = xbmcgui.DialogProgress()
    dp.create("DutchSportStreams","Please wait")  
    xbmc.Player().play(url, liz, False)
	def __init__( self ) :
		#
		# Constants
		#
		self.VIDEO_PAGE_URL2 = re.compile( ".*/video/(\d+)/.*" )
		self.VIDEO_PAGE_URL3 = re.compile( ".*/video[s]?/.*-(\d+)" )
		
		#
		# Parse parameters...
		#
		params = dict(part.split('=') for part in sys.argv[ 2 ][ 1: ].split('&'))
		
		self.video_page_url = urllib.unquote( params[ "video_page_url" ] )
		self.play_hd        = urllib.unquote( params[ "play_hd" ] ) 

		# Settings
		self.video_players = { "0" : xbmc.PLAYER_CORE_AUTO,
							   "1" : xbmc.PLAYER_CORE_DVDPLAYER,
							   "2" : xbmc.PLAYER_CORE_MPLAYER }
		self.video_player = xbmcplugin.getSetting ("video_player")
		
		#
		# Get current item details...
		#
		self.video_title     = unicode( xbmc.getInfoLabel( "ListItem.Title"  ), "utf-8" )
		self.video_thumbnail =          xbmc.getInfoImage( "ListItem.Thumb"  )
		self.video_studio    = unicode( xbmc.getInfoLabel( "ListItem.Studio" ), "utf-8" )
		self.video_plot      = unicode( xbmc.getInfoLabel( "ListItem.Plot"   ), "utf-8" )
		self.video_genre     = unicode( xbmc.getInfoLabel( "ListItem.Genre"  ), "utf-8" )

		#
		# Play video...
		#
		self.playVideo()
Example #23
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)
Example #24
0
def download_button(url,name):
		print url
		req = urllib2.Request(url)
		req.add_header('User-Agent', HEADER)
		f=urllib2.urlopen(req)
		a=f.read()
		f.close()
		p=re.compile('<param name="movie" value="http://www.traileraddict.com/emb/(.+?)">')
		info=p.findall(a)
		url='http://www.traileraddict.com/fvar.php?tid='+info[0]
		#print url
		req = urllib2.Request(url)
		req.add_header('User-Agent', HEADER)
		f=urllib2.urlopen(req)
		a=f.read()
		f.close()
		p=re.compile('fileurl=(.+?)&vidwidth')
		info=p.findall(a)
		z=re.compile('&image=(.+?)').findall(a)
		url=info[0]
		thumb=z[0]
		#print thumb
		#print url
		title=name
		name=clean_file(name)
		name=name[:+32]
		if (xbmcplugin.getSetting('ask_filename') == 'true'):
			searchStr = name
			keyboard = xbmc.Keyboard(searchStr, "Save as:")
			keyboard.doModal()
			if (keyboard.isConfirmed() == False):
				return
			searchstring = keyboard.getText()
			name=searchstring
		def Download(url,dest):
				dp = xbmcgui.DialogProgress()
				dp.create('Downloading',title,'Filename: '+name+ '.flv')
				urllib.urlretrieve(url,dest,lambda nb, bs, fs, url=url: _pbhook(nb,bs,fs,url,dp))
		def _pbhook(numblocks, blocksize, filesize, url=None,dp=None):
				try:
						percent = min((numblocks*blocksize*100)/filesize, 100)
						dp.update(percent)
				except:
						percent = 100
						dp.update(percent)
				if dp.iscanceled():
						dp.close()
		flv_file = xbmc.translatePath(os.path.join(xbmcplugin.getSetting('download_Path'), name + '.flv' ))
		Download(url,flv_file)
		if xbmcplugin.getSetting("dvdplayer") == "true":
			player_type = xbmc.PLAYER_CORE_DVDPLAYER
		else:
			player_type = xbmc.PLAYER_CORE_MPLAYER
		g_thumbnail = xbmc.getInfoImage( "ListItem.Thumb" )
		listitem=xbmcgui.ListItem(title ,iconImage="DefaultVideo.png", thumbnailImage=g_thumbnail)
		if (os.path.isfile(flv_file)):
			dia = xbmcgui.Dialog()
			if dia.yesno('Download Complete', 'Do you want to play this video?'):
				xbmc.Player(player_type).play(flv_file, listitem)
Example #25
0
def PHVideo(url, name, download=None):
    progress.create('Play video', 'Searching videofile.')
    progress.update( 10, "", "Loading video page", "" )
    Supported_hosts = ['Openload.io', 'StreamCloud', 'NowVideo', 'FlashX', 'www.flashx.tv', 'streamcloud.eu', 'streamin.to']
    videopage = utils.getHtml(url, '')
    match = re.compile(r'<li id="link-([^"]+).*?xs-12">\s+Watch it on ([\w\.]+)', re.DOTALL | re.IGNORECASE).findall(videopage)
    if len(match) > 1:
        sites = []
        vidurls = []
        for videourl, site in match:
            if site in Supported_hosts:
                sites.append(site)
                vidurls.append(videourl)
        if len(sites) ==  1:
            sitename = match[0][1]
            siteurl = match[0][0]
        else:
            site = utils.dialog.select('Select video site', sites)
            sitename = sites[site]
            siteurl = vidurls[site]
    else:
        sitename = match[0][1]
        siteurl = match[0][0]
    outurl = "http://www.pornhive.tv/en/out/" + siteurl
    progress.update( 20, "", "Getting video page", "" )
    if 'loud' in sitename:
        progress.update( 30, "", "Getting StreamCloud", "" )
        playurl = getStreamCloud(outurl)
    elif "lash" in sitename:
        progress.update( 30, "", "Getting FlashX", "" )
        playurl = getFlashX(outurl)
    elif sitename == "NowVideo":
        progress.update( 30, "", "Getting NowVideo", "" )
        playurl = getNowVideo(outurl)        
    elif "Openload" in sitename:
        progress.update( 30, "", "Getting Openload", "" )
        progress.close()
        utils.PLAYVIDEO(outurl, name, download)
        return
    elif "streamin" in sitename:
        progress.update( 30, "", "Getting Streamin", "" )
        streaming = utils.getHtml(outurl, '')
        outurl=re.compile("action='([^']+)'").findall(streaming)[0]
        progress.close()
        utils.playvideo(outurl, name, download)
        return
    else:
        progress.close()
        utils.dialog.ok('Sorry','This host is not supported.')
        return
    progress.update( 90, "", "Playing video", "" )
    progress.close()
    if download == 1:
        utils.downloadVideo(playurl, name)
    else:
        iconimage = xbmc.getInfoImage("ListItem.Thumb")
        listitem = xbmcgui.ListItem(name, iconImage="DefaultVideo.png", thumbnailImage=iconimage)
        listitem.setInfo('video', {'Title': name, 'Genre': 'P**n'})
        xbmc.Player().play(playurl, listitem)
Example #26
0
    def choose_show ( self, args ):
        # NOTE: ***** not used yet *****
        # we get the filename and add to the playlist

        ok = True
        try:
            args=args.split("&",4)
            smbName=urllib.unquote(args[0])
            print "choose_show: Playing show: " + smbName
            title=urllib.unquote(args[1])
            genre=urllib.unquote(args[2])
            descr=urllib.unquote(args[3])

            print "playing " + smbName

            thumbnail = xbmc.getInfoImage( "ListItem.Thumb" )

            filesize = os.path.getsize(smbName)

            playlist = xbmc.PlayList( xbmc.PLAYLIST_VIDEO )
            # clear any possible entries
            playlist.clear()
            # set the default icon
            icon = "DefaultVideo.png"
            # only need to add label, icon and thumbnail, setInfo() and addSortMethod() takes care of label2
            listitem = xbmcgui.ListItem( title, iconImage=icon, thumbnailImage=thumbnail )
            # set the key information
            listitem.setInfo( "video", {
			"Title": title,
			"Tvshowtitle": title,
			"Genre": genre,
			"Plotoutline": descr,
			"Size": filesize,
			} )
            # add item to our playlist
            playlist.add( smbName, listitem )
            player = xbmc.Player()
            player.play( playlist )
        except:
            print "playing failed"
            xbmcgui.Dialog().ok("Error", "An error ocurred playing the selected show")
            ok = False
            raise

        # set some sort methods
        if ( ok ):
            xbmcplugin.addSortMethod( handle=int( sys.argv[ 1 ] ), sortMethod=xbmcplugin.SORT_METHOD_DATE )
            xbmcplugin.addSortMethod( handle=int( sys.argv[ 1 ] ), sortMethod=xbmcplugin.SORT_METHOD_LABEL )
            xbmcplugin.addSortMethod( handle=int( sys.argv[ 1 ] ), sortMethod=xbmcplugin.SORT_METHOD_VIDEO_TITLE )
            xbmcplugin.addSortMethod( handle=int( sys.argv[ 1 ] ), sortMethod=xbmcplugin.SORT_METHOD_SIZE )
            xbmcplugin.addSortMethod( handle=int( sys.argv[ 1 ] ), sortMethod=xbmcplugin.SORT_METHOD_STUDIO )
            xbmcplugin.addSortMethod( handle=int( sys.argv[ 1 ] ), sortMethod=xbmcplugin.SORT_METHOD_PROGRAM_COUNT )
            xbmcplugin.addSortMethod( handle=int( sys.argv[ 1 ] ), sortMethod=xbmcplugin.SORT_METHOD_EPISODE )
            xbmcplugin.addSortMethod( handle=int( sys.argv[ 1 ] ), sortMethod=xbmcplugin.SORT_METHOD_FILE )

        # saw this in the MythTV plug-in
        xbmcplugin.endOfDirectory( handle=int( sys.argv[ 1 ] ), succeeded=ok )

        return ok
Example #27
0
def PLAYVIDEO(url, name):
    progress.create('Play video', 'Searching videofile.')
    progress.update( 10, "", "Loading video page", "" )
    hosts = []
    videosource = getHtml(url, url)
    if re.search('videomega', videosource, re.DOTALL | re.IGNORECASE):
        hosts.append('VideoMega')
    if re.search('openload', videosource, re.DOTALL | re.IGNORECASE):
        hosts.append('OpenLoad')
    if re.search('www.flashx.tv', videosource, re.DOTALL | re.IGNORECASE):
        hosts.append('FlashX')        
    if len(hosts) == 0:
        progress.close()
        dialog.ok('Oh oh','Couldn\'t find any video')
        return
    elif len(hosts) > 1:
        if addon.getSetting("dontask") == "true":
            vidhost = hosts[0]            
        else:
            vh = dialog.select('Videohost:', hosts)
            vidhost = hosts[vh]
    else:
        vidhost = hosts[0]
    
    if vidhost == 'VideoMega':
        progress.update( 40, "", "Loading videomegatv", "" )
        if re.search("http://videomega.tv/iframe.js", videosource, re.DOTALL | re.IGNORECASE):
            hashref = re.compile("""javascript["']>ref=['"]([^'"]+)""", re.DOTALL | re.IGNORECASE).findall(videosource)
        else:
            hashkey = re.compile("""hashkey=([^"']+)""", re.DOTALL | re.IGNORECASE).findall(videosource)
            hashpage = getHtml('http://videomega.tv/validatehash.php?hashkey='+hashkey[0], url)
            hashref = re.compile('ref="([^"]+)', re.DOTALL | re.IGNORECASE).findall(hashpage)
        progress.update( 80, "", "Getting video file", "" )
        videopage = getHtml('http://videomega.tv/view.php?ref='+hashref[0], url)
        videourl = re.compile('<source src="([^"]+)"', re.DOTALL | re.IGNORECASE).findall(videopage)
        videourl = videourl[0]
    elif vidhost == 'OpenLoad':
        progress.update( 40, "", "Loading Openload", "" )
        openloadurl = re.compile('<iframe src="([^"]+)"', re.DOTALL | re.IGNORECASE).findall(videosource)
        openloadsrc = getHtml(openloadurl[0], url)
        videourl = re.compile('<source src="([^"]+)"', re.DOTALL | re.IGNORECASE).findall(openloadsrc)
        progress.update( 80, "", "Getting video file", "" )
        openload302 = getVideoLink(videourl[0],openloadurl[0])
        realurl = openload302.replace('https://','http://')
        videourl = realurl + "|" + openloadurl[0]
    elif vidhost == 'FlashX':
        progress.update( 40, "", "Loading FlashX", "" )
        flashxurl = re.compile('<iframe src="([^"]+)"', re.DOTALL | re.IGNORECASE).findall(videosource)
        flashxsrc = getHtml2(flashxurl[0])
        flashxjs = re.compile("<script type='text/javascript'>([^<]+)</sc", re.DOTALL | re.IGNORECASE).findall(flashxsrc)
        progress.update( 80, "", "Getting video file", "" )
        flashxujs = beautify(flashxjs[0])
        videourl = re.compile(r',.*file: "([^"]+)".*\}\],', re.DOTALL | re.IGNORECASE).findall(flashxujs)
        videourl = videourl[0]
    progress.close()
    iconimage = xbmc.getInfoImage("ListItem.Thumb")
    listitem = xbmcgui.ListItem(name, iconImage="DefaultVideo.png", thumbnailImage=iconimage)
    listitem.setInfo('video', {'Title': name, 'Genre': 'P**n'})
    xbmc.Player().play(videourl, listitem)
Example #28
0
def Main():
    try:
        args = Info()

        if args.isempty():
            add_directory_items()

        elif args.url:
            title = unicode(xbmc.getInfoLabel("ListItem.Title"), "utf-8")
            plot = unicode(xbmc.getInfoLabel("ListItem.Plot"), "utf-8")
            duration = unicode(xbmc.getInfoLabel("ListItem.Duration"), "utf-8")
            thumb = unicode(xbmc.getInfoImage("ListItem.Thumb"), "utf-8")

            destination = None
            if args.download:
                # default select folder
                if args.tomovie:
                    destination = getBrowseDialog(heading="Select movie to save trailer", dlg_type=1, shares="video")
                else:
                    destination = getBrowseDialog(heading="Choose folder to save trailer")

            xbmc.executebuiltin("ActivateWindow(busydialog)")
            xbmc.sleep(100)
            url = urllib.unquote_plus(args.url)
            media = getVideoFromPageBA(url)

            if destination:
                xbmc.executebuiltin("Dialog.Close(busydialog,true)")
                local_media = download(media, destination, title)
                if local_media:
                    try:
                        local_media = local_media.encode("utf-8")
                    except:
                        pass
                    media = local_media

                # if local_media and os.path.exists( local_media ):
                #    media = local_media
                else:
                    # reload url is expired
                    xbmc.executebuiltin("ActivateWindow(busydialog)")
                    xbmc.sleep(100)
                    url = urllib.unquote_plus(args.url)
                    media = getVideoFromPageBA(url)

            if media:
                listitem = xbmcgui.ListItem(title, "", "DefaultVideo.png", thumb)
                listitem.setInfo("video", {"title": title, "plot": plot, "duration": duration})

                xbmc.Player(xbmc.PLAYER_CORE_DVDPLAYER).play(media, listitem)

            xbmc.executebuiltin("Dialog.Close(busydialog,true)")

        elif args.webbrowser:
            import webbrowser

            webbrowser.open(urllib.unquote_plus(args.webbrowser))
    except:
        print_exc()
Example #29
0
def playvid(videourl, name, download=None):
    if download == 1:
        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'})
        xbmc.Player().play(videourl, listitem)
def NFPlayvid(url, name):
    videopage = utils.getHtml(url, '')
    match = re.compile('<source src="([^"]+)"', re.DOTALL | re.IGNORECASE).findall(videopage)
    videourl = match[0]
    iconimage = xbmc.getInfoImage("ListItem.Thumb")
    listitem = xbmcgui.ListItem(name, iconImage="DefaultVideo.png", thumbnailImage=iconimage)
    listitem.setInfo('video', {'Title': name, 'Genre': 'P**n'})
    xbmc.Player().play(videourl, listitem)
Example #31
0
def PlayLiveLink ( url ): 
#	url = tabURL.replace('%s',channelName);
	req = urllib2.Request(url)
	req.add_header('User-Agent', 'Mozilla/5.0(iPad; U; CPU iPhone OS 3_2 like Mac OS X; en-us) AppleWebKit/531.21.10 (KHTML, like Gecko) Version/4.0.4 Mobile/7B314 Safari/531.21.10')
	response = urllib2.urlopen(req)
	link=response.read()
	response.close()
#	print link
	print url

#	match =re.findall('<script id.+\s+src="(.*)">',link,  re.IGNORECASE)

	match =re.findall('"http.*(ebound).*?\?site=(.*?)"',link,  re.IGNORECASE)[0]


	print match
	cName=match[1]
	newURL='http://www.eboundservices.com/iframe/newads/iframe.php?stream='+ match[1]+'&width=undefined&height=undefined&clip=' + match[1]
	name=match[1];
	print newURL

	
	req = urllib2.Request(newURL)
	req.add_header('User-Agent', 'Mozilla/5.0(iPad; U; CPU iPhone OS 3_2 like Mac OS X; en-us) AppleWebKit/531.21.10 (KHTML, like Gecko) Version/4.0.4 Mobile/7B314 Safari/531.21.10')
	response = urllib2.urlopen(req)
	link=response.read()
	response.close()
	
	
#	match =re.findall('<iframe.+src=\'(.*)\' frame',link,  re.IGNORECASE)
#	print match
#	req = urllib2.Request(match[0])
#	req.add_header('User-Agent', 'Mozilla/5.0(iPad; U; CPU iPhone OS 3_2 like Mac OS X; en-us) AppleWebKit/531.21.10 (KHTML, like Gecko) Version/4.0.4 Mobile/7B314 Safari/531.21.10')
#	response = urllib2.urlopen(req)
#	link=response.read()
#	response.close()
	time = 2000  #in miliseconds
	defaultStreamType=0 #0 RTMP,1 HTTP
	defaultStreamType=selfAddon.getSetting( "DefaultStreamType" ) 
	print 'defaultStreamType',defaultStreamType
	if linkType=="HTTP" or (linkType=="" and defaultStreamType=="1"):
#	print link
		line1 = "Playing Http Stream"
		xbmc.executebuiltin('Notification(%s, %s, %d, %s)'%(__addonname__,line1, time, __icon__))
		
		match =re.findall('MM_openBrWindow\(\'(.*)\',\'ebound\'', link,  re.IGNORECASE)
			
	#	print url
	#	print match
		
		strval = match[0]
		
		#listitem = xbmcgui.ListItem(name)
		#listitem.setInfo('video', {'Title': name, 'Genre': 'Live TV'})
		#playlist = xbmc.PlayList( xbmc.PLAYLIST_VIDEO )
		#playlist.clear()
		#playlist.add (strval)
		
		#xbmc.Player().play(playlist)
		listitem = xbmcgui.ListItem( label = str(name), iconImage = "DefaultVideo.png", thumbnailImage = xbmc.getInfoImage( "ListItem.Thumb" ), path=strval )
		print "playing stream name: " + str(name) 
		listitem.setInfo( type="video", infoLabels={ "Title": name, "Path" : strval } )
		#listitem.setInfo( type="video", infoLabels={ "Title": name, "Plot" : name, "TVShowTitle": name } )
		xbmc.Player( xbmc.PLAYER_CORE_DVDPLAYER ).play( str(strval), listitem)
	else:
		line1 = "Playing RTMP Stream"
		xbmc.executebuiltin('Notification(%s, %s, %d, %s)'%(__addonname__,line1, time, __icon__))
		
		#print link
		match =re.findall("m3u8.*?=(.*)[=]','e", link)

		print url
		print match

		strval = match[0]

		#listitem = xbmcgui.ListItem(name)
		#listitem.setInfo('video', {'Title': name, 'Genre': 'Live TV'})
		#playlist = xbmc.PlayList( xbmc.PLAYLIST_VIDEO )
		#playlist.clear()
		#playlist.add (strval)

		playfile='rtmp://cdn.ebound.tv/tv?wmsAuthSign=/%s app=tv?wmsAuthSign=?%s swfurl=http://www.eboundservices.com/live/v6/player.swf?domain=&channel=%s&country=GB pageUrl=http://www.eboundservices.com/iframe/newads/iframe.php?stream=%s tcUrl=rtmp://cdn.ebound.tv/tv?wmsAuthSign=?%s live=true'	% (cName,strval,cName,cName,strval)
		#playfile='rtmp://cdn.ebound.tv/tv?wmsAuthSign=/humtv app=tv?wmsAuthSign=?%s swfurl=http://www.eboundservices.com/live/v6/player.swf?domain=&channel=humtv&country=GB pageUrl=http://www.eboundservices.com/iframe/newads/iframe.php?stream=humtv tcUrl=rtmp://cdn.ebound.tv/tv?wmsAuthSign=?%s live=true'	% (strval,strval)

		print playfile
		#xbmc.Player().play(playlist)
		listitem = xbmcgui.ListItem( label = str(name), iconImage = "DefaultVideo.png", thumbnailImage = xbmc.getInfoImage( "ListItem.Thumb" ) )
		print "playing stream name: " + str(name) 
		#listitem.setInfo( type="video", infoLabels={ "Title": name, "Path" : playfile } )
		#listitem.setInfo( type="video", infoLabels={ "Title": name, "Plot" : name, "TVShowTitle": name } )
		xbmc.Player( xbmc.PLAYER_CORE_AUTO ).play( playfile, listitem)
	
	
	return
Example #32
0
def PlayStream(sourceEtree, urlSoup, name, url):
	try:
		channelId = urlSoup.url.text
		pDialog = xbmcgui.DialogProgress()
		pDialog.create('XBMC', 'Communicating with SS')
		import base64
		if 1==1:
			liveLink=base64.b64decode('aHR0cDovLzQ2LjEwMS45LjIyNi82MC9jaCVzL2luZGV4Lm0zdTg=')%channelId
			pDialog.create('XBMC', 'Playing channel')
			listitem = xbmcgui.ListItem( label = str(name), iconImage = "DefaultVideo.png", thumbnailImage = xbmc.getInfoImage( "ListItem.Thumb" ), path=liveLink )
			player = CustomPlayer.MyXBMCPlayer()
			start = time.time()  
			player.pdialogue=pDialog
			if pDialog.iscanceled():
				return True
			player.play( liveLink,listitem)  
			if pDialog.iscanceled():
				return True
			#pDialog.close()
			while player.is_active:
				xbmc.sleep(200)
			#return player.urlplayed
			done = time.time()
			elapsed = done - start
			#save file
			if player.urlplayed and elapsed>=3:
				return True
		pDialog.close()
		return False
	except:
		traceback.print_exc(file=sys.stdout)    
	return False  
Example #33
0
def play_video(name, url, cat):
    title = name
    name = clean_file(name)
    name = name[:+32]

    def Download(url, dest):
        dp = xbmcgui.DialogProgress()
        dp.create('Downloading', title, 'Filename: ' + name + '.flv')
        urllib.urlretrieve(
            url,
            dest,
            lambda nb, bs, fs, url=url: _pbhook(nb, bs, fs, url, dp))

    def _pbhook(numblocks, blocksize, filesize, url=None, dp=None):
        try:
            percent = min((numblocks * blocksize * 100) / filesize, 100)
            dp.update(percent)
        except:
            percent = 100
            dp.update(percent)
        if dp.iscanceled():
            dp.close()

    flv_file = None
    stream = 'false'
    if (xbmcplugin.getSetting('download') == 'true'):
        dialog = xbmcgui.Dialog()
        flv_file = dialog.browse(3, 'Choose Download Directory', 'video', '',
                                 False, False, '')
        Download(url, flv_file + name + '.flv')
    elif (xbmcplugin.getSetting('download') == 'false'
          and xbmcplugin.getSetting('download_ask') == 'true'):
        dia = xbmcgui.Dialog()
        ret = dia.select(xbmc.getLocalizedString(30005), [
            xbmc.getLocalizedString(30001),
            xbmc.getLocalizedString(30007),
            xbmc.getLocalizedString(30006)
        ])
        if (ret == 0):
            dialog = xbmcgui.Dialog()
            flv_file = dialog.browse(3, 'Choose Download Directory', 'video',
                                     '', False, False, '')
            Download(url, flv_file + name + '.flv')
        elif (ret == 1):
            stream = 'true'
        else:
            pass
    elif (xbmcplugin.getSetting('download') == 'false'
          and xbmcplugin.getSetting('download_ask') == 'false'):
        stream = 'true'
    if xbmcplugin.getSetting("dvdplayer") == "true":
        player_type = xbmc.PLAYER_CORE_DVDPLAYER
    else:
        player_type = xbmc.PLAYER_CORE_MPLAYER
    g_thumbnail = xbmc.getInfoImage("ListItem.Thumb")
    listitem = xbmcgui.ListItem(title,
                                iconImage="DefaultVideo.png",
                                thumbnailImage=g_thumbnail)
    listitem.setInfo(type="Video",
                     infoLabels={
                         "Title": title,
                         "Director": "G4TV",
                         "Studio": "G4TV",
                         "Genre": cat
                     })
    if (flv_file != None and os.path.isfile(flv_file + name + '.flv')):
        xbmc.Player(player_type).play(flv_file + name + '.flv', listitem)
    elif (stream == 'true'):
        xbmc.Player(player_type).play(str(url), listitem)
    xbmc.sleep(200)
Example #34
0
                thumbnail = thumbnail.encode("utf-8")
            except:
                pass
            # if there is no local tbn file leave blank
            if (not os.path.isfile(thumbnail)):
                thumbnail = ""
        return thumbnail
    except:
        print_exc()
        return ""


#get cached xbmc thumb
try:
    LIST_ITEM_THUMB = xbmc.translatePath(
        xbmc.getInfoImage("ListItem.Thumb")) or get_thumbnail(sys.argv[0] +
                                                              sys.argv[2])
except:
    LIST_ITEM_THUMB = ""
    print_exc()
if not LIST_ITEM_THUMB:
    LIST_ITEM_THUMB = "DefaultPicture.png"


class MainGui(xbmcgui.WindowXMLDialog):
    def __init__(self, *args, **kwargs):
        xbmcgui.WindowXMLDialog.__init__(self, *args, **kwargs)

        #set heading, picture, type, line, yes, no
        self.heading = kwargs.get("heading", "No title")
        self.picture = kwargs.get("picture", "DefaultPicture.png")
def getLibraryInfo(mediaurl):
    '''Obtiene información de la Biblioteca si existe (ficheros strm) o de los parámetros
    '''
    if DEBUG:
        logger.info(
            'streamondemand.platformcode.xbmctools playlist OBTENCIÓN DE DATOS DE BIBLIOTECA'
        )

    # Información básica
    label = xbmc.getInfoLabel('listitem.label')
    label2 = xbmc.getInfoLabel('listitem.label2')
    iconImage = xbmc.getInfoImage('listitem.icon')
    thumbnailImage = xbmc.getInfoImage(
        'listitem.Thumb')  #xbmc.getInfoLabel( 'listitem.thumbnailImage' )
    if DEBUG:
        logger.info("[xbmctools.py]getMediaInfo: label = " + label)
        logger.info("[xbmctools.py]getMediaInfo: label2 = " + label2)
        logger.info("[xbmctools.py]getMediaInfo: iconImage = " + iconImage)
        logger.info("[xbmctools.py]getMediaInfo: thumbnailImage = " +
                    thumbnailImage)

    # Creación de listitem
    listitem = xbmcgui.ListItem(label, label2, iconImage, thumbnailImage,
                                mediaurl)

    # Información adicional
    lista = [
        ('listitem.genre', 's'),  #(Comedy)
        ('listitem.year', 'i'),  #(2009)
        ('listitem.episode', 'i'),  #(4)
        ('listitem.season', 'i'),  #(1)
        ('listitem.top250', 'i'),  #(192)
        ('listitem.tracknumber', 'i'),  #(3)
        ('listitem.rating', 'f'),  #(6.4) - range is 0..10
        #        ('listitem.watched', 'd'),          # depreciated. use playcount instead
        ('listitem.playcount', 'i'
         ),  #(2) - number of times this item has been played
        #        ('listitem.overlay', 'i'),          #(2) - range is 0..8.  See GUIListItem.h for values
        (
            'listitem.overlay', 's'
        ),  #JUR - listitem devuelve un string, pero addinfo espera un int. Ver traducción más abajo
        #('listitem.cast', 's'),             # (Michal C. Hall) - List concatenated into a string
        #('listitem.castandrole', 's'),      #(Michael C. Hall|Dexter) - List concatenated into a string
        ('listitem.director', 's'),  #(Dagur Kari)
        ('listitem.mpaa', 's'),  #(PG-13)
        ('listitem.plot', 's'),  #(Long Description)
        ('listitem.plotoutline', 's'),  #(Short Description)
        ('listitem.title', 's'),  #(Big Fan)
        ('listitem.duration', 's'),  #(3)
        ('listitem.studio', 's'),  #(Warner Bros.)
        ('listitem.tagline',
         's'),  #(An awesome movie) - short description of movie
        ('listitem.writer', 's'),  #(Robert D. Siegel)
        ('listitem.tvshowtitle', 's'),  #(Heroes)
        ('listitem.premiered', 's'),  #(2005-03-04)
        ('listitem.status', 's'),  #(Continuing) - status of a TVshow
        ('listitem.code', 's'),  #(tt0110293) - IMDb code
        ('listitem.aired', 's'),  #(2008-12-07)
        ('listitem.credits', 's'),  #(Andy Kaufman) - writing credits
        ('listitem.lastplayed', 's'),  #(%Y-%m-%d %h
        ('listitem.album', 's'),  #(The Joshua Tree)
        ('listitem.votes', 's'),  #(12345 votes)
        ('listitem.trailer', 's'),  #(/home/user/trailer.avi)
    ]
    # Obtenemos toda la info disponible y la metemos en un diccionario
    # para la función setInfo.
    infodict = dict()
    for label, tipo in lista:
        key = label.split('.', 1)[1]
        value = xbmc.getInfoLabel(label)
        if value != "":
            if DEBUG:
                logger.info("[xbmctools.py]getMediaInfo: " + key + " = " +
                            value)  #infoimage=infolabel
            if tipo == 's':
                infodict[key] = value
            elif tipo == 'i':
                infodict[key] = int(value)
            elif tipo == 'f':
                infodict[key] = float(value)

    #Transforma el valor de overlay de string a int.
    if infodict.has_key('overlay'):
        value = infodict['overlay'].lower()
        if value.find('rar') > -1:
            infodict['overlay'] = 1
        elif value.find('zip') > -1:
            infodict['overlay'] = 2
        elif value.find('trained') > -1:
            infodict['overlay'] = 3
        elif value.find('hastrainer') > -1:
            infodict['overlay'] = 4
        elif value.find('locked') > -1:
            infodict['overlay'] = 5
        elif value.find('unwatched') > -1:
            infodict['overlay'] = 6
        elif value.find('watched') > -1:
            infodict['overlay'] = 7
        elif value.find('hd') > -1:
            infodict['overlay'] = 8
        else:
            infodict.pop('overlay')
    if len(infodict) > 0:
        listitem.setInfo("video", infodict)

    return listitem
Example #36
0
def PlayLiveLink(url):

    progress = xbmcgui.DialogProgress()
    progress.create('Progress', 'Fetching Streaming Info')
    progress.update(10, "", "Finding links..", "")

    if mode == 7:
        req = urllib2.Request(url)
        req.add_header(
            'User-Agent',
            'Mozilla/5.0(iPad; U; CPU iPhone OS 3_2 like Mac OS X; en-us) AppleWebKit/531.21.10 (KHTML, like Gecko) Version/4.0.4 Mobile/7B314 Safari/531.21.10'
        )
        response = urllib2.urlopen(req)
        link = response.read()
        response.close()
        match = re.findall('"http.*(ebound).*?\?site=(.*?)"', link,
                           re.IGNORECASE)[0]
        cName = match[1]
        progress.update(20, "", "Finding links..", "")

    else:
        cName = url
    #match =re.findall('"http.*(ebound).*?\?site=(.*?)"',link,  re.IGNORECASE)[0]

    newURL = 'http://www.eboundservices.com/iframe/newads/iframe.php?stream=' + cName + '&width=undefined&height=undefined&clip=' + cName
    print newURL

    req = urllib2.Request(newURL)
    req.add_header(
        'User-Agent',
        'Mozilla/5.0(iPad; U; CPU iPhone OS 3_2 like Mac OS X; en-us) AppleWebKit/531.21.10 (KHTML, like Gecko) Version/4.0.4 Mobile/7B314 Safari/531.21.10'
    )
    response = urllib2.urlopen(req)
    link = response.read()
    response.close()
    progress.update(50, "", "Finding links..", "")

    #	match =re.findall('<iframe.+src=\'(.*)\' frame',link,  re.IGNORECASE)
    #	print match
    #	req = urllib2.Request(match[0])
    #	req.add_header('User-Agent', 'Mozilla/5.0(iPad; U; CPU iPhone OS 3_2 like Mac OS X; en-us) AppleWebKit/531.21.10 (KHTML, like Gecko) Version/4.0.4 Mobile/7B314 Safari/531.21.10')
    #	response = urllib2.urlopen(req)
    #	link=response.read()
    #	response.close()
    time = 2000  #in miliseconds
    defaultStreamType = 0  #0 RTMP,1 HTTP
    defaultStreamType = selfAddon.getSetting("DefaultStreamType")
    print 'defaultStreamType', defaultStreamType
    if 1 == 2 and (linkType == "HTTP" or
                   (linkType == "" and defaultStreamType
                    == "1")):  #disable http streaming for time being
        #	print link
        line1 = "Playing Http Stream"
        xbmc.executebuiltin('Notification(%s, %s, %d, %s)' %
                            (__addonname__, line1, time, __icon__))

        match = re.findall('MM_openBrWindow\(\'(.*)\',\'ebound\'', link,
                           re.IGNORECASE)

        #	print url
        #	print match

        strval = match[0]

        #listitem = xbmcgui.ListItem(name)
        #listitem.setInfo('video', {'Title': name, 'Genre': 'Live TV'})
        #playlist = xbmc.PlayList( xbmc.PLAYLIST_VIDEO )
        #playlist.clear()
        #playlist.add (strval)

        #xbmc.Player().play(playlist)
        listitem = xbmcgui.ListItem(
            label=str(cName),
            iconImage="DefaultVideo.png",
            thumbnailImage=xbmc.getInfoImage("ListItem.Thumb"),
            path=strval)
        print "playing stream name: " + str(cName)
        listitem.setInfo(type="video",
                         infoLabels={
                             "Title": cName,
                             "Path": strval
                         })
        listitem.setInfo(type="video",
                         infoLabels={
                             "Title": cName,
                             "Plot": cName,
                             "TVShowTitle": cName
                         })
        xbmc.Player().play(str(strval), listitem)
    else:
        line1 = "Playing RTMP Stream"
        xbmc.executebuiltin('Notification(%s, %s, %d, %s)' %
                            (__addonname__, line1, time, __icon__))
        progress.update(60, "", "Finding links..", "")

        post = {'username': '******'}
        post = urllib.urlencode(post)
        req = urllib2.Request(
            'http://eboundservices.com/flashplayerhash/index.php')
        req.add_header(
            'User-Agent',
            'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/33.0.1750.117 Safari/537.36'
        )
        response = urllib2.urlopen(req, post)
        link = response.read()
        response.close()

        print link
        #match =re.findall("=(.*)", link)

        #print url
        #print match

        strval = link  # match[0]

        #listitem = xbmcgui.ListItem(name)
        #listitem.setInfo('video', {'Title': name, 'Genre': 'Live TV'})
        #playlist = xbmc.PlayList( xbmc.PLAYLIST_VIDEO )
        #playlist.clear()
        #playlist.add (strval)

        playfile = 'rtmp://cdn.ebound.tv/tv?wmsAuthSign=/%s app=tv?wmsAuthSign=?%s swfurl=http://www.eboundservices.com/live/v6/player.swf?domain=&channel=%s&country=GB pageUrl=http://www.eboundservices.com/iframe/newads/iframe.php?stream=%s tcUrl=rtmp://cdn.ebound.tv/tv?wmsAuthSign=?%s live=true timeout=15' % (
            cName, strval, cName, cName, strval)
        #playfile='rtmp://cdn.ebound.tv/tv?wmsAuthSign=/humtv app=tv?wmsAuthSign=?%s swfurl=http://www.eboundservices.com/live/v6/player.swf?domain=&channel=humtv&country=GB pageUrl=http://www.eboundservices.com/iframe/newads/iframe.php?stream=humtv tcUrl=rtmp://cdn.ebound.tv/tv?wmsAuthSign=?%s live=true'	% (strval,strval)
        progress.update(100, "", "Almost done..", "")
        print playfile
        #xbmc.Player().play(playlist)
        listitem = xbmcgui.ListItem(
            label=str(name),
            iconImage="DefaultVideo.png",
            thumbnailImage=xbmc.getInfoImage("ListItem.Thumb"))
        print "playing stream name: " + str(name)
        #listitem.setInfo( type="video", infoLabels={ "Title": name, "Path" : playfile } )
        #listitem.setInfo( type="video", infoLabels={ "Title": name, "Plot" : name, "TVShowTitle": name } )
        xbmc.Player().play(playfile, listitem)
        #xbmcplugin.setResolvedUrl(int(sys.argv[1]), True, listitem)

    return
Example #37
0
def PlayStream(sourceEtree, urlSoup, name, url):
    try:
        #url = urlSoup.url.text
        pDialog = xbmcgui.DialogProgress()
        pDialog.create('XBMC', 'Parsing the xml file')
        pDialog.update(10, 'fetching channel info')
        title = ''
        link = ''
        sc = ''
        try:
            link = urlSoup.item.link.text
            sc = sourceEtree.findtext('sname')
            title = urlSoup.item.title.text
        except:
            pass
        if link == '':
            timeD = 2000  #in miliseconds
            line1 = "couldn't read title and link"
            xbmc.executebuiltin('Notification(%s, %s, %d, %s)' %
                                (__addonname__, line1, timeD, __icon__))
            return False
        regexs = urlSoup.find('regex')
        pDialog.update(20, 'Parsing info')
        if (not regexs == None) and len(regexs) > 0:
            liveLink = getRegexParsed(urlSoup, link)
        else:
            liveLink = link

        if len(liveLink) == 0:
            timeD = 2000  #in miliseconds
            line1 = "couldn't read title and link"
            xbmc.executebuiltin('Notification(%s, %s, %d, %s)' %
                                (__addonname__, line1, timeD, __icon__))
            return False

        timeD = 2000  #in miliseconds
        line1 = "Resource found,playing now."
        pDialog.update(30, line1)
        liveLink = replaceSettingsVariables(liveLink)
        name += '-' + sc + ':' + title
        if (sc == 'GLArab' or sc == 'Local') and '$GL-' in liveLink:
            gcid = None
            try:
                gcid = urlSoup.item.glchannelid.text
                if gcid and len(gcid) == 0: gcid = None
            except:
                pass
            liveLink = replaceGLArabVariables(liveLink, pDialog, gcid, title)
            if liveLink == "": return False
        print 'liveLink', liveLink
        pDialog.close()
        listitem = xbmcgui.ListItem(
            label=str(name),
            iconImage="DefaultVideo.png",
            thumbnailImage=xbmc.getInfoImage("ListItem.Thumb"),
            path=liveLink)
        if not 'plugin.video.f4mTester' in liveLink:
            player = CustomPlayer.MyXBMCPlayer()
            start = time.time()
            #xbmc.Player().play( liveLink,listitem)
            player.play(liveLink, listitem)
            xbmc.sleep(2000)
            while player.is_active:
                xbmc.sleep(200)
            #return player.urlplayed
            done = time.time()
            elapsed = done - start
            if player.urlplayed and elapsed >= 3:
                return True
            else:
                return False
        else:
            xbmc.executebuiltin('XBMC.RunPlugin(' + liveLink + ')')
            return True

    except:
        traceback.print_exc(file=sys.stdout)
    return False
Example #38
0
def PHVideo(url, name, download=None):
    progress.create('Play video', 'Searching videofile.')
    progress.update(10, "", "Loading video page", "")
    Supported_hosts = [
        'Openload.io', 'StreamCloud', 'NowVideo', 'www.nowvideo.sx', 'FlashX',
        'www.flashx.tv', 'streamcloud.eu', 'streamin.to', 'videowood.tv',
        'www.keeplinks.eu'
    ]
    videopage = utils.getHtml(url, '')
    match = re.compile(
        r'<li id="link-([^"]+).*?xs-12">\s+Watch it on ([\w\.]+)',
        re.DOTALL | re.IGNORECASE).findall(videopage)
    if len(match) > 1:
        sites = []
        vidurls = []
        for videourl, site in match:
            if site in Supported_hosts:
                sites.append(site)
                vidurls.append(videourl)
        if len(sites) == 1:
            sitename = match[0][1]
            siteurl = match[0][0]
        elif len(sites) > 1:
            site = utils.dialog.select('Select video site', sites)
            sitename = sites[site]
            siteurl = vidurls[site]
        else:
            utils.notify('Sorry', 'No supported hosts found.')
            return
    else:
        sitename = match[0][1]
        siteurl = match[0][0]
    outurl = "http://www.pornhive.tv/en/out/" + siteurl
    progress.update(20, "", "Getting video page", "")
    if 'loud' in sitename:
        progress.update(30, "", "Getting StreamCloud", "")
        playurl = getStreamCloud(outurl)
    elif "lash" in sitename:
        progress.update(30, "", "Getting FlashX", "")
        playurl = getFlashX(outurl)
    elif sitename == "NowVideo" or sitename == "www.nowvideo.sx":
        progress.update(30, "", "Getting NowVideo", "")
        playurl = getNowVideo(outurl)
    elif "Openload" in sitename:
        progress.update(30, "", "Getting Openload", "")
        progress.close()
        utils.PLAYVIDEO(outurl, name, download)
        return
    elif "videowood" in sitename:
        progress.update(30, "", "Getting Videowood", "")
        progress.close()
        utils.PLAYVIDEO(outurl, name, download)
        return
    elif "streamin" in sitename:
        progress.update(30, "", "Getting Streamin", "")
        streaming = utils.getHtml(outurl, '')
        outurl = re.compile("action='([^']+)'").findall(streaming)[0]
        progress.close()
        utils.playvideo(outurl, name, download)
        return
    if 'keeplinks' in sitename:
        progress.update(30, "", "Getting Keeplinks", "")
        outurl2 = getKeeplinks(outurl)
        utils.playvideo(outurl2, name, download, outurl)
        return
    else:
        progress.close()
        utils.notify('Sorry', 'This host is not supported.')
        return
    progress.update(90, "", "Playing video", "")
    progress.close()
    if playurl:
        if download == 1:
            utils.downloadVideo(playurl, name)
        else:
            iconimage = xbmc.getInfoImage("ListItem.Thumb")
            listitem = xbmcgui.ListItem(name,
                                        iconImage="DefaultVideo.png",
                                        thumbnailImage=iconimage)
            listitem.setInfo('video', {'Title': name, 'Genre': 'P**n'})
            xbmc.Player().play(playurl, listitem)
Example #39
0
def PlayStream(url, name, mode):

	if mode==10:
		req = urllib2.Request(url)
		req.add_header('User-Agent','Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/33.0.1750.154 Safari/537.36')
		response = urllib2.urlopen(req)
		link=response.read()
		response.close()
		match =re.findall('file: "rtmp([^"]*)', link)

		rtmpLink=match[0]
		#rtmpLink='://192.95.32.7:1935/live/dubai_sport?user=MjA5N2Q3YjA2M2Q2ZjhiNWNjODAzYWJmM2RmNzU4YWE=&pass=fc9226bd032346a2deab1f903652229b'
		liveLink="rtmp%s app=live/ swfUrl=http://www.hdarabic.com/jwplayer.flash.swf pageUrl=http://www.hdarabic.com live=1 timeout=15"%rtmpLink
	else:
		newURL='http://www.teledunet.com/tv_/?channel=%s&no_pub'%url
		req = urllib2.Request(newURL)
		req.add_header('User-Agent','Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/33.0.1750.154 Safari/537.36')
		req.add_header('Referer',newURL)

		response = urllib2.urlopen(req)
		link=response.read()
		response.close()
		match =re.findall('time_player=(.*?);', link)
		match=str(long(float(match[0])))

		liveLink='rtmp://5.135.134.110:1935/teledunet playpath=%s swfUrl=http://www.teledunet.com/tv_/player.swf?id0=%s&skin=bekle/bekle.xml&channel=%s  pageUrl=http://www.teledunet.com/tv_/?channel=%s&no_pub live=1  timeout=15'%(url,match,url,url)
		
	#print 'liveLink',liveLink

	listitem = xbmcgui.ListItem( label = str(name), iconImage = "DefaultVideo.png", thumbnailImage = xbmc.getInfoImage( "ListItem.Thumb" ), path=liveLink )
	xbmc.Player().play( liveLink,listitem)
Example #40
0
def PlayStream(sourceEtree, urlSoup, name, url):
    try:
        channelId = urlSoup.url.text
        pDialog = xbmcgui.DialogProgress()
        pDialog.create('XBMC', 'Communicating with Teledunet')
        pDialog.update(10, 'fetching channel page')
        loginName = selfAddon.getSetting("teledunetTvLogin")

        if 1 == 1:
            newURL = 'http://www.teledunet.com/mobile/'
            print 'newURL', newURL
            #req = urllib2.Request(newURL)
            #req.add_header('User-Agent','Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/33.0.1750.154 Safari/537.36')
            #req.add_header('Referer',newURL)
            #response = urllib2.urlopen(req)
            #link=response.read()
            #response.close()
            token = ''
            try:
                link = None
                result = getChannelHTML(channelId)
                #cache2Hr.cacheFunction(getChannelHTML)

                if result:
                    link = result['link']
                    token = result['token']
                    print 'file_exists', len(link)
                else:
                    print 'cache or the url failed!!'
                #file_exists=cache2Hr.get('MainChannelPage')

                #if file_exists and file_exists=='yes':
                #	print 'it says use local file'
                #	link=getStoredFile(teledunet_htmlfile)

                #if link==None:
                #	print 'Oopps, not using local file'
                #	if not loginName=="":
                #		if shouldforceLogin():
                #			if performLogin():
                #				print 'done login'
                #			else:
                #				print 'login failed??'
                #		else:
                #			print 'Login not forced.. perhaps reusing the session'
                #	else:
                #		print 'login name not defined'

                #	link=getUrl(newURL,getCookieJar() ,None,'http://www.teledunet.com/')
                #if storeInFile(link,teledunet_htmlfile):
                #	cache2Hr.set('MainChannelPage','yes')
                #	print 'Stored in local file',cache2Hr.get('MainChannelPage')

                if 'fromspacer' in link:
                    match = re.findall('fromspacer\((.*?)\)', link)
                else:
                    match = re.findall('aut=\'\?id0=(.*?)\'', link)
                print match
                timesegment = str(long(float(match[0])))
                if timesegment == "0":
                    print 1 / 0
                    #produce error

                rtmp = re.findall(('rtmp://(.*?)/%s\'' % channelId), link)[0]
                rtmp = 'rtmp://%s/%s' % (rtmp, channelId)
                #if '5.135.134.110' in rtmp and 'bein' in channelId:
                #	rtmp=rtmp.replace('5.135.134.110','www.teledunet.com')
            except:
                clearFileCache()
                traceback.print_exc(file=sys.stdout)
                print 'trying backup'
                try:
                    link = getUrl(
                        "http://www.pastebin.com/download.php?i=fKh4gG5s",
                        getCookieJar())
                    rtmp = re.findall(('rtmp://(.*?)/%s\'' % channelId),
                                      link)[0]
                    rtmp = 'rtmp://%s/%s' % (rtmp, channelId)
                except:
                    traceback.print_exc(file=sys.stdout)
                    rtmp = 'rtmp://5.135.134.110:1935/teledunet/%s' % (
                        channelId)
                    print 'error in channel using hardcoded value'
        pDialog.update(80, 'trying to play')
        liveLink = sourceEtree.findtext('rtmpstring')

        print 'rtmpstring', liveLink, rtmp
        #		liveLink=liveLink%(rtmp,channelId,match,channelId,channelId)
        liveLink = liveLink % (rtmp, channelId, timesegment, channelId,
                               'user' + token, token)
        name += '-Teledunet'
        print 'liveLink', liveLink
        pDialog.close()
        totalTried = 0
        howMaytimes = 15
        try:
            howMaytimes = int(selfAddon.getSetting("teledunetRetryCount"))
        except:
            pass

        pDialog = xbmcgui.DialogProgress()
        pDialog.create('XBMC', 'Playing channel')
        howMaytimes = 1
        while totalTried < howMaytimes:

            totalTried += 1
            pDialog.update((totalTried * 100) / howMaytimes,
                           'Teledunet: Try #' + str(totalTried) + ' of ' +
                           str(howMaytimes))
            listitem = xbmcgui.ListItem(
                label=str(name),
                iconImage="DefaultVideo.png",
                thumbnailImage=xbmc.getInfoImage("ListItem.Thumb"),
                path=liveLink)
            player = CustomPlayer.MyXBMCPlayer()
            #xbmc.Player().play( liveLink,listitem)
            start = time.time()
            player.pdialogue = pDialog
            if pDialog.iscanceled():
                break
            player.play(liveLink, listitem)
            if pDialog.iscanceled():
                break
            #pDialog.close()
            while player.is_active:
                xbmc.sleep(200)
            #return player.urlplayed
            done = time.time()
            elapsed = done - start
            #save file
            if player.urlplayed and elapsed >= 3:
                return True
        pDialog.close()
        return False
    except:
        traceback.print_exc(file=sys.stdout)
    return False
Example #41
0
def play_video(name,url):
	title=name
	name=clean_file(name)
	name=name[:+32]
	def Download(url,dest):
			dp = xbmcgui.DialogProgress()
			dp.create('Downloading',title,'Filename: '+name+ '.flv')
			urllib.urlretrieve(url,dest,lambda nb, bs, fs, url=url: _pbhook(nb,bs,fs,url,dp))
	def _pbhook(numblocks, blocksize, filesize, url=None,dp=None):
			try:
					percent = min((numblocks*blocksize*100)/filesize, 100)
					dp.update(percent)
			except:
					percent = 100
					dp.update(percent)
			if dp.iscanceled():
					dp.close()
	flv_file = None
	stream = 'false'
	if (xbmcplugin.getSetting('download') == 'true'):
		if (xbmcplugin.getSetting('ask_filename') == 'true'):
			searchStr = name
			keyboard = xbmc.Keyboard(searchStr, "Save as:")
			keyboard.doModal()
			if (keyboard.isConfirmed() == False):
				return
			searchstring = keyboard.getText()
			name=searchstring
		flv_file = xbmc.translatePath(os.path.join(xbmcplugin.getSetting('download_Path'), name + '.flv' ))
		Download(url,flv_file)
	elif (xbmcplugin.getSetting('download') == 'false' and xbmcplugin.getSetting('download_ask') == 'true'):
		dia = xbmcgui.Dialog()
		ret = dia.select('What do you want to do?', ['Download & Play', 'Stream', 'Exit'])
		if (ret == 0):
			if (xbmcplugin.getSetting('ask_filename') == 'true'):
				searchStr = name
				keyboard = xbmc.Keyboard(searchStr, "Save as:")
				keyboard.doModal()
				if (keyboard.isConfirmed() == False):
					return
				searchstring = keyboard.getText()
				name=searchstring
			flv_file = xbmc.translatePath(os.path.join(xbmcplugin.getSetting('download_Path'), name + '.flv'))
			Download(url,flv_file)
		elif (ret == 1):
			stream = 'true'
		else:
			pass
	elif (xbmcplugin.getSetting('download') == 'false' and xbmcplugin.getSetting('download_ask') == 'false'):
		stream = 'true'
	if xbmcplugin.getSetting("dvdplayer") == "true":
		player_type = xbmc.PLAYER_CORE_DVDPLAYER
	else:
		player_type = xbmc.PLAYER_CORE_MPLAYER
	g_thumbnail = xbmc.getInfoImage( "ListItem.Thumb" )
	listitem=xbmcgui.ListItem(title ,iconImage="DefaultVideo.png", thumbnailImage=g_thumbnail)
	if (flv_file != None and os.path.isfile(flv_file)):
		xbmc.Player(player_type).play(str(flv_file), listitem)
	elif (stream == 'true'):
		xbmc.Player(player_type).play(str(url), listitem)
	xbmc.sleep(200)
    def playVideo(self):
        #
        # Init
        #
        no_url_found = False
        unplayable_media_file = False
        have_valid_url = False

        #
        # Get current list item details...
        #
        # title = unicode(xbmc.getInfoLabel("listitem.Title"), "utf-8")
        thumbnail_url = xbmc.getInfoImage("list_item.Thumb")
        # studio = unicode(xbmc.getInfoLabel("list_item.Studio"), "utf-8")
        plot = unicode(xbmc.getInfoLabel("list_item.Plot"), "utf-8")
        genre = unicode(xbmc.getInfoLabel("list_item.Genre"), "utf-8")

        #
        # Show wait dialog while parsing data...
        #
        dialog_wait = xbmcgui.DialogProgress()
        dialog_wait.create(LANGUAGE(30504), self.title)
        # wait 1 second
        xbmc.sleep(1000)

        # Set cookies for cookie-firewall and nsfw-switch
        if SETTINGS.getSetting('nsfw') == 'true':
            cookies = {"Cookie": "cpc=10", "nsfw": "1"}
        else:
            cookies = {"Cookie": "cpc=10"}

            # Make a session
            sess = requests.session()

            # Set cookies for cookie-firewall and nsfw-switch
            if SETTINGS.getSetting('nsfw') == 'true':
                cookies = {"Cookie": "cpc=10", "nsfw": "1"}
            else:
                cookies = {"Cookie": "cpc=10"}

            # Determine if cloudflare protection is active or not
            html_source = sess.get(self.video_page_url, cookies=cookies).text
            if str(html_source).find("cloudflare") >= 0:
                cloudflare_active = True
            else:
                cloudflare_active = False

            # Get the page
            if cloudflare_active == True:
                try:
                    import cfscrape
                except:
                    xbmcgui.Dialog().ok(LANGUAGE(30000), LANGUAGE(30513))
                    sys.exit(1)
                try:
                    # returns a CloudflareScraper instance
                    scraper = cfscrape.create_scraper(sess)
                except:
                    xbmcgui.Dialog().ok(LANGUAGE(30000), LANGUAGE(30514))
                    sys.exit(1)
                try:
                    html_source = scraper.get(self.video_page_url).content
                except:
                    xbmcgui.Dialog().ok(LANGUAGE(30000), LANGUAGE(30515))
                    sys.exit(1)

        soup = BeautifulSoup(html_source)

        video_url = ''
        # <div class="videoplayer" id="video1" data-files="eyJmbHYiOiJodHRwOlwvXC9tZWRpYS5kdW1wZXJ0Lm5sXC9mbHZcLzI4OTE2NWRhXzEwMjU1NzUyXzYzODMxODA4OTU1NDc2MV84MTk0MzU3MDVfbi5tcDQuZmx2IiwidGFibGV0IjoiaHR0cDpcL1wvbWVkaWEuZHVtcGVydC5ubFwvdGFibGV0XC8yODkxNjVkYV8xMDI1NTc1Ml82MzgzMTgwODk1NTQ3NjFfODE5NDM1NzA1X24ubXA0Lm1wNCIsIm1vYmlsZSI6Imh0dHA6XC9cL21lZGlhLmR1bXBlcnQubmxcL21vYmlsZVwvMjg5MTY1ZGFfMTAyNTU3NTJfNjM4MzE4MDg5NTU0NzYxXzgxOTQzNTcwNV9uLm1wNC5tcDQiLCJzdGlsbCI6Imh0dHA6XC9cL3N0YXRpYy5kdW1wZXJ0Lm5sXC9zdGlsbHNcLzY1OTM1MjRfMjg5MTY1ZGEuanBnIn0="></div></div>
        video_urls = soup.findAll('div', attrs={'class': re.compile("video")}, limit=1)
        if len(video_urls) == 0:
            no_url_found = True
        else:
            video_url_enc = video_urls[0]['data-files']
            # base64 decode
            video_url_dec = str(base64.b64decode(video_url_enc))
            # {"flv":"http:\/\/media.dumpert.nl\/flv\/5770e490_Jumbo_KOOP_DAN__Remix.avi.flv","tablet":"http:\/\/media.dumpert.nl\/tablet\/5770e490_Jumbo_KOOP_DAN__Remix.avi.mp4","mobile":"http:\/\/media.dumpert.nl\/mobile\/5770e490_Jumbo_KOOP_DAN__Remix.avi.mp4","720p":"http:\/\/media.dumpert.nl\/720p\/5770e490_Jumbo_KOOP_DAN__Remix.avi.mp4","still":"http:\/\/static.dumpert.nl\/stills\/6593503_5770e490.jpg"}
            # or
            # {"embed":"youtube:U89fl5fZETE","still":"http:\/\/static.dumpert.nl\/stills\/6650228_24eed546.jpg"}

            xbmc.log("[ADDON] %s v%s (%s) debug mode, %s = %s" % (
                    ADDON, VERSION, DATE, "video_url_dec", str(video_url_dec)), xbmc.LOGDEBUG)

            # convert string to dictionary
            video_url_dec_dict = ast.literal_eval(video_url_dec)

            video_url_embed = ''
            try:
                video_url_embed = str(video_url_dec_dict['embed'])
                embed_found = True
            except KeyError:
                embed_found = False

            video_url = ''
            if embed_found:
                # make youtube plugin url
                youtube_id = video_url_embed.replace("youtube:", "")
                youtube_url = 'plugin://plugin.video.youtube/play/?video_id=%s' % youtube_id
                video_url = youtube_url
                have_valid_url = True
                xbmc.log("[ADDON] %s v%s (%s) debug mode, %s = %s" % (
                        ADDON, VERSION, DATE, "video_url1", str(video_url)), xbmc.LOGDEBUG)
            else:
                # matching the desired and available quality
                if self.VIDEO == '0':
                    try:
                        video_url = str(video_url_dec_dict['mobile'])
                    except KeyError:
                        no_url_found = True
                elif self.VIDEO == '1':
                    try:
                        video_url = str(video_url_dec_dict['tablet'])
                    except KeyError:
                        try:
                            video_url = str(video_url_dec_dict['mobile'])
                        except KeyError:
                            no_url_found = True
                elif self.VIDEO == '2':
                    try:
                        video_url = str(video_url_dec_dict['720p'])
                    except KeyError:
                        try:
                            video_url = str(video_url_dec_dict['tablet'])
                        except KeyError:
                            try:
                                video_url = str(video_url_dec_dict['mobile'])
                            except KeyError:
                                no_url_found = True

                if no_url_found:
                    pass
                else:
                    video_url = video_url.replace('\/', '/')
                    xbmc.log("[ADDON] %s v%s (%s) debug mode, %s = %s" % (
                            ADDON, VERSION, DATE, "video_url2", str(video_url)), xbmc.LOGDEBUG)

                    # The need for speed: let's guess that the video-url exists
                    have_valid_url = True

        # Play video...
        if have_valid_url:
            list_item = xbmcgui.ListItem(path=video_url)
            xbmcplugin.setResolvedUrl(self.plugin_handle, True, list_item)
        #
        # Alert user
        #
        elif no_url_found:
            xbmcgui.Dialog().ok(LANGUAGE(30000), LANGUAGE(30505))
        elif unplayable_media_file:
            xbmcgui.Dialog().ok(LANGUAGE(30000), LANGUAGE(30506))
Example #43
0
def PlayStream(sourceEtree, urlSoup, name, url):
	try:
		playpath=urlSoup.chnumber.text
		page_name=urlSoup.link.text
		pDialog = xbmcgui.DialogProgress()
		pDialog.create('XBMC', 'Communicating with Livetv')
		pDialog.update(40, 'Attempting to Login')
		
		retryPlay=True
		liveTvPremiumCode=selfAddon.getSetting( "liveTvPremiumCode" )
		liveTvNonPremiumCode=selfAddon.getSetting( "liveTvNonPremiumCode" )
		if 1==2 and liveTvPremiumCode=="" and liveTvNonPremiumCode=="":
				pDialog.close()
				Msg="Please login using Livetv login option on main menu."
				dialog = xbmcgui.Dialog()
				ok = dialog.ok('Livetv Login', Msg)
				return False

		lastWorkingCode=selfAddon.getSetting( "lastLivetvWorkingCode" )
		while retryPlay:
			retryPlay=False
			usingLastWorkingCode=False
			disableFreeForNow=True# Tick tock tick tock.. you were lucking that you didn't play the game. but no more games anymore :(
			#dont worry, its still disable
			if liveTvPremiumCode=="":
				if lastWorkingCode=="" and liveTvNonPremiumCode=="":#this shouldn't happen now
					#timeD = 2000  #in miliseconds
					#line1="Login disabled, use Non Premium code"
					#xbmc.executebuiltin('Notification(%s, %s, %d, %s)'%(__addonname__,line1, timeD, __icon__))
					#return False
					print 'no code speficied'
					#no login for time being ;)
				if lastWorkingCode=="" and liveTvNonPremiumCode=="" : #stop free account
					if 1==2 and shouldforceLogin():
						print 'performing login'
						if not performLogin():
							timeD = 1000  #in miliseconds
							line1="Login failed-still trying"
							xbmc.executebuiltin('Notification(%s, %s, %d, %s)'%(__addonname__,line1, timeD, __icon__))
						else:
							
							print 'login worked!'

					else:
						print 'not performing login, reusing cache'
					code=getcode(page_name);
					if code==None or len(code)==0:
							timeD = 2000  #in miliseconds
							line1="Unable to get the code-livetv down? or something changed"
							xbmc.executebuiltin('Notification(%s, %s, %d, %s)'%(__addonname__,line1, timeD, __icon__))
							return False
				else:
					code=getcode(page_name);
					if code==None or len(code)==0:
							timeD = 2000  #in miliseconds
							line1="Premium page?"
							xbmc.executebuiltin('Notification(%s, %s, %d, %s)'%(__addonname__,line1, timeD, __icon__))
							#return False
							code=lastWorkingCode
					#print 'using last working code',lastWorkingCode
					#if not lastWorkingCode=="":
					#	code=lastWorkingCode
					#	usingLastWorkingCode=True
					#else:
					#	code=liveTvNonPremiumCode
					
			else:
				print 'using premium code',lastWorkingCode
				code=liveTvPremiumCode

			print 'firstCode',code
			


			liveLink= sourceEtree.findtext('rtmpstring')
			pDialog.update(80, 'Login Completed, now playing')
			print 'rtmpstring',liveLink
			if liveTvPremiumCode=="":
				page_url=None
				try:
					page_url=urlSoup.link.text
				except:
					page_url=makeUrl(urlSoup.cname.text)
				liveLink=liveLink%(playpath,code,page_url)
				#liveLink="rtmp://tdsiptv.ddns.me/live/%s?code=%s"%(playpath,code)
			else:
				liveLink="rtmp://tdsiptv.ddns.me/live/%s?code=%s"%(playpath,liveTvPremiumCode)
			name+='-LiveTV'
			print 'liveLink',liveLink
			listitem = xbmcgui.ListItem( label = str(name), iconImage = "DefaultVideo.png", thumbnailImage = xbmc.getInfoImage( "ListItem.Thumb" ), path=liveLink )
			pDialog.close()
			player = CustomPlayer.MyXBMCPlayer()
			start = time.time()
			#xbmc.Player().play( liveLink,listitem)
			player.play( liveLink,listitem)
			while player.is_active:
				xbmc.sleep(200)
			#return player.urlplayed
			#done = time.time()
			done = time.time()
			elapsed = done - start
			if player.urlplayed and elapsed>=3:
				selfAddon.setSetting( id="lastLivetvWorkingCode" ,value=code)
				return True
			else:
				#selfAddon.setSetting( id="lastLivetvWorkingCode" ,value="")
				lastWorkingCode=""
				#retryPlay=usingLastWorkingCode#this is not required
		return False
	except:
		traceback.print_exc(file=sys.stdout)    
	return False    
Example #44
0
    def playVideo(self):
        #
        # Init
        #
        video_url = ""
        dialog_wait = xbmcgui.DialogProgress()

        #
        # Get current list item details...
        #
        # title = convertToUnicodeString(xbmc.getInfoLabel("list_item.Title"))
        thumbnail_url = convertToUnicodeString(
            xbmc.getInfoImage("list_item.Thumb"))
        # studio = convertToUnicodeString(xbmc.getInfoLabel("list_item.Studio"))
        # plot = convertToUnicodeString(xbmc.getInfoLabel("list_item.Plot"))
        # genre = convertToUnicodeString(xbmc.getInfoLabel("list_item.Genre"))

        try:
            # requests is sooooo nice, respect!
            session = requests.Session()

            # get the page that contains the video
            response = session.get(self.video_page_url)

            html_source = response.text
            html_source = convertToUnicodeString(html_source)

            # is it a premium-only video? (f.e. https://www.gamekings.tv/premium/110853/)
            # <div class="video__premiumonly">
            #     <div class="video__premiumonlywrapper">
            #         <h3 class="video__notice">Premium <span>Content</span></h3>
            #         <a href="#" class="field__button  js-login">Log in</a>
            #         <span class="video__or-text">of</span>
            #         <a href="https://www.gamekings.tv/get-premium/" class="field__button  field__button--premium">Word Premium</a>
            #     </div>
            # </div>

            if str(html_source).find('premiumonly') >= 0:
                if self.IS_PREMIUM_MEMBER:
                    try:
                        # we need a NEW (!!!) session
                        session = requests.Session()

                        # # get the login-page
                        # response = session.get(LOGINURL)
                        # html_source = reply.text
                        # html_source = convertToUnicodeString(html_source)
                        #
                        # log("login-page", html_source)
                        #
                        # the login page should contain something like this
                        #  <input type="text" name="log" id="user_login" ...
                        # ...
                        # <input type="password" name="pwd" id="user_pass" ...

                        payload = {
                            'log': SETTINGS.getSetting('username'),
                            'pwd': SETTINGS.getSetting('password')
                        }

                        # post the LOGIN-page with the LOGIN-data, to actually login this session
                        response = session.post(LOGIN_URL, data=payload)

                        html_source = response.text
                        html_source = convertToUnicodeString(html_source)

                        # check that the login was technically ok (status_code 200).
                        # This in itself does NOT mean that the username/password were correct.
                        if response.status_code == 200:
                            # check that 'login_error' is in the response. If that's the case, the login was not ok
                            # and the username and password in settings are not ok.
                            if str(html_source).find('login_error') >= 0:
                                xbmcgui.Dialog().ok(LANGUAGE(30000),
                                                    LANGUAGE(30601),
                                                    LANGUAGE(30602),
                                                    LANGUAGE(30603))
                                sys.exit(1)
                            else:
                                # dialog_wait.create("Login Successfull", "Currently looking for video")

                                log("self.video_page_url",
                                    "login was succesfull!!")

                                # let's try getting the page again after a login, hopefully it contains a link to
                                # the video now
                                response = session.get(self.video_page_url)

                                # log("retrieved page", self.video_page_url)
                        else:
                            # Something went wrong with logging in
                            xbmcgui.Dialog().ok(
                                LANGUAGE(30000),
                                LANGUAGE(30604) % (str(response.status_code)))
                            sys.exit(1)

                    except urllib.error.HTTPError as error:

                        log("HTTPerror1", error)

                        xbmcgui.Dialog().ok(LANGUAGE(30000),
                                            LANGUAGE(30606) % (str(error)))
                        sys.exit(1)
                    except:
                        exception = sys.exc_info()[0]

                        log("Exception1", exception)

                        sys.exit(1)
                # This is a premium video and the Premium-membership-switch in the settings is off
                else:
                    xbmcgui.Dialog().ok(LANGUAGE(30000), LANGUAGE(30605))
                    sys.exit(1)

        except urllib.error.HTTPError as error:

            log("HTTPerror2", error)

            xbmcgui.Dialog().ok(LANGUAGE(30000),
                                LANGUAGE(30606) % (str(error)))
            sys.exit(1)
        except:
            exception = sys.exc_info()[0]

            log("Exception2", exception)

            sys.exit(1)

        html_source = response.text
        html_source = convertToUnicodeString(html_source)

        have_valid_url = False
        no_url_found = True
        youtube_id = ''

        # encoded container with the m3u8 url:
        # "c34696670236c6163737d32256d6265646d236f6e6471696e6562722e3c396662716d656027796464786d3226343032202865696768647d3223363032202372736d322
        # 8647470737a3f2f27616d656b696e67637e2763646e6e236f6f267964656f637f243435373f58507235454f4d6463335074405262335
        # 2202662716d65626f627465627d32203220216c6c6f6776657c6c63736275656e6e3c3f296662716d656e3c3f2469667e3"
        # Let's get the encoded video url, in the example above that's the second line
        start_pos_encoded_m3u8_url = html_source.find(
            HTTPSCOLONSLASHSLASH_ENCODED)
        if start_pos_encoded_m3u8_url >= 0:

            # log("start_pos_encoded_m3u8_url", start_pos_encoded_m3u8_url)

            end_pos_encoded_m3u8_url = html_source[
                start_pos_encoded_m3u8_url:].find(END_TAG)
            if end_pos_encoded_m3u8_url >= 0:

                # log("end_pos_encoded_m3u8_url", end_pos_encoded_m3u8_url)

                encoded_m3u8_url = html_source[
                    start_pos_encoded_m3u8_url:start_pos_encoded_m3u8_url +
                    end_pos_encoded_m3u8_url]

                # log("encoded_m3u8_url", encoded_m3u8_url)

                decoded_m3u8_url = decodeString(encoded_m3u8_url)

                log("decoded_m3u8_url", decoded_m3u8_url)

                # The decoded m3u8 url should look something like this: https://gamekings.gcdn.co/videos/4457_Xp2EEOmd3SpDPb2S
                # We have to lowercase the part before the last '/' to fix any uppercase digits (i guess my magic decoding isn't perfect ;))
                pos_last_slash = decoded_m3u8_url.rfind("/")
                if pos_last_slash >= 0:
                    first_part = decoded_m3u8_url[0:pos_last_slash]

                    # log("first_part", first_part)

                    second_part = decoded_m3u8_url[pos_last_slash:]

                    # log("second_part", second_part)

                    # Lowercase the first part and add the filename of the m3u8-file
                    decoded_m3u8_url = first_part.lower(
                    ) + second_part + "/" + MASTER_DOT_M3U8

                    log("decoded_m3u8_url completed", decoded_m3u8_url)

                    response = session.get(decoded_m3u8_url)

                    # determine the wanted video max_video_quality
                    if self.PREFERRED_QUALITY == '0':  # Low
                        max_video_quality = VQ360P
                    elif self.PREFERRED_QUALITY == '1':  # Medium
                        max_video_quality = VQ480P
                    elif self.PREFERRED_QUALITY == '2':  # High Quality
                        max_video_quality = VQ720P
                    elif self.PREFERRED_QUALITY == '3':  # Very High Quality
                        max_video_quality = VQ1080P
                    elif self.PREFERRED_QUALITY == '4':  # Ultra High Quality
                        max_video_quality = VQ4K
                    else:  # Default in case max_video_quality is not found
                        max_video_quality = VQ720P

                    # log("wanted max_video_quality", max_video_quality)

                    # an example of the content of a m3u8 file (2019):
                    # #EXTM3U
                    # #EXT-X-STREAM-INF:PROGRAM-ID=1,BANDWIDTH=464000,RESOLUTION=640x360,FRAME-RATE=60.000,CODECS="avc1.4d401f,mp4a.40.2"
                    # index-s360p-v1-a1.m3u8
                    # #EXT-X-STREAM-INF:PROGRAM-ID=1,BANDWIDTH=928000,RESOLUTION=854x480,FRAME-RATE=60.000,CODECS="avc1.4d401f,mp4a.40.2"
                    # index-s480p-v1-a1.m3u8
                    # #EXT-X-STREAM-INF:PROGRAM-ID=1,BANDWIDTH=2128000,RESOLUTION=1280x720,FRAME-RATE=60.000,CODECS="avc1.4d4020,mp4a.40.2"
                    # index-s720p-v1-a1.m3u8
                    # #EXT-X-STREAM-INF:PROGRAM-ID=1,BANDWIDTH=6128000,RESOLUTION=1920x1080,FRAME-RATE=60.000,CODECS="avc1.4d402a,mp4a.40.2"
                    # index-s1080p-v1-a1.m3u8
                    #EXT-X-I-FRAME-STREAM-INF:BANDWIDTH=18304,RESOLUTION=640x360,CODECS="avc1.4d401f",URI="iframes-s360p-v1-a1.m3u8"
                    #EXT-X-I-FRAME-STREAM-INF:BANDWIDTH=36479,RESOLUTION=854x480,CODECS="avc1.4d401f",URI="iframes-s480p-v1-a1.m3u8"
                    #EXT-X-I-FRAME-STREAM-INF:BANDWIDTH=92824,RESOLUTION=1280x720,CODECS="avc1.4d4020",URI="iframes-s720p-v1-a1.m3u8"
                    #EXT-X-I-FRAME-STREAM-INF:BANDWIDTH=240783,RESOLUTION=1920x1080,CODECS="avc1.4d402a",URI="iframes-s1080p-v1-a1.m3u8"

                    # an example of the content of a m3u8 file (2020/11/10):
                    # #EXTM3U
                    # #EXT-X-STREAM-INF:PROGRAM-ID=1,BANDWIDTH=464000,RESOLUTION=640x360,FRAME-RATE=30.000,CODECS="avc1.64001e,mp4a.40.2"
                    # index-svod360n-v1-a1.m3u8
                    # #EXT-X-STREAM-INF:PROGRAM-ID=1,BANDWIDTH=928000,RESOLUTION=854x480,FRAME-RATE=30.000,CODECS="avc1.64001f,mp4a.40.2"
                    # index-svod480n-v1-a1.m3u8
                    # #EXT-X-STREAM-INF:PROGRAM-ID=1,BANDWIDTH=2128000,RESOLUTION=1280x720,FRAME-RATE=30.000,CODECS="avc1.64001f,mp4a.40.2"
                    # index-svod720n-v1-a1.m3u8
                    # #EXT-X-STREAM-INF:PROGRAM-ID=1,BANDWIDTH=6128000,RESOLUTION=1920x1080,FRAME-RATE=30.000,CODECS="avc1.640028,mp4a.40.2"
                    # index-svod1080n-v1-a1.m3u8
                    #EXT-X-I-FRAME-STREAM-INF:BANDWIDTH=65908,RESOLUTION=640x360,CODECS="avc1.64001e",URI="iframes-svod360n-v1-a1.m3u8"
                    #EXT-X-I-FRAME-STREAM-INF:BANDWIDTH=978632,RESOLUTION=854x480,CODECS="avc1.64001f",URI="iframes-svod480n-v1-a1.m3u8"
                    #EXT-X-I-FRAME-STREAM-INF:BANDWIDTH=235616,RESOLUTION=1280x720,CODECS="avc1.64001f",URI="iframes-svod720n-v1-a1.m3u8"
                    #EXT-X-I-FRAME-STREAM-INF:BANDWIDTH=488781,RESOLUTION=1920x1080,CODECS="avc1.640028",URI="iframes-svod1080n-v1-a1.m3u8"

                    # Let's try and find a video of the desired video max_video_quality.
                    # If that can't be found, try to find a video with less than the desired video max_video_quality
                    # 4K doesn't seem to be available as of now (september 2019) but it may be in the future
                    video_quality_url = ''
                    if video_quality_url == '':
                        if max_video_quality in [VQ4K]:
                            video_quality_url = self.find_video_quality_url(
                                VQ4K, response, decoded_m3u8_url)
                    if video_quality_url == '':
                        if max_video_quality in [VQ4K, VQ1080P]:
                            video_quality_url = self.find_video_quality_url(
                                VQ1080P, response, decoded_m3u8_url)
                            if video_quality_url == '':
                                video_quality_url = self.find_video_quality_url(
                                    VQ1080N, response, decoded_m3u8_url)
                    if video_quality_url == '':
                        if max_video_quality in [VQ4K, VQ1080P, VQ720P]:
                            video_quality_url = self.find_video_quality_url(
                                VQ720P, response, decoded_m3u8_url)
                            if video_quality_url == '':
                                video_quality_url = self.find_video_quality_url(
                                    VQ720N, response, decoded_m3u8_url)
                    if video_quality_url == '':
                        if max_video_quality in [
                                VQ4K, VQ1080P, VQ720P, VQ480P
                        ]:
                            video_quality_url = self.find_video_quality_url(
                                VQ480P, response, decoded_m3u8_url)
                            if video_quality_url == '':
                                video_quality_url = self.find_video_quality_url(
                                    VQ480N, response, decoded_m3u8_url)
                    if video_quality_url == '':
                        if max_video_quality in [
                                VQ4K, VQ1080P, VQ720P, VQ480P, VQ360P
                        ]:
                            video_quality_url = self.find_video_quality_url(
                                VQ360P, response, decoded_m3u8_url)
                            if video_quality_url == '':
                                video_quality_url = self.find_video_quality_url(
                                    VQ360N, response, decoded_m3u8_url)

                    # If we didn't find a video url with the desired video max_video_quality or lower, use the m3u8 file url
                    if video_quality_url == '':
                        video_url = decoded_m3u8_url
                    else:

                        log("video_quality_url", video_quality_url)

                        # Find out if the altered m3u8 url exists
                        response = session.get(video_quality_url)

                        # log("response.status_code", response.status_code)

                        # if we find a m3u8 file with the altered url, let's use that.
                        # If it is not found, let's use the unaltered url.
                        if response.status_code in [200]:
                            video_url = video_quality_url
                        else:
                            video_url = decoded_m3u8_url

                    log("decoded video_url", video_url)

                    have_valid_url = True
                    no_url_found = False

        # Maybe it's something like this. Let's try and find the youtube id
        # <div id="videoplayer" data-autoplay="false" data-type="youtube" data-color="0567D8" data-url='https://youtu.be/hmGe65Wf9Hw' data-thumb='https://www.gamekings.tv/wp-content/uploads/robocop-terminator-mortal-kombat-11-1280x720.jpg' style='background-image: url(https://www.gamekings.tv/wp-content/uploads/robocop-terminator-mortal-kombat-11-1280x720.jpg);'>
        if have_valid_url:
            pass
        else:
            start_pos_video_url = html_source.find("https://youtu.be/")
            if start_pos_video_url >= 0:
                end_pos_video_url = html_source.find("'", start_pos_video_url)
                if end_pos_video_url >= 0:
                    youtube_id = html_source[
                        start_pos_video_url:end_pos_video_url]
                    youtube_id = youtube_id.replace("https://youtu.be/", "")
                    youtube_id = youtube_id.strip()

                    log("youtube_id", youtube_id)

                    have_valid_url = True
                    no_url_found = False

        if have_valid_url:
            pass
        # I guess we try another way
        else:
            # Get the video url
            # <div class="content  content--page  content--bglight  content--blue">
            #             <div class="video">
            #             <div id='videoplayer'></div>
            #             <script type="text/javascript">
            #                 jwplayer('videoplayer').setup({
            #                     file: 'https://player.vimeo.com/external/166503498.hd.mp4?s=c44264eced6082c0789371cb5209af96bc44035b',
            #                     image: 'https://www.gamekings.tv/wp-content/uploads/20160513_gk1702_splash.jpg',
            #                     title: 'Gamekings S17E02: De Synergie Aflevering',
            #                     width: '100%',
            #                     aspectratio: '16:9',
            #                     skin: '',
            #                     primary: 'html5',
            #                     autostart: 'true',
            #                     startparam: 'start',
            #                     ...
            no_url_found = False
            have_valid_url = True
            start_pos_video_url = html_source.find(
                "https://player.vimeo.com/external")
            if start_pos_video_url == -1:
                start_pos_video_url = html_source.find(
                    "https://player.vimeo.com/video")
                if start_pos_video_url == -1:
                    start_pos_video_url = html_source.find(
                        "https://www.youtube.com/")
                    if start_pos_video_url >= 0:
                        # Ignore a found "https://www.youtube.com/gamekingsextra"
                        start_pos_youtube_gamekingsextra = html_source.find(
                            "https://www.youtube.com/gamekingsextra")
                        if start_pos_video_url == start_pos_youtube_gamekingsextra:
                            start_pos_video_url = html_source.find(
                                "https://www.youtube.com/",
                                start_pos_youtube_gamekingsextra + 1)
                            if start_pos_video_url == -1:
                                no_url_found = True
                                have_valid_url = False

            # Try to make a valid video url
            if have_valid_url:

                #log("html_source[start_pos_video_url:]", html_source[start_pos_video_url:])

                # Let's only use the video_url part
                html_source_split = str(
                    html_source[start_pos_video_url:]).split()
                video_url = html_source_split[0]

                # Remove the quote on the last position
                if video_url.endswith('"') or video_url.endswith("'"):
                    video_url = video_url[0:len(video_url) - 1]

                log("video_url after split and removing trailing quote",
                    video_url)

                if video_url.find("target=") >= 0:
                    no_url_found = True
                    have_valid_url = False
                    video_url = ""
                elif video_url.find("www.youtube.com/channel/") >= 0:
                    no_url_found = True
                    have_valid_url = False
                    video_url = ""
                elif video_url.find("player.vimeo.com/api/player.js") >= 0:
                    no_url_found = True
                    have_valid_url = False
                    video_url = ""
                elif video_url.find(
                        "www.youtube.com/user/Gamekingsextra") >= 0:
                    no_url_found = True
                    have_valid_url = False
                    video_url = ""

            log("video_url", video_url)

        # Play video
        if have_valid_url:
            # regular gamekings video's on vimeo look like this: https://player.vimeo.com/external/166503498.hd.mp4?s=c44264eced6082c0789371cb5209af96bc44035b
            if video_url.find("player.vimeo.com/external/") > 0:
                # no need to do anything with the vimeo addon, we can use the video_url directly
                pass
            # premium video's on vimeo look like this: https://player.vimeo.com/video/190106340?title=0&autoplay=1&portrait=0&badge=0&color=C7152F
            if video_url.find("player.vimeo.com/video/") > 0:
                # no need to do anything with the vimeo addon, we can use the video_url directly
                pass
            if youtube_id == '':
                if video_url.find("youtube") > 0:
                    youtube_id = str(video_url)
                    youtube_id = youtube_id.replace(
                        "https://www.youtube.com/embed/", "")
                    youtube_id = youtube_id.replace(
                        "https://www.youtube.com/watch?v=", "")
                    youtube_id = youtube_id.replace(
                        "https://www.youtube.com/watch", "")
                    youtube_id = youtube_id.replace("https://www.youtube.com/",
                                                    "")
                    youtube_id = youtube_id[0:youtube_id.find("?")]
                    youtube_id = youtube_id.strip()

                    log("youtube_id2", youtube_id)

                    video_url = 'plugin://plugin.video.youtube/play/?video_id=%s' % youtube_id
            else:
                youtube_id = youtube_id.strip()

                video_url = 'plugin://plugin.video.youtube/play/?video_id=%s' % youtube_id

            log("final video_url", video_url)

            # It was a loooong and twisted walk, but at last we can try and play an actual video file
            list_item = xbmcgui.ListItem(path=video_url)
            xbmcplugin.setResolvedUrl(self.plugin_handle, True, list_item)
        #
        # Check if it's a twitch live stream
        #
        # example of a live stream: video_url = 'plugin://plugin.video.twitch/?channel_id=57330659&amp;mode=play;'
        elif str(html_source).find(TWITCH_URL_GAMEKINGS_TV) > 0:
            xbmcgui.Dialog().ok(LANGUAGE(30000), LANGUAGE(30611))
        #
        # Alert user
        #
        elif no_url_found:
            xbmcgui.Dialog().ok(LANGUAGE(30000), LANGUAGE(30505))
Example #45
0
def PLAYVIDEO(url, name):
    progress.create('Play video', 'Searching videofile.')
    progress.update( 10, "", "Loading video page", "" )
    hosts = []
    videosource = getHtml(url, url)
    if re.search('videomega', videosource, re.DOTALL | re.IGNORECASE):
        hosts.append('VideoMega')
    if re.search('openload', videosource, re.DOTALL | re.IGNORECASE):
        hosts.append('OpenLoad')
    if re.search('www.flashx.tv', videosource, re.DOTALL | re.IGNORECASE):
        hosts.append('FlashX')        
    if len(hosts) == 0:
        progress.close()
        dialog.ok('Oh oh','Couldn\'t find any video')
        return
    elif len(hosts) > 1:
        if addon.getSetting("dontask") == "true":
            vidhost = hosts[0]            
        else:
            vh = dialog.select('Videohost:', hosts)
            vidhost = hosts[vh]
    else:
        vidhost = hosts[0]
    
    if vidhost == 'VideoMega':
        progress.update( 40, "", "Loading videomegatv", "" )
        if re.search("videomega.tv/iframe.js", videosource, re.DOTALL | re.IGNORECASE):
            hashref = re.compile("""javascript["']>ref=['"]([^'"]+)""", re.DOTALL | re.IGNORECASE).findall(videosource)
        elif re.search("videomega.tv/iframe.php", videosource, re.DOTALL | re.IGNORECASE):
            hashref = re.compile(r"iframe\.php\?ref=([^&]+)&", re.DOTALL | re.IGNORECASE).findall(videosource)
        else:
            hashkey = re.compile("""hashkey=([^"']+)""", re.DOTALL | re.IGNORECASE).findall(videosource)
            hashpage = getHtml('http://videomega.tv/validatehash.php?hashkey='+hashkey[0], url)
            hashref = re.compile('ref="([^"]+)', re.DOTALL | re.IGNORECASE).findall(hashpage)
        progress.update( 80, "", "Getting video file", "" )
        videopage = getHtml('http://videomega.tv/view.php?ref='+hashref[0], url)
        videourl = re.compile('<source src="([^"]+)"', re.DOTALL | re.IGNORECASE).findall(videopage)
        videourl = videourl[0]
    elif vidhost == 'OpenLoad':
        progress.update( 40, "", "Loading Openload", "" )
        openloadurl = re.compile('<iframe src="([^"]+)"', re.DOTALL | re.IGNORECASE).findall(videosource)
        openloadsrc = getHtml(openloadurl[0], url)
        videourl = re.compile('<source src="([^"]+)"', re.DOTALL | re.IGNORECASE).findall(openloadsrc)
        progress.update( 80, "", "Getting video file", "" )
        openload302 = getVideoLink(videourl[0],openloadurl[0])
        realurl = openload302.replace('https://','http://')
        videourl = realurl + "|" + openloadurl[0]
    elif vidhost == 'FlashX':
        progress.update( 40, "", "Loading FlashX", "" )
        flashxurl = re.compile('<iframe src="([^"]+)"', re.DOTALL | re.IGNORECASE).findall(videosource)
        flashxsrc = getHtml2(flashxurl[0])
        flashxjs = re.compile("<script type='text/javascript'>([^<]+)</sc", re.DOTALL | re.IGNORECASE).findall(flashxsrc)
        progress.update( 80, "", "Getting video file", "" )
        flashxujs = beautify(flashxjs[0])
        videourl = re.compile(r',.*file: "([^"]+)".*\}\],', re.DOTALL | re.IGNORECASE).findall(flashxujs)
        videourl = videourl[0]
    progress.close()
    iconimage = xbmc.getInfoImage("ListItem.Thumb")
    listitem = xbmcgui.ListItem(name, iconImage="DefaultVideo.png", thumbnailImage=iconimage)
    listitem.setInfo('video', {'Title': name, 'Genre': 'P**n'})
    xbmc.Player().play(videourl, listitem)
def Playvid(performerID, name):
    response = utils.getHtml(
        "https://streamate.com/ajax/config/?name=" + name +
        "&sakey=&sk=streamate.com&userid=0&version=2.2.0&ajax=1")
    data = json.loads(response)

    host = data['liveservices'][
        'host'] + "/socket.io/?puserid=" + performerID + "&EIO=3&transport=websocket"  #24824942
    ws = websocket.WebSocket()
    ws = websocket.create_connection(host)

    ws.send('40/live')

    quitting = 0
    while quitting == 0:
        message = ws.recv()
        match = re.compile('performer offline',
                           re.DOTALL | re.IGNORECASE).findall(message)
        if match:
            quitting = 1
            ws.close()
            utils.notify('Model is offline')
            return None

        match = re.compile('isPaid":true',
                           re.DOTALL | re.IGNORECASE).findall(message)
        if match:
            quitting = 1
            ws.close()
            utils.notify('Model not in freechat')
            return None

        match = re.compile('roomInfoUpdate',
                           re.DOTALL | re.IGNORECASE).findall(message)
        if match:
            ws.send(
                '42/live,["GetVideoPath",{"nginx":1,"protocol":2,"attempt":1}]'
            )
            while quitting == 0:
                message = ws.recv()
                match = re.compile('(http[^"]+m3u8)',
                                   re.DOTALL | re.IGNORECASE).findall(message)
                if match:
                    videourl = match[0]
                    quitting = 1
                    ws.close()

    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:
        #iconimage = xbmc.getInfoImage("ListItem.Thumb")
        #listitem = xbmcgui.ListItem(name, iconImage="DefaultVideo.png", thumbnailImage=iconimage)
        #listitem.setInfo('video', {'Title': name, 'Genre': 'P**n'})
        xbmc.Player().play(videourl, listitem)
Example #47
0
def Playvid(url, name):
    playmode = int(addon.getSetting('chatplay'))
    chatslow = int(addon.getSetting('chatslow'))
    listhtml = utils.getHtml(url, hdr=cbheaders)
    iconimage = xbmc.getInfoImage("ListItem.Thumb")

    m3u8url = re.compile(r"loadHlsVideo\('([^']+)",
                         re.DOTALL | re.IGNORECASE).findall(listhtml)
    if m3u8url:
        m3u8stream = m3u8url[0]
        if chatslow == 1:
            m3u8stream = m3u8stream.replace('_fast', '')
    else:
        m3u8stream = False

    if playmode == 0:
        if m3u8stream:
            videourl = m3u8stream
        else:
            utils.notify('Oh oh', 'Couldn\'t find a playable webcam link')
            return

    elif playmode == 1:
        if m3u8stream:
            from F4mProxy import f4mProxyHelper
            f4mp = f4mProxyHelper()
            f4mp.playF4mLink(m3u8stream,
                             name,
                             proxy=None,
                             use_proxy_for_chunks=False,
                             maxbitrate=0,
                             simpleDownloader=False,
                             auth=None,
                             streamtype='HLS',
                             setResolved=False,
                             swf=None,
                             callbackpath="",
                             callbackparam="",
                             iconImage=iconimage)
            return
        else:
            utils.notify('Oh oh', 'Couldn\'t find a playable webcam link')
            return

    elif playmode == 2:
        flv_info = []
        embed = re.compile(r"EmbedViewerSwf\(*(.+?)\);",
                           re.DOTALL).findall(listhtml)[0]
        for line in embed.split("\n"):
            data = re.search("""\s+["']([^"']+)["'],""", line)
            if data:
                flv_info.append(data.group(1))

        streamserver = "rtmp://%s/live-edge" % (flv_info[2])
        modelname = flv_info[1]
        username = flv_info[8]
        password = urllib.unquote(flv_info[12])
        unknown = flv_info[13]
        swfurl = "https://chaturbate.com/static/flash/CBV_2p650.swf"

        videourl = "%s app=live-edge swfUrl=%s tcUrl=%s pageUrl=http://chaturbate.com/%s/ conn=S:%s conn=S:%s conn=S:2.650 conn=S:%s conn=S:%s playpath=mp4" % (
            streamserver, swfurl, streamserver, modelname, username, modelname,
            password, unknown)

    listitem = xbmcgui.ListItem(name,
                                iconImage="DefaultVideo.png",
                                thumbnailImage=iconimage)
    listitem.setInfo('video', {'Title': name, 'Genre': 'P**n'})
    listitem.setProperty("IsPlayable", "true")
    xbmc.Player().play(videourl, listitem)
Example #48
0
"""
    Player module: plays the selected video
"""

# TODO: remove this when dialog issue is resolved
import xbmc
# set our title
g_title = unicode(xbmc.getInfoLabel("ListItem.Title"), "utf-8")
# set our studio (only works if the user is using the video library)
g_studio = unicode(xbmc.getInfoLabel("ListItem.Studio"), "utf-8")
# set our genre (only works if the user is using the video library)
g_genre = unicode(xbmc.getInfoLabel("ListItem.Genre"), "utf-8")
# set our rating (only works if the user is using the video library)
g_mpaa_rating = unicode(xbmc.getInfoLabel("ListItem.MPAA"), "utf-8")
# set our thumbnail
g_thumbnail = xbmc.getInfoImage("ListItem.Thumb")
# set our plotoutline
g_plotoutline = unicode(xbmc.getInfoLabel("ListItem.Plot"), "utf-8")

# create the progress dialog (we do it here so there is minimal delay with nothing displayed)
import xbmcgui

pDialog = xbmcgui.DialogProgress()
pDialog.create("AOL Videos Plugin", "Downloading video...")

# main imports
import sys
import os

import xbmcplugin
Example #49
0
def PlayStream(sourceSoup, urlSoup, name, url):
	try:
		#url = urlSoup.url.text
		title=''
		link=''
		sc=''
		try:
			title=urlSoup.item.title.text
			
			link=urlSoup.item.link.text
			sc=sourceSoup.sname.text
		except: pass
		if link=='':
			timeD = 2000  #in miliseconds
			line1="couldn't read title and link"
			xbmc.executebuiltin('Notification(%s, %s, %d, %s)'%(__addonname__,line1, timeD, __icon__))
			return False
		regexs = urlSoup.find('regex')
		if (not regexs==None) and len(regexs)>0:
			liveLink=	getRegexParsed(urlSoup,link)
		else:
			liveLink=	link
		if len(liveLink)==0:
			timeD = 2000  #in miliseconds
			line1="couldn't read title and link"
			xbmc.executebuiltin('Notification(%s, %s, %d, %s)'%(__addonname__,line1, timeD, __icon__))
			return False
			
		timeD = 2000  #in miliseconds
		line1="Resource found,playing now."
		xbmc.executebuiltin('Notification(%s, %s, %d, %s)'%(__addonname__,line1, timeD, __icon__))

		name+='-'+sc+':'+title
		print 'liveLink',liveLink
		listitem = xbmcgui.ListItem( label = str(name), iconImage = "DefaultVideo.png", thumbnailImage = xbmc.getInfoImage( "ListItem.Thumb" ), path=liveLink )
		player = CustomPlayer.MyXBMCPlayer()
		start = time.time() 
		#xbmc.Player().play( liveLink,listitem)
		player.play( liveLink,listitem)
		while player.is_active:
			xbmc.sleep(200)
		#return player.urlplayed
		done = time.time()
		elapsed = done - start
		if player.urlplayed and elapsed>=3:
			return True
		else:
			return False  
	except:
		traceback.print_exc(file=sys.stdout)    
	return False  
    def playVideo(self):
        #
        # Init
        #
        is_folder = False
        # Create a list for our items.
        listing = []
        unplayable_media_file = False
        have_valid_url = False
        dialogWait = xbmcgui.DialogProgress()

        #
        # Get current list item details...
        #
        # title = xbmc.getInfoLabel("listitem.Title")
        thumbnail_url = xbmc.getInfoImage("list_item.Thumb")
        # studio = xbmc.getInfoLabel("list_item.Studio")
        plot = xbmc.getInfoLabel("list_item.Plot")
        genre = xbmc.getInfoLabel("list_item.Genre")

        #
        # Get HTML page
        #
        response = requests.get(self.video_page_url, headers=HEADERS)

        html_source = response.text
        html_source = convertToUnicodeString(html_source)

        #log ("html_source1", html_source)

        begin_pos_video_file = str(html_source).find(
            "http://www.worldstarhiphop.com/embed/")
        end_pos_video_file = str(html_source).find('&quot;',
                                                   begin_pos_video_file)
        video_url = html_source[begin_pos_video_file:end_pos_video_file]

        log("video_url1", video_url)

        try:
            #
            # Get HTML page
            #
            response = requests.get(video_url, headers=HEADERS)

            html_source = response.text
            html_source = convertToUnicodeString(html_source)

            #log ("html_source2", html_source)

            # It should contain something like this:
            # <source src="http://hw-videos.worldstarhiphop.com/u/vid/2015/03/15/Sequencealeganfgilswetseassisndede1.flv" type="video/mp4">
            pos_vid_url = str(html_source).find(
                "hw-videos.worldstarhiphop.com/")
            if pos_vid_url >= 0:
                pos_start_quote = str(html_source).rfind('"', 0, pos_vid_url)
                pos_end_quote = str(html_source).find('"', pos_start_quote + 1)
                video_url = html_source[pos_start_quote + 1:pos_end_quote]
                have_valid_url = True
            else:
                unplayable_media_file = True
        except:
            unplayable_media_file = True

        log("have_valid_url", have_valid_url)

        log("video_url2", video_url)

        if have_valid_url:
            list_item = xbmcgui.ListItem(path=video_url)
            xbmcplugin.setResolvedUrl(self.plugin_handle, True, list_item)
        #
        # Alert user
        #
        elif unplayable_media_file:
            xbmcgui.Dialog().ok(LANGUAGE(30000), LANGUAGE(30506))
Example #51
0
def PlayOtherUrl ( url ):
    progress = xbmcgui.DialogProgress()
    progress.create('Progress', 'Fetching Streaming Info')
    progress.update( 10, "", "Finding links..", "" )

    if url=='http://live.aryzindagi.tv/':
        req = urllib2.Request(url)
        #req.add_header('User-Agent', 'Verismo-BlackUI_(2.4.7.5.8.0.34)')   
        #req.add_header('User-Agent', 'Mozilla/5.0(iPad; U; CPU iPhone OS 3_2 like Mac OS X; en-us) AppleWebKit/531.21.10 (KHTML, like Gecko) Version/4.0.4 Mobile/7B314 Safari/531.21.10')
        req.add_header('User-Agent', 'Verismo-BlackUI_(2.4.7.5.8.0.34)') 
        response = urllib2.urlopen(req)
        link=response.read()
        curlpatth='file: "(htt.*?)"'
        progress.update( 50, "", "Preparing url..", "" )
        dag_url =re.findall(curlpatth,link)[0]
    elif url=='etv':
        req = urllib2.Request('http://m.news18.com/live-tv/etv-urdu')
        #req.add_header('User-Agent', 'Verismo-BlackUI_(2.4.7.5.8.0.34)')   
        req.add_header('User-Agent', 'Mozilla/5.0(iPad; U; CPU iPhone OS 3_2 like Mac OS X; en-us) AppleWebKit/531.21.10 (KHTML, like Gecko) Version/4.0.4 Mobile/7B314 Safari/531.21.10')
        #req.add_header('User-Agent', 'Verismo-BlackUI_(2.4.7.5.8.0.34)') 
        response = urllib2.urlopen(req)
        link=response.read()
        curlpatth='<source src="(.*?)"'
        progress.update( 50, "", "Preparing url..", "" )
        dag_url =re.findall(curlpatth,link)[0]
    elif 'dag1.asx' not in url and 'stagefright' not in url:
        req = urllib2.Request(url)
        #req.add_header('User-Agent', 'Verismo-BlackUI_(2.4.7.5.8.0.34)')   
        #req.add_header('User-Agent', 'Mozilla/5.0(iPad; U; CPU iPhone OS 3_2 like Mac OS X; en-us) AppleWebKit/531.21.10 (KHTML, like Gecko) Version/4.0.4 Mobile/7B314 Safari/531.21.10')
        response = urllib2.urlopen(req)
        link=response.read()
        curlpatth='<link>(.*?)<\/link>'
        progress.update( 50, "", "Preparing url..", "" )
        dag_url =re.findall(curlpatth,link)
        if not (dag_url and len(dag_url)>0 ):
            curlpatth='\<ENTRY\>\<REF HREF="(.*?)"'
            dag_url =re.findall(curlpatth,link)[0]
        else:
            dag_url=dag_url[0]
    else:
        dag_url=url
    print 'dag_url',dag_url,name
    if 'Dunya news' in name and 'dag1.asx' not in dag_url:
        print 'aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa'
        dag_url='http://dag-chi.totalstream.net/dag1.asx?id=ad1!dunya'

    if 'dag1.asx' in dag_url:    
        

        req = urllib2.Request(dag_url)
        req.add_header('User-Agent', 'Verismo-BlackUI_(2.4.7.5.8.0.34)')   
        response = urllib2.urlopen(req)
        link=response.read()
        dat_pattern='href="([^"]+)"[^"]+$'
        dag_url =re.findall(dat_pattern,link)[0]
    print 'dag_url2',dag_url
    final_url=get_dag_url(dag_url)
    progress.update( 100, "", "Almost done..", "" )
    print final_url
    listitem = xbmcgui.ListItem( label = str(name), iconImage = "DefaultVideo.png", thumbnailImage = xbmc.getInfoImage( "ListItem.Thumb" ) )
    print "playing stream name: " + str(name) 
    xbmc.Player( xbmc.PLAYER_CORE_AUTO ).play( final_url, listitem)    
Example #52
0
def PlayShowLink(url):
    #	url = tabURL.replace('%s',channelName);
    print "URL: %s" % url
    #regstring='http:\/\/(.*?)\/admin'
    #match=re.findall(regstring, url)

    url2 = 'http://serialzone.in/admin/AjaxProcess.php?cfile=load_video&id=%s&param=value&_=%s' % (
        url, time.time())
    print url2
    req = urllib2.Request(url2)
    req.add_header(
        'User-Agent',
        'Mozilla/5.0(iPad; U; CPU iPhone OS 3_2 like Mac OS X; en-us) AppleWebKit/531.21.10 (KHTML, like Gecko) Version/4.0.4 Mobile/7B314 Safari/531.21.10'
    )
    response = urllib2.urlopen(req)
    link = response.read()
    response.close()

    #        print "LINK READ: ", link
    match = re.findall('embed\/(.*?)\?', link)
    #        print "MATCH: ",match,"\t\tMATCH LEN: ",len(match)

    if len(match) == 0:
        #		print 'not found trying again'
        match = re.findall('yp\(\'(.*?)\'', link)
    #	print "LINK: ",link
    #        print "MATCH: ",match
    if len(match) == 0:
        #		print 'not found trying again'
        match = re.findall('\(\'(.*?)\'', link)
        if match[0].startswith('http'):
            urltofetch = match[0]
            req = urllib2.Request(urltofetch)
            req.add_header(
                'User-Agent',
                'Mozilla/5.0(iPad; U; CPU iPhone OS 3_2 like Mac OS X; en-us) AppleWebKit/531.21.10 (KHTML, like Gecko) Version/4.0.4 Mobile/7B314 Safari/531.21.10'
            )
            response = urllib2.urlopen(req)
            link = response.read()
            response.close()
            match = re.findall("\'(http.*?master.m3u8?.*?)\'", link)
            if len(match) == 0 and 'ozee.com' in urltofetch.lower():
                import jscrypto
                print 'dd', link
                linkdatareg = '(var hlsplayurl.*?\}\')'
                lindata = re.findall(linkdatareg, link)[0]
                print lindata
                ct = re.findall('"ct":"(.*?)"', lindata)[0]
                salt = re.findall('"s":"(.*?)"', lindata)[0]
                passphrase = re.findall('dailytoday.?=.?\"(.*?)\"',
                                        link.split('var hlsplayurl')[0])[-1]
                salt = salt.decode("hex")
                url = jscrypto.decode(ct, passphrase, salt)
                uurl = url.replace("\\/", "/").replace('"', '')
                cookieJar = cookielib.LWPCookieJar()
                getUrl(
                    uurl,
                    cookieJar=cookieJar,
                    headers=
                    [('User-Agent',
                      'Mozilla/5.0(iPad; U; CPU iPhone OS 3_2 like Mac OS X; en-us) AppleWebKit/531.21.10 (KHTML, like Gecko) Version/4.0.4 Mobile/7B314 Safari/531.21.10'
                      )])

                uurl = uurl + '|User-Agent=%s&Cookie=%s' % (
                    'Mozilla/5.0(iPad; U; CPU iPhone OS 3_2 like Mac OS X; en-us) AppleWebKit/531.21.10 (KHTML, like Gecko) Version/4.0.4 Mobile/7B314 Safari/531.21.10',
                    getCookiesString(cookieJar))
                print uurl
                listitem = xbmcgui.ListItem(
                    label=str(name),
                    iconImage="DefaultVideo.png",
                    thumbnailImage=xbmc.getInfoImage("ListItem.Thumb"))
                print "playing stream name: " + str(name)
                xbmc.Player().play(uurl, listitem)
            else:
                xbmc.executebuiltin("xbmc.PlayMedia(" + match[0] + ")")
            return

    time1 = 2000
    line1 = "Playing Youtube Link"
    xbmc.executebuiltin('Notification(%s, %s, %d, %s)' %
                        (__addonname__, line1, time1, __icon__))

    youtubecode = match[0]

    progress = xbmcgui.DialogProgress()
    progress.create('Progress', 'Checking if Proxy Required?')
    progress.update(20, "", "Getting Urls..")

    liveUrl = 'https://m.youtube.com/watch?v=%s' % youtubecode
    stringFailed = 'The uploader has not made this video available in your country'
    req = urllib2.Request(liveUrl)
    req.add_header(
        'User-Agent',
        'Mozilla/5.0 (iPad; CPU OS 5_0 like Mac OS X) AppleWebKit/534.46 (KHTML, like Gecko) Version/5.1 Mobile/9A334 Safari/7534.48.3'
    )
    response = urllib2.urlopen(req)
    link = response.read()
    response.close()
    if stringFailed in link and 'googlevideo' not in link:
        try:
            proxyserver = selfAddon.getSetting('ProxyServer')  #:8080
            proxyport = str(selfAddon.getSetting('ProxyPort'))
            try:
                vquality = int(selfAddon.getSetting('youtubevideo'))
                print vquality
                vquality = "hd720|medium|small".split('|')[vquality]
            except:
                vquality = "medium"
            print proxyserver, proxyport, vquality
            progress.update(
                60, "", "Yes proxy required, using %s:%s" %
                (proxyserver, str(proxyport)))
            ##use US proxy and play with it

            cookieJar = cookielib.LWPCookieJar()
            cookie_handler = urllib2.HTTPCookieProcessor(cookieJar)
            opener = urllib2.build_opener(
                cookie_handler, urllib2.HTTPBasicAuthHandler(),
                urllib2.HTTPHandler(),
                urllib2.ProxyHandler(
                    {'https': '%s:%s' % (proxyserver, proxyport)}))
            req = urllib2.Request(liveUrl)
            req.add_header(
                'User-Agent',
                'Mozilla/5.0 (iPad; CPU OS 5_0 like Mac OS X) AppleWebKit/534.46 (KHTML, like Gecko) Version/5.1 Mobile/9A334 Safari/7534.48.3'
            )
            response = opener.open(req, timeout=20)
            link = response.read()
            response.close()
            print link
            progress.update(90, "", "Got the Link, Now playing via proxy")
            pat2 = '\\\\?u0026quality=(.*?)\\\\.*?url=(http.*?videoplayback.*?),'
            pat = 'url_encoded_fmt_stream_map\\\\"\\: (.*?), '
            final_url = re.findall(pat, link)
            if len(final_url) == 0:
                return
                #final_url=re.findall(pat2,link)
            final_url = final_url[0].split(',')
            print final_url
            print 'final_url', final_url
            qarray = []
            for sss in final_url:
                url = urllib.unquote(sss.split('url=')[1].split('\\')[0])
                qlt = sss.split('quality=')[1].split(',')[0].split('\\')[0]
                qarray.append([url, qlt])
            urltoplay = None
            if len(qarray) == 0:
                progress.update(
                    99, "", "FAILED, proxy issues or link resolution problem")
                time1 = 2000
                line1 = "GeoBocked:Proxy issues or link resolution problem"
                xbmc.executebuiltin('Notification(%s, %s, %d, %s)' %
                                    (__addonname__, line1, time1, __icon__))
                return
            print 'qarray', qarray
            if len(qarray) > 1:
                for uu in qarray:
                    if uu[1] == vquality and ',' not in uu[0]:
                        urltoplay = uu[0]
                        print 'quality selected', uu
            if not urltoplay:
                print 'default quality selected', final_url[0]
                urltoplay = final_url[0][0]

            urltoplay = urllib.unquote(urltoplay)
            print 'urltoplay', urltoplay
            playmediawithproxy(urltoplay, name, '', proxyserver, proxyport,
                               progress)
        except:
            traceback.print_exc(file=sys.stdout)
        return ''

    uurl = 'plugin://plugin.video.youtube/play/?video_id=%s' % youtubecode
    #uurl = 'plugin://plugin.video.youtube/v/%s' % youtubecode
    #	print uurl
    xbmc.executebuiltin("xbmc.PlayMedia(" + uurl + ")")

    return
Example #53
0
 def get_cached_profile_thumb(self):
     return xbmc.translatePath(xbmc.getInfoImage("System.ProfileThumb"))
    "title":       unicode( xbmc.getInfoLabel( "ListItem.Title" ),       "utf-8" ),
    "genre":       unicode( xbmc.getInfoLabel( "ListItem.Genre" ),       "utf-8" ),
    "plot":        unicode( xbmc.getInfoLabel( "ListItem.Plot" ),        "utf-8" ),
    "Aired":       unicode( xbmc.getInfoLabel( "ListItem.Premiered" ),   "utf-8" ),
    "mpaa":        unicode( xbmc.getInfoLabel( "ListItem.MPAA" ),        "utf-8" ),
    "duration":    unicode( xbmc.getInfoLabel( "ListItem.DUration" ),    "utf-8" ),
    "studio":      unicode( xbmc.getInfoLabel( "ListItem.Studio" ),      "utf-8" ),
    "cast":        [unicode( xbmc.getInfoLabel( "ListItem.Cast" ),        "utf-8" )],
    "writer":      unicode( xbmc.getInfoLabel( "ListItem.Writer" ),      "utf-8" ),
    "director":    unicode( xbmc.getInfoLabel( "ListItem.Director" ),    "utf-8" ),
    "season":      int(     xbmc.getInfoLabel( "ListItem.Season" )    or "-1"    ),
    "episode":     int(     xbmc.getInfoLabel( "ListItem.Episode" )   or "1"     ),
    "year":        int(     xbmc.getInfoLabel( "ListItem.Year" )      or "0"     ),
    }
# set our thumbnail
g_thumbnail = unicode( xbmc.getInfoImage( "ListItem.Thumb" ), "utf-8" )

savedTime = 0
totalTime = 0
key = 0
url = ""
listitem = None
dataEmission = None

#def playVideo( PID, startoffset=None, strwatched=None, listitem=None ):
#    #global g_strwatched
#    #if not g_strwatched and strwatched is not None:
#    #    g_strwatched = strwatched
#
#    # set our play path
#    rtmp_url = getVideo( PID )
Example #55
0
 def __init__(self, nfo_path=None):
     info_labels = {
         'size':
         unicode(xbmc.getInfoLabel("ListItem.Size"), 'utf-8'),
         'tvshowtitle':
         unicode(xbmc.getInfoLabel("ListItem.TvShowTitle"), 'utf-8'),
         'title':
         unicode(xbmc.getInfoLabel("ListItem.Title"), 'utf-8'),
         'genre':
         unicode(xbmc.getInfoLabel("ListItem.Genre"), 'utf-8'),
         'plot':
         unicode(xbmc.getInfoLabel("ListItem.Plot"), 'utf-8'),
         'aired':
         unicode(xbmc.getInfoLabel("ListItem.Premiered"), 'utf-8'),
         'mpaa':
         unicode(xbmc.getInfoLabel("ListItem.MPAA"), 'utf-8'),
         'duration':
         unicode(xbmc.getInfoLabel("ListItem.DUration"), 'utf-8'),
         'studio':
         unicode(xbmc.getInfoLabel("ListItem.Studio"), 'utf-8'),
         'cast':
         unicode(xbmc.getInfoLabel("ListItem.Cast"), 'utf-8'),
         'writer':
         unicode(xbmc.getInfoLabel("ListItem.Writer"), 'utf-8'),
         'director':
         unicode(xbmc.getInfoLabel("ListItem.Director"), 'utf-8'),
         'season':
         int(xbmc.getInfoLabel("ListItem.Season") or "-1"),
         'episode':
         int(xbmc.getInfoLabel("ListItem.Episode") or "-1"),
         'year':
         int(xbmc.getInfoLabel("ListItem.Year") or "-1"),
     }
     # Clear empty keys
     for key in info_labels.keys():
         if (info_labels[key] == -1):
             del info_labels[key]
         try:
             if (len(info_labels[key]) < 1):
                 del info_labels[key]
         except:
             pass
     try:
         info_labels['size'] = self._size_to_bytes(info_labels['size'])
     except:
         pass
     try:
         code = self._code_from_plot(info_labels['plot'])
         if code:
             info_labels['code'] = code
     except:
         pass
     try:
         info_labels['cast'] = info_labels['cast'].split('\n')
     except:
         pass
     if not 'title' in info_labels:
         if nfo_path:
             info_labels['title'] = os.path.basename(nfo_path)
         else:
             info_labels['title'] = 'Unknown'
     self.info_labels = info_labels
     self.fanart = unicode(
         xbmc.getInfoImage("Listitem.Property(Fanart_Image)"), 'utf-8')
     self.thumbnail = unicode(xbmc.getInfoImage("ListItem.Thumb"), 'utf-8')
     self.nfo_path = nfo_path
Example #56
0
def GetRTMP(streamType, url):

    html = getURL(url)
    rtmp = ""

    # Zonein stream
    if streamType == ZoneinStreamType:
        url = re.compile('src="(.+?)"').findall(html)[0]

        html = getURL(url)
        swfLink = re.compile('<param name="movie" value="(.+?)"/>').findall(
            html)[0]
        channelID = re.compile(
            '<param name="FlashVars" VALUE=".+?&cid=(.+?)&.+?">').findall(
                html)[0]
        rtmp = ZoneRTMP + channelID + "?doPlay=a/ playpath=" + ZonePlayPath + " swfurl=" + swfLink + " swfvfy=true"

    # Seeon.tv stream
    elif streamType == SeeonStreamType:
        url = re.compile("src='(.+?)'").findall(html)[0]

        html = getURL(url)
        rtmp = SeeonRTMP.strip('\n').replace("#", str(random.randint(1, 9)))
        swfLink = re.compile('<param name="movie" value="(.+?)">').findall(
            html)[0]
        channelID = re.compile(
            '<param name="flashvars" .+?&file=(.+?).flv.+?>').findall(html)[0]
        rtmp = rtmp + " playpath=" + channelID + " swfurl=" + swfLink + " pageurl=" + url + " swfvfy=true"

    # Jimey.tv stream
    elif streamType == JimeyStreamType:
        channelID = re.compile(
            "<param name='flashvars' value='(.+?)&").findall(html)[0]
        rtmp = JimeyRTMP + " playpath=" + channelID + " swfurl=" + JimeySWF + " pageurl=" + url + " swfvfy=true"

    # Wii-Cast stream
    elif streamType == WiiCastStreamType:
        url = re.compile("<iframe src='(.+?)'").findall(html)[0]

        html = getURL(url)
        print html
        rtmpurl = WiiCastRTMP
        swf = re.compile("so.addVariable('plugins','(.+?)')").findall(html)[0]
        playpath = re.compile("so.addVariable('file', '(.+?)');").findall(
            html)[0]
        rtmp = rtmpurl + " playpath=" + playpath + " swfurl=" + swf + " pageurl=" + url + " swfvfy=true"

    # Ustream.tv stream
    elif streamType == Ustream:
        channelID = re.compile('ustream.vars.channelId=(.+?);').findall(
            html)[0]
        if len(channelID) == 0:
            dialog = xbmcgui.Dialog()
            ok = dialog.ok('USTREAM.tv', 'Error: Not a live feed.')
            return
        url = UstreamAMF.strip('\n').replace("#", str(channelID))

        html = getURL(url)

        playPath = re.compile('streamName\W\W\W(.+?)\x00',
                              re.DOTALL).findall(html)[0]
        tcUrl = re.compile('cdnUrl\W\W\S(.+?)\x00', re.DOTALL).findall(html)[0]
        tcUrl2 = re.compile('fmsUrl\W\W\S(.+?)\x00',
                            re.DOTALL).findall(html)[0]
        print tcUrl
        print tcUrl2
        print playPath

        if len(tcUrl) == 0:
            if len(tcUrl2) == 0:
                dialog = xbmcgui.Dialog()
                ok = dialog.ok('USTREAM.tv', 'Error: Not a live feed.')
                return
            else:
                new = tcUrl2.replace('/ustreamVideo', ':1935/ustreamVideo')
                rtmp_url = new + '/'
                #dialog = xbmcgui.Dialog()
                #ok = dialog.ok('Debug', rtmp_url+'\nplayPath: '+playPath)
        else:
            rtmp_url = tcUrl
            #dialog = xbmcgui.Dialog()
            #ok = dialog.ok('Debug', rtmp_url+'\n'+playPath)

        thumb = xbmc.getInfoImage("ListItem.Thumb")
        rtmp = tcUrl + " playpath=" + playPath + " swfurl=" + UstreamSWF + " swfvfy=true"

        #cid=re.compile('<param name="flashvars" value=".+?&amp;channelid=(.+?).+?/>').findall(html)[0]
        #playPath = UstreamPlayPath.strip('\n').replace("#",str(cid))
        #rtmp=UstreamRTMP + " playpath=" + playPath + " swfurl=" + UstreamSWF + " swfvfy=true"

    return rtmp
Example #57
0
def PlayStream(sourceEtree, urlSoup, name, url):
    try:
        channelId = urlSoup.url.text
        pDialog = xbmcgui.DialogProgress()
        pDialog.create('XBMC', 'Communicating with Teledunet')
        pDialog.update(10, 'fetching channel page')
        loginName = selfAddon.getSetting("teledunetTvLogin")

        howMaytimes = 2
        totalTried = 0
        doDummy = False
        while totalTried < howMaytimes:
            totalTried += 1
            if 1 == 1:
                newURL = 'http://www.teledunet.com/mobile/'
                print 'newURL', newURL
                token = ''
                try:
                    link = None
                    result = getChannelHTML(channelId)
                    #cache2Hr.cacheFunction(getChannelHTML)

                    if result:
                        link = result['link']
                        token = result['token']
                        mainpage = result['mainpage']

                        print 'file_exists', len(link)
                    else:
                        print 'cache or the url failed!!'
                    rtmp = re.findall(('rtmp://(.*?)/%s\'' % channelId), link)
                    if len(rtmp) == 0:
                        print 'creating it manually'
                        rtmp = 'rtmp://127.0.0.1:1935/live/%s' % channelId
                    else:
                        rtmp = rtmp[0]
                    print 'rtmp1', rtmp
                    rtmp = 'rtmp://%s/%s' % (rtmp, channelId)
                    print 'rtmp2', rtmp
                    if '127.0.0.1' in rtmp:
                        server_pat = 'Array\((.*?)\);'
                        servers_array = re.findall(
                            server_pat, link)[0].replace('\'', '') + ','
                        print servers_array
                        server_pat = "(rtmp:.*?),"
                        servers_array = re.findall(server_pat, servers_array)
                        rtmp = servers_array[0]
                except:
                    clearFileCache()
                    traceback.print_exc(file=sys.stdout)
                    print 'trying backup'
                    try:
                        link = getUrl("http://pastebin.com/raw.php?i=z66yHXcG",
                                      getCookieJar())
                        rtmp = re.findall(('rtmp://(.*?)/%s\'' % channelId),
                                          link)[0]
                        rtmp = 'rtmp://%s/%s' % (rtmp, channelId)
                    except:
                        traceback.print_exc(file=sys.stdout)
                        rtmp = 'rtmp://5.196.84.28:1935/live/%s' % (channelId)
                        print 'error in channel using hardcoded value'
            pDialog.update(80, 'trying to play')
            liveLink = sourceEtree.findtext('rtmpstring')
            freeCH = '2m'
            ip_patt = "ip='(.*?)';"
            dz_patt = "dz='(.*?)';"
            today = datetime.datetime.now()
            v1 = 234 * (366 -
                        (today - datetime.datetime(today.year, 1, 1)).days + 0)
            v2 = 222
            #something wrong in calc, may be timezone?
            dz = re.findall(dz_patt, link)[0]
            ip = re.findall(ip_patt, link)[0]
            ip2 = ''.join(ip.split('.')[0:4])
            print 'dz', dz
            access_id = str(((365 - int(dz)) * long(ip2) * v1) + v2)
            access_id = '?id1=' + access_id
            access_iddummy = '?id1=1'

            liveLinkdummy = liveLink % (
                rtmp, '', access_id, freeCH,
                selfAddon.getSetting("teledunetTvLogin"), '')
            liveLink = liveLink % (rtmp, channelId, access_id, freeCH,
                                   selfAddon.getSetting("teledunetTvLogin"),
                                   token)

            name += '-Teledunet'
            print 'liveLink', liveLink
            pDialog.close()
            #            try:
            #                howMaytimes=int(selfAddon.getSetting( "teledunetRetryCount" ))
            #            except:pass

            pDialog = xbmcgui.DialogProgress()
            pDialog.create('XBMC', 'Playing channel')

            patt = 'add_friend=(.*?)\'.*?<img src="premium.png"'
            res = re.findall(patt, mainpage)
            randomuser = ''
            if res and len(res) > 0:
                randomuser = res[0]


#		howMaytimes=2
#		totalTried=0
#		while totalTried<howMaytimes:
            if 1 == 1:  ##instead of while
                liveLinkPlay = liveLink
                if totalTried == 1 and doDummy:
                    liveLinkPlay = liveLinkdummy
                pDialog.update((totalTried * 100) / howMaytimes,
                               'Teledunet: Try #' + str(totalTried) + ' of ' +
                               str(howMaytimes))
                listitem = xbmcgui.ListItem(
                    label=str(name),
                    iconImage="DefaultVideo.png",
                    thumbnailImage=xbmc.getInfoImage("ListItem.Thumb"),
                    path=liveLinkPlay)
                player = CustomPlayer.MyXBMCPlayer()
                #xbmc.Player().play( liveLink,listitem)
                start = time.time()
                player.pdialogue = pDialog
                if pDialog.iscanceled():
                    break
                if 1 == 2 and totalTried == 2:
                    if len(randomuser) == 0:
                        break
                    else:
                        liveLinkPlay = re.sub('user=(.*?)&',
                                              'user=%s&' % randomuser,
                                              liveLinkPlay)
                player.play(liveLinkPlay, listitem)
                if pDialog.iscanceled():
                    break
                #pDialog.close()
                while player.is_active:
                    xbmc.sleep(200)
                #return player.urlplayed
                done = time.time()
                elapsed = done - start
                #save file
                if player.urlplayed and elapsed >= 3:
                    return True
        pDialog.close()
        return False
    except:
        traceback.print_exc(file=sys.stdout)
    return False
Example #58
0
def playmediawithproxy(media_url, name, iconImage,proxyip,port,progress):

    progress.create('Progress', 'Playing with custom proxy')
    progress.update( 50, "", "setting proxy..", "" )
    proxyset=False
    existing_proxy=''
    try:
        
        existing_proxy=getConfiguredProxy()
        print 'existing_proxy',existing_proxy
        #read and set here
        setKodiProxy( proxyip + ':' + port+':0')

        print 'proxy setting complete', getConfiguredProxy()
        proxyset=True
        progress.update( 80, "", "setting proxy complete, now playing", "" )
        progress.close()
        progress=None
        import  CustomPlayer
        player = CustomPlayer.MyXBMCPlayer()
        listitem = xbmcgui.ListItem( label = str(name), iconImage = iconImage, thumbnailImage = xbmc.getInfoImage( "ListItem.Thumb" ), path=media_url )
        player.play( media_url,listitem)
        xbmc.sleep(1000)
        while player.is_active:
            xbmc.sleep(200)
    except:
        traceback.print_exc()
    if progress:
        progress.close()
    if proxyset:
        print 'now resetting the proxy back'
        setKodiProxy(existing_proxy)
        print 'reset here'
    return ''
Example #59
0
    liz.setInfo( type="Video", infoLabels={ "Title": "Add-on settings"} )
    u = sys.argv[0] + "?" + urllib.urlencode({'url':'#','mode':'settings','name':'Add-on settings','maxbitrate':0,'proxy':'','proxy_for_chunks':False}) 
    ok=xbmcplugin.addDirectoryItem(handle=int(sys.argv[1]),url=u,listitem=liz,isFolder=False, )

elif mode == "play":
    req = urllib2.Request(url)
    req.add_header('User-Agent', 'Mozilla/5.0 (Windows; U; Windows NT 5.1; en-GB; rv:1.9.0.4) Gecko/2008092417 Firefox/4.0.4')
    response = urllib2.urlopen(req, timeout=90)
    link=response.read()
    response.close()
    data = json.loads(link)
    
    streamUrl = data['hds_stream_' + __video_quality]
    
    if '.m3u8' in streamUrl:
        listitem = xbmcgui.ListItem( label = str(name), iconImage = "DefaultVideo.png", thumbnailImage = xbmc.getInfoImage( "ListItem.Thumb" ), path=streamUrl )
        xbmc.Player().play( streamUrl,listitem)
    else:
        if __video_streaming == 'm3u8':
            streamUrl = data['hls_stream']
            streamUrl = streamUrl.replace('_1000','_' + __video_quality)
            #kiem tra xem co bitrate nay khong?
            ok = False
            try:
                pDialog = xbmcgui.DialogProgressBG()
                pDialog.create('', 'Detecting bitrate...')
                req = urllib2.Request(streamUrl)
                req.add_header('User-Agent', 'Mozilla/5.0 (Windows; U; Windows NT 5.1; en-GB; rv:1.9.0.4) Gecko/2008092417 Firefox/4.0.4')
                response = urllib2.urlopen(req, timeout=5)
                link=response.read()
                response.close()
class ItemDescription(xbmcgui.WindowXMLDialog):
    # control id's
    CONTROL_DOWNLOAD_BUTTON = 5
    CONTROL_REFRESH_BUTTON = 6
    CONTROL_GET_THUMB_BUTTON = 10
    CONTROL_PLAY_PREVIEW_BUTTON = 11
    CONTROL_CANCEL_BUTTON = 12
    CONTROL_CANCEL2_BUTTON = 303  # bouton mouse only

    # autre facon de recuperer tous les infos d'un item dans la liste.
    i_thumbnail = xbmc.getInfoImage("ListItem.Thumb")
    i_previewPicture = xbmc.getInfoImage("ListItem.Property(fanartpicture)")
    i_date = unicode(xbmc.getInfoLabel("ListItem.Property(date)"), "utf-8")
    i_title = unicode(xbmc.getInfoLabel("ListItem.Property(title)"), "utf-8")
    i_added = unicode(xbmc.getInfoLabel("ListItem.Property(added)"), "utf-8")
    i_itemId = unicode(xbmc.getInfoLabel("ListItem.Property(itemId)"), "utf-8")
    i_author = unicode(xbmc.getInfoLabel("ListItem.Property(author)"), "utf-8")
    i_outline = unicode(xbmc.getInfoLabel("ListItem.Property(outline)"),
                        "utf-8")
    i_version = unicode(xbmc.getInfoLabel("ListItem.Property(version)"),
                        "utf-8")
    i_language = unicode(xbmc.getInfoLabel("ListItem.Property(language)"),
                         "utf-8")
    i_fileName = unicode(xbmc.getInfoLabel("ListItem.Property(fileName)"),
                         "utf-8")
    i_type = unicode(xbmc.getInfoLabel("Container.Property(Category)"),
                     "utf-8")
    i_dlsource = unicode(xbmc.getInfoLabel("container.Property(DLSource)"),
                         "utf-8")
    i_description = unicode(
        xbmc.getInfoLabel("ListItem.Property(description)"), "utf-8")
    i_previewVideoURL = unicode(
        xbmc.getInfoLabel("ListItem.Property(previewVideoURL)"), "utf-8")

    def __init__(self, *args, **kwargs):
        xbmcgui.WindowXMLDialog.__init__(self, *args, **kwargs)
        xbmc.executebuiltin("Skin.Reset(AnimeWindowXMLDialogClose)")
        xbmc.executebuiltin("Skin.SetBool(AnimeWindowXMLDialogClose)")

        self.mainwin = kwargs["mainwin"]

    def onInit(self):
        # onInit est pour le windowXML seulement
        try:
            self._set_skin_colours()
            self._set_controls_labels()
        except:
            print_exc()

    def _set_skin_colours(self):
        try:
            xbmc.executebuiltin("Skin.SetString(PassionSkinColourPath,%s)" %
                                (self.mainwin.settings["skin_colours_path"], ))
            xbmc.executebuiltin("Skin.SetString(PassionSkinHexColour,%s)" %
                                ((self.mainwin.settings["skin_colours"]
                                  or get_default_hex_color()), ))
            xbmc.executebuiltin(
                "Skin.SetString(PassionLabelHexColour,%s)" %
                ((self.mainwin.settings["labels_colours"]
                  or get_default_hex_color("Blue Confluence")), ))
        except:
            xbmc.executebuiltin(
                "Skin.SetString(PassionLabelHexColour,ffffffff)")
            xbmc.executebuiltin(
                "Skin.SetString(PassionSkinHexColour,ffffffff)")
            xbmc.executebuiltin(
                "Skin.SetString(PassionSkinColourPath,default)")
            print_exc()

    def _set_controls_labels(self):
        xbmcgui.lock()
        self.i_itemId = self.i_itemId or str(
            self.mainwin.getCurrentListPosition() + 1)
        try:
            if self.i_previewPicture:
                filename = os.path.basename(self.i_previewPicture)
                thumbnail = os.path.join(BASE_THUMBS_PATH, filename[0],
                                         filename)
                if os.path.isfile(thumbnail): self.i_thumbnail = thumbnail
        except:
            print_exc()
        try:
            self.getControl(48).reset()
            listitem = xbmcgui.ListItem(self.i_title, "", self.i_thumbnail,
                                        self.i_thumbnail)
            listitem.setProperty("title", self.i_title)
            listitem.setProperty("itemId", self.i_itemId)
            listitem.setProperty("author", self.i_author)
            listitem.setProperty("DLSource", self.i_dlsource)
            listitem.setProperty("type", self.i_type)
            listitem.setProperty("language", self.i_language)
            listitem.setProperty("version", self.i_version)
            listitem.setProperty("date", self.i_date)
            listitem.setProperty("added", self.i_added)
            listitem.setProperty("outline", self.i_outline)
            #listitem.setProperty( "rating", self.i_rating ) # not implanted
            listitem.setProperty("fileName", self.i_fileName)

            listitem.setProperty("description", self.i_description or _(604))
            listitem.setProperty("fanartpicture", self.i_previewPicture)
            listitem.setProperty("previewVideoURL", self.i_previewVideoURL)
            self.getControl(48).addItem(listitem)
        except:
            print_exc()
        xbmcgui.unlock()

    def get_item_infos(self, main_listitem):
        try:
            self.i_date = unicode(main_listitem.getProperty("date"), "utf-8")
            self.i_added = unicode(main_listitem.getProperty("added"), "utf-8")
            self.i_title = unicode(main_listitem.getProperty("title"), "utf-8")
            self.i_itemId = unicode(
                main_listitem.getProperty("itemId"),
                "utf-8") or str(self.mainwin.getCurrentListPosition() + 1)
            self.i_author = unicode(main_listitem.getProperty("author"),
                                    "utf-8")
            self.i_version = unicode(main_listitem.getProperty("version"),
                                     "utf-8")
            self.i_outline = unicode(main_listitem.getProperty("outline"),
                                     "utf-8")
            self.i_language = unicode(main_listitem.getProperty("language"),
                                      "utf-8")
            self.i_fileName = unicode(main_listitem.getProperty("fileName"),
                                      "utf-8")
            self.i_description = unicode(
                main_listitem.getProperty("description"), "utf-8")
            self.i_previewPicture = unicode(
                main_listitem.getProperty("fanartpicture"), "utf-8")
            self.i_previewVideoURL = unicode(
                main_listitem.getProperty("previewVideoURL"), "utf-8")
        except:
            print_exc()

    def onFocus(self, controlID):
        #cette fonction n'est pas utiliser ici, mais dans les XML si besoin
        #Note: Mais il faut la declarer :)
        pass

    def onClick(self, controlID):
        try:
            if controlID in (self.CONTROL_CANCEL_BUTTON,
                             self.CONTROL_CANCEL2_BUTTON):
                # bouton quitter, on ferme le dialog
                self._close_dialog()
            elif controlID == self.CONTROL_DOWNLOAD_BUTTON:
                #bouton downlaod ou installer
                self.mainwin.install_add_ons()
            elif controlID == self.CONTROL_REFRESH_BUTTON:
                #bouton pour rafraichir l'item en temps reel ds le dialog et l'item de la liste en court
                self.getControl(48).reset()
                main_listitem = self.mainwin.refresh_item()
                self.get_item_infos(main_listitem)
                self._set_controls_labels()
            elif controlID == self.CONTROL_GET_THUMB_BUTTON:
                #bouton pour choisir une vignette quand le add-ons est downloader
                #non utilise pour le moment (desactive)
                pass
            elif controlID == self.CONTROL_PLAY_PREVIEW_BUTTON:
                #bouton pour ecouter un add-ons si disponible
                #non utilise pour le moment (desactive)
                pass
            else:
                pass
        except:
            print_exc()

    def onAction(self, action):
        #( ACTION_PARENT_DIR, ACTION_PREVIOUS_MENU, ACTION_CONTEXT_MENU, )
        if action in (9, 10, 117): self._close_dialog()

    def _close_dialog(self, OK=False):
        import time
        xbmc.executebuiltin("Skin.Reset(AnimeWindowXMLDialogClose)")
        time.sleep(.4)
        #xbmc.sleep( 100 )
        self.close()