示例#1
0
文件: SnapVideo.py 项目: noba3/KoTos
 def getVideoInfo(self, video_url):
     videoInfo = None
     videoId = self.getVideoId(video_url)
     if videoId is not None:
         Logger.logDebug('Snapper selected = ' + self.getModuleName() + ' for video URL = ' + video_url)
         videoInfo = self.__getVideoInfo(videoId)
     return videoInfo
示例#2
0
def retrieveVideoInfo(videoUrl):
    try:
        xbmcaddon.Addon('plugin.video.vevo')
    except:
        dialog = xbmcgui.Dialog()
        dialog.ok('[B][COLOR red]MISSING: [/COLOR][/B] VEVO add-on', '',
                  'Please install VEVO add-on created by BlueCop!',
                  'Available at http://code.google.com/p/bluecop-xbmc-repo/')
        raise
    video_info = VideoInfo()
    video_info.set_video_hosting_info(getVideoHostingInfo())
    video_info.set_video_id(videoUrl)
    addon_url = 'plugin://plugin.video.vevo/?'
    vevo_id = videoUrl.split('/')[-1]
    if videoUrl.startswith('playlist'):
        url = urllib.quote_plus(
            'http://api.vevo.com/mobile/v2/playlist/%s.json?' % vevo_id)
        addon_url += 'url=%s' % url
        addon_url += '&mode=playPlaylist'
        addon_url += '&duration=210'
        addon_url += '&page=1'
        video_info.add_video_link(XBMC_EXECUTE_PLUGIN,
                                  addon_url,
                                  addUserAgent=False,
                                  addReferer=False)
        video_info.set_video_image('')
        video_info.set_video_name(' ')
    else:
        url = 'http://videoplayer.vevo.com/VideoService/AuthenticateVideo?isrc=%s&extended=true' % vevo_id
        video = json.loads(
            HttpUtils.HttpClient().getHtmlContent(url=url))['video']
        title = ''
        try:
            title = video['title'].encode('utf-8')
        except:
            title = ''
        video_image = video['imageUrl']
        if len(video['featuredArtists']) > 0:
            feats = ''
            for featuredartist in video['featuredArtists']:
                # featuredartist_image = featuredartist['image_url']
                featuredartist_name = featuredartist['artistName'].encode(
                    'utf-8')
                feats += featuredartist_name + ', '
            feats = feats[:-2]
            title += ' (ft. ' + feats + ')'

        addon_url += 'url=%s' % vevo_id
        addon_url += '&mode=playVideo'
        addon_url += '&duration=210'
        video_info.add_video_link(VIDEO_QUAL_SD,
                                  addon_url,
                                  addUserAgent=False,
                                  addReferer=False)
        video_info.set_video_image(video_image)
        video_info.set_video_name(title)

    Logger.logDebug(addon_url)
    video_info.set_video_stopped(False)
    return video_info
示例#3
0
文件: SnapVideo.py 项目: noba3/KoTos
 def isVideoHostedByYou(self, video_url):
     isVideoHoster = False
     videoId = self.getVideoId(video_url)
     if videoId is not None:
         Logger.logDebug('Snapper selected = ' + self.getModuleName() + ' for video URL = ' + video_url)
         isVideoHoster = True
     return isVideoHoster
示例#4
0
文件: Metadata.py 项目: noba3/KoTos
def __addMovieInfo_in_item(item):
    if item.get_next_action_name() == 'Movie_Streams':
        year = unicode(item.get_moving_data()['movieYear'],
                       errors='ignore').encode('utf-8')
        title = unicode(item.get_moving_data()['movieTitle'],
                        errors='ignore').encode('utf-8')
        meta = None
        try:
            global __metaget__
            if __metaget__ is None:
                __metaget__ = metahandlers.MetaData()
            meta = __metaget__.get_meta('movie', title, year=year)
        except:
            Logger.logDebug('Failed to load metahandler module')
        xbmc_item = item.get_xbmc_list_item_obj()

        if (meta is not None):
            xbmc_item.setIconImage(meta['thumb_url'])
            xbmc_item.setThumbnailImage(meta['cover_url'])
            videoInfo = {'trailer_url': meta['trailer_url']}
            for key, value in meta.items():
                if type(value) is str:
                    value = unicode(value).encode('utf-8')
                videoInfo[key] = value
            xbmc_item.setInfo('video', videoInfo)
            xbmc_item.setProperty('fanart_image', meta['backdrop_url'])
            item.add_request_data('videoInfo', videoInfo)

            contextMenuItems = []
            contextMenuItems.append(('Movie Information', 'XBMC.Action(Info)'))
            xbmc_item.addContextMenuItems(contextMenuItems, replaceItems=False)
        else:
            xbmc_item.setInfo('video', {'title': title, 'year': year})
            item.add_request_data('videoInfo', {'title': title, 'year': year})
def callBackDialogProgressBar(function_obj, function_args, heading, failure_message=None, line1='Please wait...', line2='Retrieved $current_index of $total_it items', line3='To go back, press the Cancel button'):
    total_iteration = len(function_args)
    current_index = 0
    ProgressDisplayer().end()
    pDialog = None
    if not SUPPRESS_DIALOG_MSG:
        pDialog = xbmcgui.DialogProgress()
        pDialog.create(heading, line1, line2.replace('$total_it', str(total_iteration)).replace('$current_index', str(current_index)), line3)
        pDialog.update(1)
    Logger.logDebug('Total Iterations = ' + str(total_iteration))
    function_returns = []
    isCanceled = False
    for arg in function_args:
        try:
            returnedObj = function_obj(arg)
            if returnedObj is not None and type(returnedObj) is list:
                function_returns.extend(returnedObj)
            elif returnedObj is not None:
                function_returns.append(returnedObj)
            if not SUPPRESS_DIALOG_MSG and pDialog is not None:
                current_index = current_index + 1
                percent = (current_index * 100) / total_iteration
                pDialog.update(percent, line1, line2.replace('$total_it', str(total_iteration)).replace('$current_index', str(current_index)), line3)
                if (pDialog.iscanceled()):
                    isCanceled = True
                    break
        except Exception, e:
            if not SUPPRESS_DIALOG_MSG and pDialog is not None and failure_message is not None:
                pDialog.close()
                dialog = xbmcgui.Dialog()
                dialog.ok('[B][COLOR red]FAILED: [/COLOR][/B]Info Retrieval Process', failure_message, 'You may like to try again later or use other source if available')
            Logger.logFatal(e)
            raise Exception(ExceptionHandler.DONOT_DISPLAY_ERROR, '')
        if isCanceled:
            raise Exception(ExceptionHandler.PROCESS_STOPPED, 'It looks like you don\'t want wait more|Process was stopped in between')
示例#6
0
def retrieveVideoInfo(videoUrl):
    try:
        xbmcaddon.Addon('plugin.video.iplayer')
    except:
        dialog = xbmcgui.Dialog()
        dialog.ok('[B][COLOR red]MISSING: [/COLOR][/B] BBC IPlayer v2 add-on',
                  '',
                  'Please install BBC IPlayer v2 add-on created by Hitcher!',
                  'Available at http://code.google.com/p/xbmc-iplayerv2/')
        raise
    video_info = VideoInfo()
    video_info.set_video_hosting_info(getVideoHostingInfo())
    video_info.set_video_id(videoUrl)
    addon_url = 'plugin://plugin.video.iplayer/?'
    video_params = videoUrl.split('/')

    addon_url += 'pid=%s' % video_params[0]
    video_info.add_video_link(VIDEO_QUAL_SD,
                              addon_url,
                              addUserAgent=False,
                              addReferer=False)
    video_info.set_video_image(
        'http://www.bbc.co.uk/iplayer/images/episode/%s_512_288.jpg' %
        video_params[0])
    video_info.set_video_name(video_params[1].replace('_', ' '))

    Logger.logDebug(addon_url)
    video_info.set_video_stopped(False)
    return video_info
示例#7
0
def retieveTrailerStream(request_obj, response_obj):
    soup = None
    title = request_obj.get_data()['movieTitle']
    if request_obj.get_data().has_key('movieInfo'):
        soup = BeautifulSoup.BeautifulSoup(request_obj.get_data()['movieInfo'])
    elif request_obj.get_data().has_key('moviePageUrl'):
        contentDiv = BeautifulSoup.SoupStrainer('div', {'dir': 'ltr'})
        soup = HttpUtils.HttpClient().getBeautifulSoup(
            url=request_obj.get_data()['moviePageUrl'],
            parseOnlyThese=contentDiv)
    if soup is None:
        return
    videoLink = None
    Logger.logDebug(soup.prettify())
    frameTag = soup.findChild('iframe', recursive=True)
    if frameTag is not None:
        videoLink = frameTag['src']
    else:
        paramTag = soup.findChild('param',
                                  attrs={'name': 'movie'},
                                  recursive=True)
        if paramTag is not None:
            videoLink = paramTag['value']
        else:
            videoLink = soup.findChild('embed', recursive=True)['src']
    request_obj.set_data({'videoLink': videoLink, 'videoTitle': title})
示例#8
0
def __addMovieInfo_in_item(item):
    if item.get_next_action_name() == 'Movie_Streams':
        year = unicode(item.get_moving_data()['movieYear'], errors='ignore').encode('utf-8')
        title = unicode(item.get_moving_data()['movieTitle'], errors='ignore').encode('utf-8')
        meta = None
        try:
            global __metaget__
            if __metaget__ is None:
                __metaget__ = metahandlers.MetaData()
            meta = __metaget__.get_meta('movie', title, year=year)
        except:
            Logger.logDebug('Failed to load metahandler module')
        xbmc_item = item.get_xbmc_list_item_obj()
        
        if(meta is not None):
            xbmc_item.setIconImage(meta['thumb_url'])
            xbmc_item.setThumbnailImage(meta['cover_url'])
            videoInfo = {'trailer_url':meta['trailer_url']}
            for key, value in meta.items():
                if type(value) is str:
                    value = unicode(value).encode('utf-8')
                videoInfo[key] = value
            xbmc_item.setInfo('video', videoInfo)
            xbmc_item.setProperty('fanart_image', meta['backdrop_url'])
            item.add_request_data('videoInfo', videoInfo)
            
            contextMenuItems = []
            contextMenuItems.append(('Movie Information', 'XBMC.Action(Info)'))
            xbmc_item.addContextMenuItems(contextMenuItems, replaceItems=False)
        else:
            xbmc_item.setInfo('video', {'title':title, 'year':year})
            item.add_request_data('videoInfo', {'title':title, 'year':year})
示例#9
0
def retrieveVideoLinks(request_obj, response_obj):
    video_source_id = 1
    video_source_img = None
    video_source_name = None
    video_part_index = 0
    video_playlist_items = []
    ignoreAllLinks = False
    
    content = BeautifulSoup.SoupStrainer('blockquote', {'class':re.compile(r'\bpostcontent\b')})
    soup = HttpClient().getBeautifulSoup(url=request_obj.get_data()['episodeUrl'], parseOnlyThese=content)
    for e in soup.findAll('br'):
        e.extract()
    Logger.logDebug(soup)
    if soup.has_key('div'):
        soup = soup.findChild('div', recursive=False)
    prevChild = ''
    prevAFont = None
    for child in soup.findChildren():
        if (child.name == 'img' or child.name == 'b' or (child.name == 'font' and not child.findChild('a'))):
            if (child.name == 'b' and prevChild == 'a') or (child.name == 'font' and child == prevAFont):
                continue
            else:
                if len(video_playlist_items) > 0:
                    response_obj.addListItem(__preparePlayListItem__(video_source_id, video_source_img, video_source_name, video_playlist_items))
                if video_source_img is not None:
                    video_source_id = video_source_id + 1
                    video_source_img = None
                    video_source_name = None
                    video_part_index = 0
                    video_playlist_items = []
                ignoreAllLinks = False
        elif not ignoreAllLinks and child.name == 'a' and not re.search('multi', str(child['href']), re.IGNORECASE):
            video_part_index = video_part_index + 1
            video_link = {}
            video_link['videoTitle'] = 'Source #' + str(video_source_id) + ' | ' + 'Part #' + str(video_part_index) + ' | ' + child.getText()
            video_link['videoLink'] = str(child['href'])
            try:
                try:
                    __prepareVideoLink__(video_link)
                except Exception, e:
                    Logger.logFatal(e)
                    video_hosting_info = SnapVideo.findVideoHostingInfo(video_link['videoLink'])
                    if video_hosting_info is None or video_hosting_info.get_video_hosting_name() == 'UrlResolver by t0mm0':
                        raise
                    video_link['videoSourceImg'] = video_hosting_info.get_video_hosting_image()
                    video_link['videoSourceName'] = video_hosting_info.get_video_hosting_name()
                video_playlist_items.append(video_link)
                video_source_img = video_link['videoSourceImg']
                video_source_name = video_link['videoSourceName']
                
                item = ListItem()
                item.add_request_data('videoLink', video_link['videoLink'])
                item.add_request_data('videoTitle', video_link['videoTitle'])
                item.set_next_action_name('SnapAndPlayVideo')
                xbmcListItem = xbmcgui.ListItem(label='Source #' + str(video_source_id) + ' | ' + 'Part #' + str(video_part_index) , iconImage=video_source_img, thumbnailImage=video_source_img)
                item.set_xbmc_list_item_obj(xbmcListItem)
                response_obj.addListItem(item)
                prevAFont = child.findChild('font')
            except:
示例#10
0
def __retrieveChannelTVShows__(tvChannelObj):
    running_tvshows = []
    finished_tvshows = []
    try:
        running_tvshows = __retrieveTVShows__(tvChannelObj["running_tvshows_url"])
        if(len(running_tvshows) == 0):
            running_tvshows.append({"name":"ENTER TO VIEW :: This is the only easy way to view!", "url":BASE_WSITE_URL + tvChannelObj["running_tvshows_url"]})
    except Exception, e:
        Logger.logFatal(e)
        Logger.logDebug('Failed to load a channel... Continue retrieval of next tv show')
示例#11
0
def callBackDialogProgressBar(
        function_obj,
        function_args,
        heading,
        failure_message=None,
        line1='Please wait...',
        line2='Retrieved $current_index of $total_it items',
        line3='To go back, press the Cancel button'):
    total_iteration = len(function_args)
    current_index = 0
    ProgressDisplayer().end()
    pDialog = None
    if not SUPPRESS_DIALOG_MSG:
        pDialog = xbmcgui.DialogProgress()
        pDialog.create(
            heading, line1,
            line2.replace('$total_it', str(total_iteration)).replace(
                '$current_index', str(current_index)), line3)
        pDialog.update(1)
    Logger.logDebug('Total Iterations = ' + str(total_iteration))
    function_returns = []
    isCanceled = False
    for arg in function_args:
        try:
            returnedObj = function_obj(arg)
            if returnedObj is not None and type(returnedObj) is list:
                function_returns.extend(returnedObj)
            elif returnedObj is not None:
                function_returns.append(returnedObj)
            if not SUPPRESS_DIALOG_MSG and pDialog is not None:
                current_index = current_index + 1
                percent = (current_index * 100) / total_iteration
                pDialog.update(
                    percent, line1,
                    line2.replace('$total_it', str(total_iteration)).replace(
                        '$current_index', str(current_index)), line3)
                if (pDialog.iscanceled()):
                    isCanceled = True
                    break
        except Exception, e:
            if not SUPPRESS_DIALOG_MSG and pDialog is not None and failure_message is not None:
                pDialog.close()
                dialog = xbmcgui.Dialog()
                dialog.ok(
                    '[B][COLOR red]FAILED: [/COLOR][/B]Info Retrieval Process',
                    failure_message,
                    'You may like to try again later or use other source if available'
                )
            Logger.logFatal(e)
            raise Exception(ExceptionHandler.DONOT_DISPLAY_ERROR, '')
        if isCanceled:
            raise Exception(
                ExceptionHandler.PROCESS_STOPPED,
                'It looks like you don\'t want wait more|Process was stopped in between'
            )
示例#12
0
 def __send_request_to_google_analytics(self, utm_url):
     ua = 'Mozilla/5.0 (Windows; U; Windows NT 5.1; en-GB; rv:1.9.0.3) Gecko/2008092417 Firefox/3.0.3'
     import urllib2
     try:
         if self.addon_context.addon.getSetting('ga_enabled') == 'true': #default is disabled
             req = urllib2.Request(utm_url, None, {'User-Agent':ua})
             response = urllib2.urlopen(req)
             print response.read()
             response.close()
     except Exception, e:
         Logger.logError(e)
         Logger.logDebug ("GA fail: %s" % utm_url)
示例#13
0
 def __send_request_to_google_analytics(self, utm_url):
     ua = 'Mozilla/5.0 (Windows; U; Windows NT 5.1; en-GB; rv:1.9.0.3) Gecko/2008092417 Firefox/3.0.3'
     import urllib2
     try:
         if self.addon_context.addon.getSetting(
                 'ga_enabled') == 'true':  #default is disabled
             req = urllib2.Request(utm_url, None, {'User-Agent': ua})
             response = urllib2.urlopen(req)
             print response.read()
             response.close()
     except Exception, e:
         Logger.logError(e)
         Logger.logDebug("GA fail: %s" % utm_url)
示例#14
0
def start(addon_id, addon_ver=None):
    try:
        Logger.logDebug(sys.argv)
        global __addon_id__
        __addon_id__ = addon_id
        __addon_ver__ = addon_ver
        
        containerObj = Container(addon_id=addon_id, addon_ver=addon_ver)
        action_id = containerObj.getTurtleRequest().get_action_id()
        containerObj.performAction(action_id)
    except urllib2.URLError, e:
        Logger.logFatal(e)
        XBMCInterfaceUtils.displayDialogMessage('Unable to connect', 'Please choose a different source if available in add-on.', 'Website used in add-on is down, try to access using web browser.', 'Please share logs with developer if problem keeps coming!')
示例#15
0
 def __init__(self, params=None):
     Logger.logDebug(params)
     self.set_action_id('__start__')
     if params is None:
         self.set_params({})
     elif type(params) is str:
         self.set_params(HttpUtils.getUrlParams(params))
     elif type(params) is dict:
         self.set_params(params)
     if self.get_params().has_key('actionId') and self.get_params()['actionId'] != '':
         self.set_action_id(self.get_params()['actionId'])
     if self.get_params().has_key('data') and self.get_params()['data'] != '':
         self.set_data(AddonUtils.decodeData(self.get_params()['data']))
示例#16
0
文件: SnapVideo.py 项目: noba3/KoTos
def __initializeSnappers():
    snapper_filepath = AddonUtils.getCompleteFilePath(Container().getAddonContext().addonPath, 'snapvideo', 'snappers.xml')
    if not AddonUtils.doesFileExist(snapper_filepath):
        snapper_filepath = AddonUtils.getCompleteFilePath(Container().getAddonContext().turtle_addonPath, 'lib/snapvideo', 'snappers.xml')
    global snappers
    if snappers is not None:
        return snappers
    snappers = []
    Logger.logDebug('Loading snappers.xml from path... ' + snapper_filepath)
    snappers_xml = AddonUtils.getBeautifulSoupObj(snapper_filepath)
    for snapperTag in snappers_xml.findAll('snapper', attrs={'enabled':'true'}):
        snappers.append(Snapper(snapperTag))
    return snappers
示例#17
0
def retrieveAudioInfo(audioUrl):
    url = 'https://api.soundcloud.com/' + audioUrl
    jObj = json.loads(HttpUtils.HttpClient().getHtmlContent(url=url))
    
    video_info = VideoInfo()
    video_info.set_video_hosting_info(getVideoHostingInfo())
    video_info.set_video_id(url)
    video_info.add_video_link(VIDEO_QUAL_SD, jObj['http_mp3_128_url'], addUserAgent=False, addReferer=False)
    video_info.set_video_image('')
    video_info.set_video_name('')
    
    Logger.logDebug(jObj['http_mp3_128_url'])
    video_info.set_video_stopped(False)
    return video_info
示例#18
0
def playZappyVideo(request_obj, response_obj):
    Logger.logDebug(request_obj.get_data());
    Container().ga_client.reportAction('zappyvideo')
    video_id = request_obj.get_data()['videoId']
    port = request_obj.get_data()['port']
    ipaddress = request_obj.get_data()['client_ip']
    video_url = "http://" + ipaddress + ":" + str(port) + "/?videoId=" + video_id
    item = ListItem()
    item.get_moving_data()['videoStreamUrl'] = video_url
    item.set_next_action_name('Play')
    xbmcListItem = xbmcgui.ListItem(label='Streaming Video')
    item.set_xbmc_list_item_obj(xbmcListItem)
    response_obj.addListItem(item)
    response_obj.addServiceResponseParam("status", "success")
    response_obj.addServiceResponseParam("message", "Enjoy the video!")
示例#19
0
 def __init__(self, params=None):
     Logger.logDebug(params)
     self.set_action_id('__start__')
     if params is None:
         self.set_params({})
     elif type(params) is str:
         self.set_params(HttpUtils.getUrlParams(params))
     elif type(params) is dict:
         self.set_params(params)
     if self.get_params().has_key(
             'actionId') and self.get_params()['actionId'] != '':
         self.set_action_id(self.get_params()['actionId'])
     if self.get_params().has_key(
             'data') and self.get_params()['data'] != '':
         self.set_data(AddonUtils.decodeData(self.get_params()['data']))
示例#20
0
def retrieveVideoInfo(videoUrl):
    try: 
        xbmcaddon.Addon('plugin.video.vevo')
    except: 
        dialog = xbmcgui.Dialog()
        dialog.ok('[B][COLOR red]MISSING: [/COLOR][/B] VEVO add-on', '', 'Please install VEVO add-on created by BlueCop!', 'Available at http://code.google.com/p/bluecop-xbmc-repo/')
        raise
    video_info = VideoInfo()
    video_info.set_video_hosting_info(getVideoHostingInfo())
    video_info.set_video_id(videoUrl)
    addon_url = 'plugin://plugin.video.vevo/?'
    vevo_id = videoUrl.split('/')[-1]
    if videoUrl.startswith('playlist'):
        url = urllib.quote_plus('http://api.vevo.com/mobile/v2/playlist/%s.json?' % vevo_id)
        addon_url += 'url=%s' % url
        addon_url += '&mode=playPlaylist'
        addon_url += '&duration=210'
        addon_url += '&page=1'
        video_info.add_video_link(XBMC_EXECUTE_PLUGIN, addon_url, addUserAgent=False, addReferer=False)
        video_info.set_video_image('')
        video_info.set_video_name(' ')
    else:
        url = 'http://videoplayer.vevo.com/VideoService/AuthenticateVideo?isrc=%s&extended=true' % vevo_id
        video = json.loads(HttpUtils.HttpClient().getHtmlContent(url=url))['video']
        title = ''
        try:title = video['title'].encode('utf-8')
        except: title = ''                  
        video_image = video['imageUrl']
        if len(video['featuredArtists']) > 0:
            feats = ''
            for featuredartist in video['featuredArtists']:
                # featuredartist_image = featuredartist['image_url']
                featuredartist_name = featuredartist['artistName'].encode('utf-8')
                feats += featuredartist_name + ', '
            feats = feats[:-2]
            title += ' (ft. ' + feats + ')'
                
        addon_url += 'url=%s' % vevo_id
        addon_url += '&mode=playVideo'
        addon_url += '&duration=210'
        video_info.add_video_link(VIDEO_QUAL_SD, addon_url, addUserAgent=False, addReferer=False)
        video_info.set_video_image(video_image)
        video_info.set_video_name(title)
    
    Logger.logDebug(addon_url)
    video_info.set_video_stopped(False)
    return video_info
示例#21
0
文件: SoundCloud.py 项目: noba3/KoTos
def retrieveAudioInfo(audioUrl):
    url = 'https://api.soundcloud.com/' + audioUrl
    jObj = json.loads(HttpUtils.HttpClient().getHtmlContent(url=url))

    video_info = VideoInfo()
    video_info.set_video_hosting_info(getVideoHostingInfo())
    video_info.set_video_id(url)
    video_info.add_video_link(VIDEO_QUAL_SD,
                              jObj['http_mp3_128_url'],
                              addUserAgent=False,
                              addReferer=False)
    video_info.set_video_image('')
    video_info.set_video_name('')

    Logger.logDebug(jObj['http_mp3_128_url'])
    video_info.set_video_stopped(False)
    return video_info
示例#22
0
def start(addon_id, addon_ver=None):
    try:
        Logger.logDebug(sys.argv)
        global __addon_id__
        __addon_id__ = addon_id
        __addon_ver__ = addon_ver

        containerObj = Container(addon_id=addon_id, addon_ver=addon_ver)
        action_id = containerObj.getTurtleRequest().get_action_id()
        containerObj.performAction(action_id)
    except urllib2.URLError, e:
        Logger.logFatal(e)
        XBMCInterfaceUtils.displayDialogMessage(
            'Unable to connect',
            'Please choose a different source if available in add-on.',
            'Website used in add-on is down, try to access using web browser.',
            'Please share logs with developer if problem keeps coming!')
示例#23
0
文件: Tune_pk.py 项目: noba3/KoTos
def retrieveVideoInfo(video_id):

    video_info = VideoInfo()
    video_info.set_video_hosting_info(getVideoHostingInfo())
    video_info.set_video_id(video_id)
    try:
        video_info_link = 'http://embed.tune.pk/play/' + str(
            video_id) + '?autoplay=no'
        html = HttpUtils.HttpClient().getHtmlContent(url=video_info_link)
        image = re.compile("preview_img = '(.+?)';").findall(html)
        if image is not None and len(image) == 1:
            video_info.set_video_image(str(image[0]))
        html = html.replace('\n\r', '').replace('\r', '').replace('\n', '')
        sources = re.compile("{(.+?)}").findall(
            re.compile("sources:(.+?)]").findall(html)[0])
        for source in sources:
            video_link = str(re.compile('file[: ]*"(.+?)"').findall(source)[0])
            Logger.logDebug(video_link)
            label_text = re.compile('label[: ]*"(.+?)"').findall(source)
            if label_text is not None and len(label_text) == 1:
                label = str(label_text[0])
                Logger.logDebug(label)
                if label == '240p':
                    video_info.add_video_link(VIDEO_QUAL_LOW, video_link)
                elif label == '360p' and video_info.get_video_link(
                        VIDEO_QUAL_SD) is None:
                    video_info.add_video_link(VIDEO_QUAL_SD, video_link)
                elif label == '480p' or label == 'SD':
                    video_info.add_video_link(VIDEO_QUAL_SD, video_link)
                elif label == '720p' or label == 'HD':
                    video_info.add_video_link(VIDEO_QUAL_HD_720, video_link)
                elif label == '1080p':
                    video_info.add_video_link(VIDEO_QUAL_HD_1080, video_link)
                else:
                    video_info.add_video_link(VIDEO_QUAL_SD, video_link)

            else:
                video_info.add_video_link(VIDEO_QUAL_SD, video_link)
        video_info.set_video_stopped(False)

    except Exception, e:
        Logger.logError(e)
        video_info.set_video_stopped(True)
示例#24
0
def retrievePakVideoLinks(request_obj, response_obj):
    video_source_id = 0
    video_source_img = None
    video_part_index = 0
    video_playlist_items = []
    html = HttpClient().getHtmlContent(url=request_obj.get_data()['episodeUrl'])
    videoFrameTags = re.compile('<iframe class\="(youtube|dailymotion)\-player" (.+?)src\="(.+?)"').findall(html)
    Logger.logDebug(videoFrameTags)
    for frameTagType, extra, videoLink in videoFrameTags:
        source_img = None
        if frameTagType == 'youtube':
            source_img = 'http://www.automotivefinancingsystems.com/images/icons/socialmedia_youtube_256x256.png'
        elif frameTagType == 'dailymotion':
            source_img = 'http://press.dailymotion.com/fr/wp-content/uploads/logo-Dailymotion.png'
            
        if video_source_img is None or video_source_img != source_img:
            if len(video_playlist_items) > 0:
                response_obj.addListItem(__preparePlayListItem__(video_source_id, video_source_img, video_playlist_items))
            video_source_id = video_source_id + 1
            video_source_img = source_img
            video_part_index = 0
            video_playlist_items = []
            
        video_part_index = video_part_index + 1
        video_link = {}
        video_link['videoTitle'] = 'Source #' + str(video_source_id) + ' | ' + 'Part #' + str(video_part_index)
        video_link['videoLink'] = videoLink
        video_playlist_items.append(video_link)
        
        item = ListItem()
        item.add_request_data('videoLink', video_link['videoLink'])
        item.add_request_data('videoTitle', video_link['videoTitle'])
        item.set_next_action_name('SnapAndPlayVideo')
        xbmcListItem = xbmcgui.ListItem(label='Source #' + str(video_source_id) + ' | ' + 'Part #' + str(video_part_index) , iconImage=video_source_img, thumbnailImage=video_source_img)
        item.set_xbmc_list_item_obj(xbmcListItem)
        response_obj.addListItem(item)
            
    if len(video_playlist_items) > 0:
        response_obj.addListItem(__preparePlayListItem__(video_source_id, video_source_img, video_playlist_items))
        
    playNowItem = __findPlayNowStream__(response_obj.get_item_list())
    if playNowItem is not None:
        request_obj.set_data({'videoPlayListItems': playNowItem.get_request_data()['videoPlayListItems']})
示例#25
0
文件: SnapVideo.py 项目: noba3/KoTos
 def __init__(self, snapper_Tag):
     modulePath = snapper_Tag['module']
     functionName = snapper_Tag['function']
     self.__video_id_regex_list = []
     for videoIdTag in snapper_Tag.findAll('video-id'):
         self.__video_id_regex_list.append(videoIdTag['regex'])
     self.__is_playlist = False
     if snapper_Tag.has_key('playlist') and snapper_Tag['playlist'] == 'true':
         self.__is_playlist = True
     components = modulePath.split('.')
     module = __import__(modulePath)
     if components is not None and isinstance(components, list):
         for index in range(1, len(components)):
             module = getattr(module, components[index])
     
     self.__snapper_module = module
     self.__snapper_modulepath = modulePath + ':' + functionName
     self.__getVideoInfo = getattr(module, functionName)
     self.getVideoHostingInfo = getattr(module, 'getVideoHostingInfo')
     Logger.logDebug('Snapper loaded = ' + modulePath)
示例#26
0
def __findPlayNowStream__(new_items):
    if Container().getAddonContext().addon.getSetting('autoplayback') == 'false':
        return None
    selectedIndex = None
    selectedSource = None
    for item in new_items:
        if item.get_moving_data().has_key('isContinuousPlayItem') and item.get_moving_data()['isContinuousPlayItem']:
            try:
                Logger.logDebug(item.get_moving_data()['videoSourceName'])
                preference = PREFERRED_DIRECT_PLAY_ORDER.index(item.get_moving_data()['videoSourceName'])
                if preference == 0:
                    selectedSource = item
                    selectedIndex = 0
                    break
                elif selectedIndex is None or selectedIndex > preference:
                    selectedSource = item
                    selectedIndex = preference
            except ValueError:
                continue
    return selectedSource
def retrieveVideoInfo(videoUrl):
    try: 
        xbmcaddon.Addon('plugin.video.iplayer')
    except: 
        dialog = xbmcgui.Dialog()
        dialog.ok('[B][COLOR red]MISSING: [/COLOR][/B] BBC IPlayer v2 add-on', '', 'Please install BBC IPlayer v2 add-on created by Hitcher!', 'Available at http://code.google.com/p/xbmc-iplayerv2/')
        raise
    video_info = VideoInfo()
    video_info.set_video_hosting_info(getVideoHostingInfo())
    video_info.set_video_id(videoUrl)
    addon_url = 'plugin://plugin.video.iplayer/?'
    video_params = videoUrl.split('/')
    
    addon_url += 'pid=%s' % video_params[0]
    video_info.add_video_link(VIDEO_QUAL_SD, addon_url, addUserAgent=False, addReferer=False)
    video_info.set_video_image('http://www.bbc.co.uk/iplayer/images/episode/%s_512_288.jpg' % video_params[0])
    video_info.set_video_name(video_params[1].replace('_', ' '))
    
    Logger.logDebug(addon_url)
    video_info.set_video_stopped(False)
    return video_info
示例#28
0
def retrieveTVShowsAndSave(request_obj, response_obj):
    oldfilepath = AddonUtils.getCompleteFilePath(baseDirPath=Container().getAddonContext().addonProfile, extraDirPath=AddonUtils.ADDON_SRC_DATA_FOLDER, filename=OLD_CHANNELS_JSON_FILE, makeDirs=True)
    AddonUtils.deleteFile(oldfilepath)
    
    filepath = AddonUtils.getCompleteFilePath(baseDirPath=Container().getAddonContext().addonProfile, extraDirPath=AddonUtils.ADDON_SRC_DATA_FOLDER, filename=CHANNELS_JSON_FILE, makeDirs=True)
    refresh = Container().getAddonContext().addon.getSetting('dtForceRefresh')
    if refresh == None or refresh != 'true':
        lastModifiedTime = AddonUtils.getFileLastModifiedTime(filepath)
        if lastModifiedTime is not None:
            diff = long((time.time() - lastModifiedTime) / 3600)
            if diff < 720:
                return
            else:
                Logger.logDebug(CHANNELS_JSON_FILE + ' was last created 30 days ago, refreshing data.')
    else:
        Logger.logDebug(CHANNELS_JSON_FILE + ' request to forcely refresh data. ')
    
    tvChannels = {}
    __retrieveChannels__(tvChannels, BASE_WSITE_URL + '/', CHANNEL_TYPE_IND)
    __retrieveChannels__(tvChannels, BASE_WSITE_URL + '/pakistan-tv/', CHANNEL_TYPE_PAK)
    # save tvChannels in moving data
    request_obj.get_data()['tvChannels'] = tvChannels
    
    status = AddonUtils.saveObjToJsonFile(filepath, tvChannels)
    if status is not None:
        Logger.logDebug('Saved status = ' + str(status))
    Container().getAddonContext().addon.setSetting('dtForceRefresh', 'false')
示例#29
0
def __preparePlayListItem__(video_items, source):
    video_playlist_items = []
    video_source_img = None
    video_source_name = None
    for item in video_items:
        video_item = {}
        video_item['videoLink'] = item.get_request_data()['videoLink']
        video_item['videoTitle'] = item.get_request_data()['videoTitle']
        video_playlist_items.append(video_item)
        video_source_img = item.get_moving_data()['videoSourceImg']
        video_source_name = item.get_moving_data()['videoSourceName']
    Logger.logDebug('IMAGE :: ')
    Logger.logDebug(video_source_img)
    Logger.logDebug(type(video_source_img))
    item = ListItem()
    item.add_request_data('videoPlayListItems', video_playlist_items)
    item.add_moving_data('isContinuousPlayItem', True)
    item.add_moving_data('videoSourceName', video_source_name)
    item.set_next_action_name('Play_AllStreams')
    xbmcListItem = xbmcgui.ListItem(
        label='[COLOR blue]' + AddonUtils.getBoldString('Continuous Play') +
        '[/COLOR]' + ' | ' + 'Source #' + source + ' | ' + 'Parts = ' +
        str(len(video_playlist_items)),
        iconImage=video_source_img,
        thumbnailImage=video_source_img)
    item.set_xbmc_list_item_obj(xbmcListItem)
    return item
示例#30
0
def retrieveVideoInfo(video_id):
    
    video_info = VideoInfo()
    video_info.set_video_hosting_info(getVideoHostingInfo())
    video_info.set_video_id(video_id)
    try:
        video_info_link = 'http://embed.tune.pk/play/' + str(video_id) + '?autoplay=no'
        html = HttpUtils.HttpClient().getHtmlContent(url=video_info_link)
        image = re.compile("preview_img = '(.+?)';").findall(html)
        if image is not None and len(image) == 1:
            video_info.set_video_image(str(image[0]))
        html = html.replace('\n\r', '').replace('\r', '').replace('\n', '')
        sources = re.compile("{(.+?)}").findall(re.compile("sources:(.+?)]").findall(html)[0])
        for source in sources:
            video_link = str(re.compile('file[: ]*"(.+?)"').findall(source)[0])
            Logger.logDebug(video_link)
            label_text = re.compile('label[: ]*"(.+?)"').findall(source)
            if label_text is not None and len(label_text) == 1:
                label = str(label_text[0])
                Logger.logDebug(label)
                if label == '240p':
                    video_info.add_video_link(VIDEO_QUAL_LOW, video_link)
                elif label == '360p' and video_info.get_video_link(VIDEO_QUAL_SD) is None:
                    video_info.add_video_link(VIDEO_QUAL_SD, video_link)
                elif label == '480p' or label == 'SD':
                    video_info.add_video_link(VIDEO_QUAL_SD, video_link)
                elif label == '720p' or label == 'HD':
                    video_info.add_video_link(VIDEO_QUAL_HD_720, video_link)
                elif label == '1080p':
                    video_info.add_video_link(VIDEO_QUAL_HD_1080, video_link)
                else:
                    video_info.add_video_link(VIDEO_QUAL_SD, video_link)
                    
            else:
                video_info.add_video_link(VIDEO_QUAL_SD, video_link)
        video_info.set_video_stopped(False)
        
    except Exception, e:
        Logger.logError(e)
        video_info.set_video_stopped(True)
示例#31
0
def __prepareVideoLink__(item):
    video_url = item.get_moving_data()['videoUrl']
    html = HttpClient().getHtmlContent(video_url)
    video_id = re.compile('http://www.youtube.com/embed/(.+?)\'').findall(html)[0]
    new_video_url = None
    if re.search('dailymotion', video_url, flags=re.I):
        new_video_url = 'http://www.dailymotion.com/video/' + video_id + '_'
    elif re.search('zshare', video_url, flags=re.I):
        new_video_url = 'http://www.zshare.net/video/' + video_id + '&'
    elif re.search('youtube', video_url, flags=re.I):
        new_video_url = 'http://www.youtube.com/watch?v=' + video_id + '&'
    elif re.search('novamov', video_url, flags=re.I):
        new_video_url = 'http://www.novamov.com/embed.php?v=' + video_id + '&'
    elif re.search('videoweed', video_url, flags=re.I):
        new_video_url = 'http://www.videoweed.es/embed.php?v=' + video_id + '&'
    elif re.search('pw', video_url, flags=re.I):
        new_video_url = 'http://cdn.playwire.com/12272/embed/' + video_id + '.xml'
        
    Logger.logDebug("NEW VIDEO URL = " + new_video_url)
        
    if new_video_url is not None:
        item.add_moving_data('videoUrl', new_video_url)
示例#32
0
def retieveTrailerStream(request_obj, response_obj):
    soup = None
    title = request_obj.get_data()['movieTitle']
    if request_obj.get_data().has_key('movieInfo'):
        soup = BeautifulSoup.BeautifulSoup(request_obj.get_data()['movieInfo'])
    elif request_obj.get_data().has_key('moviePageUrl'):
        contentDiv = BeautifulSoup.SoupStrainer('div', {'dir':'ltr'})
        soup = HttpUtils.HttpClient().getBeautifulSoup(url=request_obj.get_data()['moviePageUrl'], parseOnlyThese=contentDiv)
    if soup is None:
        return
    videoLink = None
    Logger.logDebug(soup.prettify())
    frameTag = soup.findChild('iframe', recursive=True)
    if frameTag is not None:
        videoLink = frameTag['src']
    else:
        paramTag = soup.findChild('param', attrs={'name':'movie'}, recursive=True)
        if paramTag is not None:
            videoLink = paramTag['value']
        else:
            videoLink = soup.findChild('embed', recursive=True)['src']
    request_obj.set_data({'videoLink': videoLink, 'videoTitle':title})
示例#33
0
def __retrieveChannels__(tvChannels, dtUrl, channelType):
    contentDiv = BeautifulSoup.SoupStrainer('div', {'class':re.compile(r'\bhentry\b')})
    soup = HttpClient().getBeautifulSoup(url=dtUrl, parseOnlyThese=contentDiv)
    for tvChannelTag in soup.div.findAll('div', recursive=False):
        try:
            tvChannel = {}
            running_tvshows = []
            finished_tvshows = []
            tmp_tvshows_list = None
            firstRow = False
            for tag in tvChannelTag.findAll(re.compile('div|a'), recursive=False):
                if tag.name == 'div' and tag.get('class') == 'nav_up':
                    continue
                if not firstRow:
                    channelImg = ''
                    if(tag.find('img').has_key('src')):
                        channelImg = str(tag.find('img')['src'])
                    else:
                        channelImg = str(tag.find('img')['file'])
                    channelName = re.compile(BASE_WSITE_URL + '/category/(tv-serials|pakistan-tvs)/(.+?)/').findall(str(tag.find('a')['href']))[0][1]
                    channelName = string.upper(channelName.replace('-', ' '))
                    Logger.logDebug(channelName)
                    tvChannels[channelName] = tvChannel
                    tvChannel['iconimage'] = channelImg
                    tvChannel['channelType'] = channelType
                    firstRow = True
                else:
                    if tag.name == 'div' and tag.get('class') == 'dtLink':
                        txt = tag.getText()
                        Logger.logDebug(txt)
                        if re.search('running', txt, flags=re.IGNORECASE):
                            tmp_tvshows_list = running_tvshows
                            tvChannel['running_tvshows'] = running_tvshows
                        elif re.search('finished', txt, flags=re.IGNORECASE):
                            tmp_tvshows_list = finished_tvshows
                            tvChannel['finished_tvshows'] = finished_tvshows
                        else:
                            Logger.logWarning('UNKNOWN TV SHOW CATEGORY')
                    elif tag.name == 'a':
                        tvshowUrl = str(tag['href'])
                        tvshowName = tag.getText().encode('utf-8')
                        Logger.logDebug(tvshowName)
                        tmp_tvshows_list.append({'name':HttpUtils.unescape(tvshowName), 'url':tvshowUrl})
        except Exception, e:
            Logger.logFatal(e)
            Logger.logDebug(tvChannelTag)
示例#34
0
    def GA(self, group, name):
        try:
            from random import randint
            from urllib import quote
            VISITOR = self.addon_context.addon.getSetting('ga_visitor')
            utm_gif_location = "http://www.google-analytics.com/__utm.gif"
            if not group == "None":
                utm_track = utm_gif_location + "?" + \
                        "utmwv=" + self.addon_version + \
                        "&utmn=" + str(randint(0, 0x7fffffff)) + \
                        "&utmt=" + "event" + \
                        "&utme=" + quote("5(" + self.addon_name + "*" + group + "*" + name + ")") + \
                        "&utmp=" + quote(self.addon_name) + \
                        "&utmac=" + self.ua_track + \
                        "&utmcc=__utma=%s" % ".".join(["1", VISITOR, VISITOR, VISITOR, VISITOR, "2"])
                try:
                    Logger.logDebug(
                        "============================ POSTING TRACK EVENT ============================"
                    )
                    self.__send_request_to_google_analytics(utm_track)
                except Exception, e:
                    Logger.logError(e)
                    Logger.logDebug(
                        "============================  CANNOT POST TRACK EVENT ============================"
                    )
            if name == "None":
                utm_url = utm_gif_location + "?" + \
                        "utmwv=" + self.addon_version + \
                        "&utmn=" + str(randint(0, 0x7fffffff)) + \
                        "&utmp=" + quote(self.addon_name) + \
                        "&utmac=" + self.ua_track + \
                        "&utmcc=__utma=%s" % ".".join(["1", VISITOR, VISITOR, VISITOR, VISITOR, "2"])
            else:
                if group == "None":
                    utm_url = utm_gif_location + "?" + \
                            "utmwv=" + self.addon_version + \
                            "&utmn=" + str(randint(0, 0x7fffffff)) + \
                            "&utmp=" + quote(self.addon_name + "/" + name) + \
                            "&utmac=" + self.ua_track + \
                            "&utmcc=__utma=%s" % ".".join(["1", VISITOR, VISITOR, VISITOR, VISITOR, "2"])
                else:
                    utm_url = utm_gif_location + "?" + \
                            "utmwv=" + self.addon_version + \
                            "&utmn=" + str(randint(0, 0x7fffffff)) + \
                            "&utmp=" + quote(self.addon_name + "/" + group + "/" + name) + \
                            "&utmac=" + self.ua_track + \
                            "&utmcc=__utma=%s" % ".".join(["1", VISITOR, VISITOR, VISITOR, VISITOR, "2"])

            Logger.logDebug(
                "============================ POSTING ANALYTICS ============================"
            )
            self.__send_request_to_google_analytics(utm_url)
示例#35
0
def retieveMovieStreams(request_obj, response_obj):
    if(request_obj.get_data().has_key('videoInfo')):
        title = request_obj.get_data()['videoInfo']['title']
        Container().ga_client.reportContentUsage('movie', title)
    soup = None
    if request_obj.get_data().has_key('movieInfo'):
        soup = BeautifulSoup.BeautifulSoup(request_obj.get_data()['movieInfo'])
    elif request_obj.get_data().has_key('moviePageUrl'):
        soup = HttpUtils.HttpClient().getBeautifulSoup(url=request_obj.get_data()['moviePageUrl'])
    if soup is None:
        return
    videoSources = []
    videoSourceLinks = None
    tags = soup.findAll('p')
    if len(tags) < 5:
        tags.extend(soup.findAll('span'))
    Logger.logDebug(soup.prettify())
    Logger.logDebug('   -------------------------------------------------------       ')
    for tag in tags:
        Logger.logDebug(tag)
        if re.search('^(Source|ONLINE|Server)', tag.getText(), re.IGNORECASE):
            if videoSourceLinks is not None and len(videoSourceLinks) > 0:
                videoSources.append(videoSourceLinks)
            videoSourceLinks = []
        else:
            aTags = tag.findAll('a', attrs={'href':re.compile('(desiflicks.com|desionlinetheater.com|wp.me|cine.sominaltvfilms.com)')}, recursive=True)
            if aTags is None or len(aTags) != 1:
                continue
            aTag = aTags[0]
            if aTag is not None:
                infoLink = str(aTag['href']).replace('http://adf.ly/377117/', '')
                if videoSourceLinks == None:
                    videoSourceLinks = []
                if infoLink not in videoSourceLinks:
                    videoSourceLinks.append(infoLink)
    if videoSourceLinks is not None and len(videoSourceLinks) > 0:
        videoSources.append(videoSourceLinks)
    new_items = []
    sourceCount = 0
    for videoSource in videoSources:
        sourceCount = sourceCount + 1
        new_items.extend(__prepareVideoSourceLinks__(videoSource, str(sourceCount)))
    
    if(request_obj.get_data().has_key('videoInfo')):
        __addVideoInfo__(new_items, request_obj.get_data()['videoInfo'])
    response_obj.set_item_list(new_items)
    
    playNowItem = __findPlayNowStream__(response_obj.get_item_list())
    if playNowItem is not None:
        request_obj.set_data({'videoPlayListItems': playNowItem.get_request_data()['videoPlayListItems']})
示例#36
0
 def GA(self, group, name):
         try:
             from random import randint
             from urllib import  quote
             VISITOR = self.addon_context.addon.getSetting('ga_visitor')
             utm_gif_location = "http://www.google-analytics.com/__utm.gif"
             if not group == "None":
                     utm_track = utm_gif_location + "?" + \
                             "utmwv=" + self.addon_version + \
                             "&utmn=" + str(randint(0, 0x7fffffff)) + \
                             "&utmt=" + "event" + \
                             "&utme=" + quote("5(" + self.addon_name + "*" + group + "*" + name + ")") + \
                             "&utmp=" + quote(self.addon_name) + \
                             "&utmac=" + self.ua_track + \
                             "&utmcc=__utma=%s" % ".".join(["1", VISITOR, VISITOR, VISITOR, VISITOR, "2"])
                     try:
                         Logger.logDebug("============================ POSTING TRACK EVENT ============================")
                         self.__send_request_to_google_analytics(utm_track)
                     except Exception, e:
                         Logger.logError(e)
                         Logger.logDebug("============================  CANNOT POST TRACK EVENT ============================")
             if name == "None":
                     utm_url = utm_gif_location + "?" + \
                             "utmwv=" + self.addon_version + \
                             "&utmn=" + str(randint(0, 0x7fffffff)) + \
                             "&utmp=" + quote(self.addon_name) + \
                             "&utmac=" + self.ua_track + \
                             "&utmcc=__utma=%s" % ".".join(["1", VISITOR, VISITOR, VISITOR, VISITOR, "2"])
             else:
                 if group == "None":
                     utm_url = utm_gif_location + "?" + \
                             "utmwv=" + self.addon_version + \
                             "&utmn=" + str(randint(0, 0x7fffffff)) + \
                             "&utmp=" + quote(self.addon_name + "/" + name) + \
                             "&utmac=" + self.ua_track + \
                             "&utmcc=__utma=%s" % ".".join(["1", VISITOR, VISITOR, VISITOR, VISITOR, "2"])
                 else:
                     utm_url = utm_gif_location + "?" + \
                             "utmwv=" + self.addon_version + \
                             "&utmn=" + str(randint(0, 0x7fffffff)) + \
                             "&utmp=" + quote(self.addon_name + "/" + group + "/" + name) + \
                             "&utmac=" + self.ua_track + \
                             "&utmcc=__utma=%s" % ".".join(["1", VISITOR, VISITOR, VISITOR, VISITOR, "2"])
                             
             Logger.logDebug("============================ POSTING ANALYTICS ============================")
             self.__send_request_to_google_analytics(utm_url)
示例#37
0
def __preparePlayListItem__(video_items, source):
    video_playlist_items = []
    video_source_img = None
    video_source_name = None
    for item in video_items:
        video_item = {}
        video_item['videoLink'] = item.get_request_data()['videoLink']
        video_item['videoTitle'] = item.get_request_data()['videoTitle']
        video_playlist_items.append(video_item)
        video_source_img = item.get_moving_data()['videoSourceImg']
        video_source_name = item.get_moving_data()['videoSourceName']
    Logger.logDebug('IMAGE :: ')
    Logger.logDebug(video_source_img)
    Logger.logDebug(type(video_source_img))
    item = ListItem()
    item.add_request_data('videoPlayListItems', video_playlist_items)
    item.add_moving_data('isContinuousPlayItem', True)
    item.add_moving_data('videoSourceName', video_source_name)
    item.set_next_action_name('Play_AllStreams')
    xbmcListItem = xbmcgui.ListItem(label='[COLOR blue]' + AddonUtils.getBoldString('Continuous Play') + '[/COLOR]' + ' | ' + 'Source #' + source + ' | ' + 'Parts = ' + str(len(video_playlist_items)) , iconImage=video_source_img, thumbnailImage=video_source_img)
    item.set_xbmc_list_item_obj(xbmcListItem)
    return item
示例#38
0
                formatQual = re.compile("itag=([^&]+)").findall(formatContent)[0]
                if not re.search("signature=", formatUrl):
                    sig = re.compile("sig=([^&]+)").findall(formatContent)
                    if sig is not None and len(sig) == 1:
                        formatUrl += "&signature=" + sig[0]
                    else:
                        sig = re.compile("s=([^&]+)").findall(formatContent)
                        if sig is not None and len(sig) == 1:
                            formatUrl += "&signature=" + parseSignature(sig[0])
        
            qual = formatQual
            url = HttpUtils.HttpClient().addHttpCookiesToUrl(formatUrl, addHeaders=False,addCookies=False, extraExtraHeaders={'Referer':'https://www.youtube.com/watch?v=' + video_id})
            streams[int(qual)] = url
            
        
        Logger.logDebug(streams)
        for qual in STREAMS_QUAL_MAP:
            for key in STREAMS_QUAL_MAP[qual]:
                if streams.has_key(key):
                    url = streams[key]
                    video_info.add_video_link(qual, url)
                    break
        video_info.set_video_stopped(False)
        
    except Exception, e:
        Logger.logError(e)
        video_info.set_video_stopped(True)
    return video_info


def swap(a , b):
示例#39
0
def __prepareVideoLink__(videoSourceLink):
    new_items = []
    url = videoSourceLink
    if re.search('wp.me', url, re.I):
        url = HttpUtils.getRedirectedUrl(url)
    if not url.startswith('http://'):
        url = 'http://' + url
    Logger.logDebug(url)
#     contentDiv = BeautifulSoup.SoupStrainer('div', {'class':'left_articles'})
#     soup = BeautifulSoup.BeautifulSoup(html, contentDiv)
    html = HttpUtils.HttpClient().getHtmlContent(url)
    dek = EnkDekoder.dekode(html)
    Logger.logDebug(dek)
    if dek is not None:
        html = dek
        
    html = html.replace('\n\r', '').replace('\r', '').replace('\n', '').replace('\\', '')
    children = []
    if re.search('http://videos.stvflicks.com/', html):
        docId = re.compile('http://videos.stvflicks.com/(.+?).mp4"').findall(html)[0]
        children.append('src="http://videos.stvflicks.com/' + docId + '.mp4"')
    elif re.search('http://playcineflix.com/', html):
        docId = re.compile('http://playcineflix.com/(.+?).mp4"').findall(html)[0]
        children.append('src="http://playcineflix.com/' + docId + '.mp4"')
    elif re.search('https://video.google.com/get_player', html):
        docId = re.compile('docid=(.+?)"').findall(html)[0]
        children.append('src="https://docs.google.com/file/d/' + docId + '/preview"')
    elif re.search('http://videos.videopress.com/', html):
        docId = re.compile('type="video/mp4" href="http://videos.videopress.com/(.+?).mp4"').findall(html)[0]
        children.append('src="http://videos.videopress.com/' + docId + '.mp4"')
    else:
        children = re.compile('<embed(.+?)>').findall(html)
        if children is None or len(children) == 0:
            children = re.compile('<iframe(.+?)>').findall(html)
    
            
    Logger.logDebug(children)
    for child in children:
        video_url = re.compile('src="(.+?)"').findall(child)[0]
        if(re.search('http://ads', video_url, re.I) or re.search('http://ax-d', video_url, re.I)):
            continue
        if video_url.startswith('http://goo.gl/'):
            Logger.logDebug('Found google short URL = ' + video_url)
            video_url = HttpUtils.getRedirectedUrl(video_url)
            Logger.logDebug('After finding out redirected URL = ' + video_url)
            if re.search('videos.desionlinetheater.com', video_url):
                XBMCInterfaceUtils.displayDialogMessage('Unable to parse', 'A new HTML Guardian is used to protect the page', 'Sounds technical!! hmm, it means cannot find video.', 'Fix: Find me JavaScript Interpreter online service')
        video_hosting_info = SnapVideo.findVideoHostingInfo(video_url)
        if video_hosting_info is None:
            Logger.logDebug('Unrecognized video_url = ' + video_url)
            continue
        video_source_img = video_hosting_info.get_video_hosting_image()
        
        new_item = ListItem()
        new_item.add_request_data('videoTitle', 'Part #')
        new_item.add_request_data('videoLink', video_url)
        new_item.add_moving_data('videoSourceImg', video_source_img)
        new_item.add_moving_data('videoSourceName', video_hosting_info.get_video_hosting_name())
        new_item.set_next_action_name('Play_Stream')
        xbmcListItem = xbmcgui.ListItem(label='Part #', iconImage=video_source_img, thumbnailImage=video_source_img)
        new_item.set_xbmc_list_item_obj(xbmcListItem)
        new_items.append(new_item)
    
    return new_items
示例#40
0
def __prepareVideoLink__(videoSourceLink):
    new_items = []
    url = videoSourceLink
    if re.search('wp.me', url, re.I):
        url = HttpUtils.getRedirectedUrl(url)
    if not url.startswith('http://'):
        url = 'http://' + url
    Logger.logDebug(url)
    #     contentDiv = BeautifulSoup.SoupStrainer('div', {'class':'left_articles'})
    #     soup = BeautifulSoup.BeautifulSoup(html, contentDiv)

    if re.search('', videoSourceLink):
        video_hosting_info = SnapVideo.findVideoHostingInfo(videoSourceLink)
        if video_hosting_info is None:
            Logger.logDebug('Unrecognized video_url = ' + videoSourceLink)
        else:
            video_source_img = video_hosting_info.get_video_hosting_image()

            new_item = ListItem()
            new_item.add_request_data('videoTitle', 'Part #')
            new_item.add_request_data('videoLink', videoSourceLink)
            new_item.add_moving_data('videoSourceImg', video_source_img)
            new_item.add_moving_data(
                'videoSourceName', video_hosting_info.get_video_hosting_name())
            new_item.set_next_action_name('Play_Stream')
            xbmcListItem = xbmcgui.ListItem(label='Part #',
                                            iconImage=video_source_img,
                                            thumbnailImage=video_source_img)
            new_item.set_xbmc_list_item_obj(xbmcListItem)
            new_items.append(new_item)
            return new_items

    html = HttpUtils.HttpClient().getHtmlContent(url)
    dek = EnkDekoder.dekode(html)
    Logger.logDebug(dek)
    if dek is not None:
        html = dek

    html = html.replace('\n\r', '').replace('\r',
                                            '').replace('\n',
                                                        '').replace('\\', '')
    children = []
    if re.search('http://videos.stvflicks.com/', html):
        docId = re.compile('http://videos.stvflicks.com/(.+?).mp4"').findall(
            html)[0]
        children.append('src="http://videos.stvflicks.com/' + docId + '.mp4"')
    elif re.search('http://playcineflix.com/', html):
        docId = re.compile('http://playcineflix.com/(.+?).mp4"').findall(
            html)[0]
        children.append('src="http://playcineflix.com/' + docId + '.mp4"')
    elif re.search('https://video.google.com/get_player', html):
        docId = re.compile('docid=(.+?)"').findall(html)[0]
        children.append('src="https://docs.google.com/file/d/' + docId +
                        '/preview"')
    elif re.search('http://videos.videopress.com/', html):
        docId = re.compile(
            'type="video/mp4" href="http://videos.videopress.com/(.+?).mp4"'
        ).findall(html)[0]
        children.append('src="http://videos.videopress.com/' + docId + '.mp4"')
    elif re.search('http://videos.videopress.com/', html):
        docId = re.compile(
            'type="video/mp4" href="http://videos.videopress.com/(.+?).mp4"'
        ).findall(html)[0]
        children.append('src="http://videos.videopress.com/' + docId + '.mp4"')
    elif re.search('video_alt_url=http://www.mediaplaybox.com', html):
        docId = re.compile('video_alt_url=http://www.mediaplaybox.com(.+?).mp4'
                           ).findall(html)[0]
        children.append('src="http://www.mediaplaybox.com:81/' + docId +
                        '.mp4"')
    elif re.search('video_url=http://www.mediaplaybox.com', html):
        docId = re.compile(
            'video_url=http://www.mediaplaybox.com(.+?).mp4').findall(html)[0]
        children.append('src="http://www.mediaplaybox.com:81/' + docId +
                        '.mp4"')
    else:
        children = re.compile('<embed(.+?)>').findall(html)
        if children is None or len(children) == 0:
            children = re.compile('<iframe(.+?)>').findall(html)

    Logger.logDebug(children)
    for child in children:
        video_url = re.compile('src="(.+?)"').findall(child)[0]
        if (re.search('http://ads', video_url, re.I)
                or re.search('http://ax-d', video_url, re.I)):
            continue
        if video_url.startswith('http://goo.gl/'):
            Logger.logDebug('Found google short URL = ' + video_url)
            video_url = HttpUtils.getRedirectedUrl(video_url)
            Logger.logDebug('After finding out redirected URL = ' + video_url)
            if re.search('videos.desionlinetheater.com', video_url):
                XBMCInterfaceUtils.displayDialogMessage(
                    'Unable to parse',
                    'A new HTML Guardian is used to protect the page',
                    'Sounds technical!! hmm, it means cannot find video.',
                    'Fix: Find me JavaScript Interpreter online service')
        video_hosting_info = SnapVideo.findVideoHostingInfo(video_url)
        if video_hosting_info is None:
            Logger.logDebug('Unrecognized video_url = ' + video_url)
            continue
        video_source_img = video_hosting_info.get_video_hosting_image()

        new_item = ListItem()
        new_item.add_request_data('videoTitle', 'Part #')
        new_item.add_request_data('videoLink', video_url)
        new_item.add_moving_data('videoSourceImg', video_source_img)
        new_item.add_moving_data('videoSourceName',
                                 video_hosting_info.get_video_hosting_name())
        new_item.set_next_action_name('Play_Stream')
        xbmcListItem = xbmcgui.ListItem(label='Part #',
                                        iconImage=video_source_img,
                                        thumbnailImage=video_source_img)
        new_item.set_xbmc_list_item_obj(xbmcListItem)
        new_items.append(new_item)

    return new_items
示例#41
0
                else:
                    utm_url = utm_gif_location + "?" + \
                            "utmwv=" + self.addon_version + \
                            "&utmn=" + str(randint(0, 0x7fffffff)) + \
                            "&utmp=" + quote(self.addon_name + "/" + group + "/" + name) + \
                            "&utmac=" + self.ua_track + \
                            "&utmcc=__utma=%s" % ".".join(["1", VISITOR, VISITOR, VISITOR, VISITOR, "2"])

            Logger.logDebug(
                "============================ POSTING ANALYTICS ============================"
            )
            self.__send_request_to_google_analytics(utm_url)

        except Exception, e:
            Logger.logError(e)
            Logger.logDebug(
                "================  CANNOT POST TO ANALYTICS  ================")

    def APP_LAUNCH(self):
        versionNumber = int(xbmc.getInfoLabel("System.BuildVersion")[0:2])
        '''
            if versionNumber < 12:
                if xbmc.getCondVisibility('system.platform.osx'):
                    if xbmc.getCondVisibility('system.platform.atv2'):
                        log_path = '/var/mobile/Library/Preferences'
                    else:
                        log_path = os.path.join(os.path.expanduser('~'), 'Library/Logs')
                elif xbmc.getCondVisibility('system.platform.ios'):
                    log_path = '/var/mobile/Library/Preferences'
                elif xbmc.getCondVisibility('system.platform.windows'):
                    log_path = xbmc.translatePath('special://home')
                elif xbmc.getCondVisibility('system.platform.linux'):
示例#42
0
def retieveMovieStreams(request_obj, response_obj):
    if (request_obj.get_data().has_key('videoInfo')):
        title = request_obj.get_data()['videoInfo']['title']
        Container().ga_client.reportContentUsage('movie', title)
    soup = None
    if request_obj.get_data().has_key('movieInfo'):
        soup = BeautifulSoup.BeautifulSoup(request_obj.get_data()['movieInfo'])
    elif request_obj.get_data().has_key('moviePageUrl'):
        soup = HttpUtils.HttpClient().getBeautifulSoup(
            url=request_obj.get_data()['moviePageUrl'])
    if soup is None:
        return
    videoSources = []
    videoSourceLinks = None
    tags = soup.findAll('p')
    if len(tags) < 5:
        tags.extend(soup.findAll('span'))
    Logger.logDebug(soup.prettify())
    Logger.logDebug(
        '   -------------------------------------------------------       ')
    for tag in tags:
        Logger.logDebug(tag)
        if re.search('^(Source|ONLINE|Server)', tag.getText(), re.IGNORECASE):
            if videoSourceLinks is not None and len(videoSourceLinks) > 0:
                videoSources.append(videoSourceLinks)
            videoSourceLinks = []
        else:
            aTags = tag.findAll(
                'a',
                attrs={
                    'href':
                    re.compile(
                        '(desiflicks.com|desionlinetheater.com|wp.me|cine.sominaltvfilms.com|media.thesominaltv.com|mediaplaybox.com)'
                    )
                },
                recursive=True)
            if aTags is None or len(aTags) != 1:
                continue
            aTag = aTags[0]
            if aTag is not None:
                infoLink = str(aTag['href']).replace('http://adf.ly/377117/',
                                                     '')
                if videoSourceLinks == None:
                    videoSourceLinks = []
                if infoLink not in videoSourceLinks:
                    videoSourceLinks.append(infoLink)
    if videoSourceLinks is not None and len(videoSourceLinks) > 0:
        videoSources.append(videoSourceLinks)
    new_items = []
    sourceCount = 0
    for videoSource in videoSources:
        sourceCount = sourceCount + 1
        new_items.extend(
            __prepareVideoSourceLinks__(videoSource, str(sourceCount)))

    if (request_obj.get_data().has_key('videoInfo')):
        __addVideoInfo__(new_items, request_obj.get_data()['videoInfo'])
    response_obj.set_item_list(new_items)

    playNowItem = __findPlayNowStream__(response_obj.get_item_list())
    if playNowItem is not None:
        request_obj.set_data({
            'videoPlayListItems':
            playNowItem.get_request_data()['videoPlayListItems']
        })
示例#43
0
def playHostedVideo(request_obj, response_obj):
    pbType = int(Container().getAddonContext().addon.getSetting('playbacktype'))
    
    Container().getAddonContext().addon.setSetting('ga_video_title', 'false')
    
    if pbType == 2 and XBMCInterfaceUtils.isPlaying():
        response_obj.addServiceResponseParam("status", "error")
        response_obj.addServiceResponseParam("title", "XBMC is already playing.")
        response_obj.addServiceResponseParam("message", "Check PlayIt Service add-on settings. Your this request is ignored.")
        item = ListItem()
        item.set_next_action_name('respond')
        response_obj.addListItem(item)
    else:
        if pbType == 0:
            XBMCInterfaceUtils.stopPlayer()
            
        video_url = request_obj.get_data()['videoLink']
        if video_url.startswith('http://goo.gl/'):
            Logger.logDebug('Found google short URL = ' + video_url)
            video_url = HttpUtils.getRedirectedUrl(video_url)
            Logger.logDebug('After finding out redirected URL = ' + video_url)
            request_obj.get_data()['videoLink'] = video_url
        if __is_valid_url(video_url):
            contentType = __check_media_url(video_url)
            if contentType is not None:
                if contentType == 'audio':
                    response_obj.set_redirect_action_name('play_direct_audio')
                    request_obj.get_data()['track_title'] = ''
                    request_obj.get_data()['track_link'] = video_url
                    request_obj.get_data()['track_artwork_url'] = ''
                else:
                    response_obj.set_redirect_action_name('play_direct_video')
            else:
                if XBMCInterfaceUtils.isPlayingAudio():
                    response_obj.addServiceResponseParam("status", "error")
                    response_obj.addServiceResponseParam("title", "Stop active music!")
                    response_obj.addServiceResponseParam("message", "Note: XBMC cannot play video when audio playback is in progress.")
                    item = ListItem()
                    item.set_next_action_name('respond')
                    response_obj.addListItem(item)
                else:
                    video_hosting_info = SnapVideo.findVideoHostingInfo(video_url)
                    if video_hosting_info is None:
                        response_obj.addServiceResponseParam("status", "error")
                        response_obj.addServiceResponseParam("title", "URL not supported")
                        response_obj.addServiceResponseParam("message", "Video URL is currently not supported by PlayIt. Please check if URL selected is correct.")
                        item = ListItem()
                        item.set_next_action_name('respond')
                        response_obj.addListItem(item)
                    else:
                        Container().ga_client.reportContentUsage('hostedvideo', video_hosting_info.get_video_hosting_name())
                        response_obj.addServiceResponseParam("status", "success")
                        if not XBMCInterfaceUtils.isPlaying():
                            XBMCInterfaceUtils.clearPlayList(list_type="video")
                            response_obj.addServiceResponseParam("message", "Enjoy your video!")
                        else:
                            response_obj.addServiceResponseParam("title", "Request Enqueued!")
                            response_obj.addServiceResponseParam("message", "Your request has been added to player queue.")
                        response_obj.set_redirect_action_name('play_it')
                        request_obj.get_data()['videoTitle'] = 'PlayIt Video'
        else:
            Logger.logError('video_url = ' + str(video_url))
            response_obj.addServiceResponseParam("status", "error")
            response_obj.addServiceResponseParam("title", "Invalid URL")
            response_obj.addServiceResponseParam("message", "Video URL is not valid one! Please check and try again.")
            item = ListItem()
            item.set_next_action_name('respond')
            response_obj.addListItem(item)
示例#44
0
    def APP_LAUNCH(self):
        versionNumber = int(xbmc.getInfoLabel("System.BuildVersion")[0:2])
        if versionNumber < 12:
            if xbmc.getCondVisibility("system.platform.osx"):
                if xbmc.getCondVisibility("system.platform.atv2"):
                    log_path = "/var/mobile/Library/Preferences"
                else:
                    log_path = os.path.join(os.path.expanduser("~"), "Library/Logs")
            elif xbmc.getCondVisibility("system.platform.ios"):
                log_path = "/var/mobile/Library/Preferences"
            elif xbmc.getCondVisibility("system.platform.windows"):
                log_path = xbmc.translatePath("special://home")
                log = os.path.join(log_path, "xbmc.log")
                logfile = open(log, "r").read()
            elif xbmc.getCondVisibility("system.platform.linux"):
                log_path = xbmc.translatePath("special://home/temp")
            else:
                log_path = xbmc.translatePath("special://logpath")
            log = os.path.join(log_path, "xbmc.log")
            logfile = open(log, "r").read()
            match = re.compile("Starting XBMC \((.+?) Git:.+?Platform: (.+?)\. Built.+?").findall(logfile)
        elif versionNumber > 11:
            Logger.logDebug("======================= more than ====================")
            log_path = xbmc.translatePath("special://logpath")
            log = os.path.join(log_path, "xbmc.log")
            logfile = open(log, "r").read()
            match = re.compile("Starting XBMC \((.+?) Git:.+?Platform: (.+?)\. Built.+?").findall(logfile)
        else:
            logfile = "Starting XBMC (Unknown Git:.+?Platform: Unknown. Built.+?"
            match = re.compile("Starting XBMC \((.+?) Git:.+?Platform: (.+?)\. Built.+?").findall(logfile)
        Logger.logDebug(
            "==========================   "
            + self.addon_name
            + " "
            + self.addon_version
            + "  =========================="
        )

        from random import randint

        from urllib import quote

        VISITOR = self.addon_context.addon.getSetting("ga_visitor")
        for build, PLATFORM in match:
            if re.search("12", build[0:2], re.IGNORECASE):
                build = "Frodo"
            if re.search("11", build[0:2], re.IGNORECASE):
                build = "Eden"
            if re.search("13", build[0:2], re.IGNORECASE):
                build = "Gotham"
            Logger.logDebug(build)
            Logger.logDebug(PLATFORM)
            utm_gif_location = "http://www.google-analytics.com/__utm.gif"
            utm_track = (
                utm_gif_location
                + "?"
                + "utmwv="
                + self.addon_version
                + "&utmn="
                + str(randint(0, 0x7FFFFFFF))
                + "&utmt="
                + "event"
                + "&utme="
                + quote("5(APP LAUNCH*" + build + "*" + PLATFORM + ")")
                + "&utmp="
                + quote(self.addon_name)
                + "&utmac="
                + self.ua_track
                + "&utmcc=__utma=%s" % ".".join(["1", VISITOR, VISITOR, VISITOR, VISITOR, "2"])
            )
            try:
                Logger.logDebug(
                    "============================ POSTING APP LAUNCH TRACK EVENT ============================"
                )
                self.__send_request_to_google_analytics(utm_track)
            except Exception, e:
                Logger.logError(e)
                Logger.logDebug(
                    "============================  CANNOT POST APP LAUNCH TRACK EVENT ============================"
                )
示例#45
0
def retrieveVideoInfo(video_id):
    
    video_info = VideoInfo()
    video_info.set_video_hosting_info(getVideoHostingInfo())
    video_info.set_video_id(video_id)
    try:
        
        HttpUtils.HttpClient().enableCookies()
        video_info.set_video_image('http://i.ytimg.com/vi/' + video_id + '/default.jpg')
        html = HttpUtils.HttpClient().getHtmlContent(url='http://www.youtube.com/get_video_info?video_id=' + video_id + '&asv=3&el=detailpage&hl=en_US')
        stream_map = None
        
        html = html.decode('utf8')
        html = html.replace('\n', '')
        html = html.replace('\r', '')
        html = unicode(html + '&').encode('utf-8')
        if re.search('status=fail', html):
            # XBMCInterfaceUtils.displayDialogMessage('Video info retrieval failed', 'Reason: ' + ((re.compile('reason\=(.+?)\.').findall(html))[0]).replace('+', ' ') + '.')
            Logger.logInfo('YouTube video is removed for Id = ' + video_id + ' reason = ' + html)
            video_info.set_video_stopped(True)
            return video_info
        
        title = urllib.unquote_plus(re.compile('title=(.+?)&').findall(html)[0]).replace('/\+/g', ' ')
        video_info.set_video_name(title)
        stream_info = None
        if not re.search('url_encoded_fmt_stream_map=&', html):
            stream_info = re.compile('url_encoded_fmt_stream_map=(.+?)&').findall(html)
        stream_map = None
        if (stream_info is None or len(stream_info) == 0) and re.search('fmt_stream_map": "', html):
            stream_map = re.compile('fmt_stream_map": "(.+?)"').findall(html)[0].replace("\\/", "/")
        elif stream_info is not None:
            stream_map = stream_info[0]
            
        if stream_map is None:
            params = HttpUtils.getUrlParams(html)
            Logger.logDebug('ENTERING live video scenario...')
            for key in params:
                Logger.logDebug(key + " : " + urllib.unquote_plus(params[key]))
            hlsvp = urllib.unquote_plus(params['hlsvp'])
            playlistItems = HttpUtils.HttpClient().getHtmlContent(url=hlsvp).splitlines()
            qualityIdentified = None
            for item in playlistItems:
                Logger.logDebug(item)
                if item.startswith('#EXT-X-STREAM-INF'):
                    if item.endswith('1280x720'):
                        qualityIdentified = VIDEO_QUAL_HD_720
                    elif item.endswith('1080'):
                        qualityIdentified = VIDEO_QUAL_HD_1080
                    elif item.endswith('854x480'):
                        qualityIdentified = VIDEO_QUAL_SD
                    elif item.endswith('640x360'):
                        qualityIdentified = VIDEO_QUAL_LOW
                elif item.startswith('http') and qualityIdentified is not None:
                    videoUrl = HttpUtils.HttpClient().addHttpCookiesToUrl(item, extraExtraHeaders={'Referer':'https://www.youtube.com/watch?v=' + video_id})
                    video_info.add_video_link(qualityIdentified, videoUrl)
                    qualityIdentified = None
            video_info.set_video_stopped(False)
            return video_info
        
        stream_map = urllib.unquote_plus(stream_map)
        Logger.logDebug(stream_map)
        formatArray = stream_map.split(',')
        streams = {}
        for formatContent in formatArray:
            if formatContent == '':
                continue
            formatUrl = ''
            try:
                formatUrl = urllib.unquote(re.compile("url=([^&]+)").findall(formatContent)[0]) + "&title=" + urllib.quote_plus(title)   
            except Exception, e:
                Logger.logFatal(e)     
            if re.search("rtmpe", stream_map):
                try:
                    conn = urllib.unquote(re.compile("conn=([^&]+)").findall(formatContent)[0]);
                    host = re.compile("rtmpe:\/\/([^\/]+)").findall(conn)[0];
                    stream = re.compile("stream=([^&]+)").findall(formatContent)[0];
                    path = 'videoplayback';
                    
                    formatUrl = "-r %22rtmpe:\/\/" + host + "\/" + path + "%22 -V -a %22" + path + "%22 -f %22WIN 11,3,300,268%22 -W %22http:\/\/s.ytimg.com\/yt\/swfbin\/watch_as3-vfl7aCF1A.swf%22 -p %22http:\/\/www.youtube.com\/watch?v=" + video_id + "%22 -y %22" + urllib.unquote(stream) + "%22"
                except Exception, e:
                    Logger.logFatal(e)
            if formatUrl == '':
                continue
            Logger.logDebug('************************')
            Logger.logDebug(formatContent)
            formatQual = ''
            if(formatUrl[0: 4] == "http" or formatUrl[0: 2] == "-r"):
                formatQual = re.compile("itag=([^&]+)").findall(formatContent)[0]
                if not re.search("signature=", formatUrl):
                    sig = re.compile("sig=([^&]+)").findall(formatContent)
                    if sig is not None and len(sig) == 1:
                        formatUrl += "&signature=" + sig[0]
                    else:
                        sig = re.compile("s=([^&]+)").findall(formatContent)
                        if sig is not None and len(sig) == 1:
                            formatUrl += "&signature=" + parseSignature(sig[0])
        
            qual = formatQual
            url = HttpUtils.HttpClient().addHttpCookiesToUrl(formatUrl, addHeaders=False,addCookies=False, extraExtraHeaders={'Referer':'https://www.youtube.com/watch?v=' + video_id})
            streams[int(qual)] = url
示例#46
0
    def APP_LAUNCH(self):
        versionNumber = int(xbmc.getInfoLabel("System.BuildVersion")[0:2])
        if versionNumber < 12:
            if xbmc.getCondVisibility('system.platform.osx'):
                if xbmc.getCondVisibility('system.platform.atv2'):
                    log_path = '/var/mobile/Library/Preferences'
                else:
                    log_path = os.path.join(os.path.expanduser('~'),
                                            'Library/Logs')
            elif xbmc.getCondVisibility('system.platform.ios'):
                log_path = '/var/mobile/Library/Preferences'
            elif xbmc.getCondVisibility('system.platform.windows'):
                log_path = xbmc.translatePath('special://home')
                log = os.path.join(log_path, 'xbmc.log')
                logfile = open(log, 'r').read()
            elif xbmc.getCondVisibility('system.platform.linux'):
                log_path = xbmc.translatePath('special://home/temp')
            else:
                log_path = xbmc.translatePath('special://logpath')
            log = os.path.join(log_path, 'xbmc.log')
            logfile = open(log, 'r').read()
            match = re.compile(
                'Starting XBMC \((.+?) Git:.+?Platform: (.+?)\. Built.+?'
            ).findall(logfile)
        elif versionNumber > 11:
            Logger.logDebug(
                '======================= more than ====================')
            log_path = xbmc.translatePath('special://logpath')
            log = os.path.join(log_path, 'xbmc.log')
            logfile = open(log, 'r').read()
            match = re.compile(
                'Starting XBMC \((.+?) Git:.+?Platform: (.+?)\. Built.+?'
            ).findall(logfile)
        else:
            logfile = 'Starting XBMC (Unknown Git:.+?Platform: Unknown. Built.+?'
            match = re.compile(
                'Starting XBMC \((.+?) Git:.+?Platform: (.+?)\. Built.+?'
            ).findall(logfile)
        Logger.logDebug('==========================   ' + self.addon_name +
                        ' ' + self.addon_version +
                        '  ==========================')

        from random import randint

        from urllib import quote
        VISITOR = self.addon_context.addon.getSetting('ga_visitor')
        for build, PLATFORM in match:
            if re.search('12', build[0:2], re.IGNORECASE):
                build = "Frodo"
            if re.search('11', build[0:2], re.IGNORECASE):
                build = "Eden"
            if re.search('13', build[0:2], re.IGNORECASE):
                build = "Gotham"
            Logger.logDebug(build)
            Logger.logDebug(PLATFORM)
            utm_gif_location = "http://www.google-analytics.com/__utm.gif"
            utm_track = utm_gif_location + "?" + \
                    "utmwv=" + self.addon_version + \
                    "&utmn=" + str(randint(0, 0x7fffffff)) + \
                    "&utmt=" + "event" + \
                    "&utme=" + quote("5(APP LAUNCH*" + build + "*" + PLATFORM + ")") + \
                    "&utmp=" + quote(self.addon_name) + \
                    "&utmac=" + self.ua_track + \
                    "&utmcc=__utma=%s" % ".".join(["1", VISITOR, VISITOR, VISITOR, VISITOR, "2"])
            try:
                Logger.logDebug(
                    "============================ POSTING APP LAUNCH TRACK EVENT ============================"
                )
                self.__send_request_to_google_analytics(utm_track)
            except Exception, e:
                Logger.logError(e)
                Logger.logDebug(
                    "============================  CANNOT POST APP LAUNCH TRACK EVENT ============================"
                )