def start(self, uri, mode='loop'):
     self.uri = uri
     self.playMode = mode
     
     gstplayerPath = config.plugins.iptvplayer.gstplayerpath.value
     #'export GST_DEBUG="*:6" &&' + 
     cmd = gstplayerPath  + ' "%s"' % self.uri
     if "://" in self.uri: 
         cmd += ' "%s" "%s"  "%s"  "%s" ' % (self.gstAdditionalParams['download-buffer-path'], self.gstAdditionalParams['ring-buffer-max-size'], self.gstAdditionalParams['buffer-duration'], self.gstAdditionalParams['buffer-size'])
         tmp = strwithmeta(self.uri)
         url,httpParams = DMHelper.getDownloaderParamFromUrl(tmp)
         for key in httpParams: cmd += (' "%s=%s" ' % (key, httpParams[key]) )
         if 'http_proxy' in tmp.meta:
             tmp = tmp.meta['http_proxy']
             if '://' in tmp:
                 if '@' in tmp:
                     tmp = re.search('([^:]+?://)([^:]+?):([^@]+?)@(.+?)$', tmp)
                     if tmp: cmd += (' "proxy=%s" "proxy-id=%s" "proxy-pw=%s" ' % (tmp.group(1)+tmp.group(4), tmp.group(2), tmp.group(3)) )
                 else: cmd += (' "proxy=%s" ' % tmp)
     else:
         cmd = 'exteplayer3 "%s"' % self.uri + " > /dev/null"
     self.console = eConsoleAppContainer()
     self.console_appClosed_conn = eConnectCallback(self.console.appClosed, self._playerFinished)
     printDBG("IPTVSimpleAudioPlayer.start cmd[%s]" % cmd)
     self.console.execute( cmd )
     self.stopped = False
 def startDownloader(self, sts, reason):
     if sts:
         url,downloaderParams = DMHelper.getDownloaderParamFromUrl( self.cover['src'] )
         self.cover['downloader'] .subscribeFor_Finish(self.downloaderEnd)
         self.cover['downloader'] .start(url, self._getDownloadFilePath(), downloaderParams)
         self.showSpinner()
     else: self.session.openWithCallback(self.close, MessageBox, _("Downloading cannot be started.\n Downloader [%s] not working properly.\n Status[%s]") % (self.cover['downloader'].getName(), reason.strip()), type = MessageBox.TYPE_ERROR, timeout = 10 )        
 def _startDownloader(self, sts, reason):
     if sts:
         self.downloader.subscribeFor_Finish(self.downloadFinished)
         url,downloaderParams = DMHelper.getDownloaderParamFromUrl(self.currItem.get('url', ''))
         self.downloader.start(url, GetTmpDir(self._TMP_FILE_NAME), downloaderParams)
     else:
         self["console"].setText(_("Download can not be started.\nDownloader %s not working correctly.\nStatus[%s]"))
 def getResolvedURL(self, url):
     printDBG("LocalMedia.getResolvedURL [%s]" % url)
     videoUrls = []
     
     if url.startswith('/') and fileExists(url):
         url = 'file://'+url
     
     uri, params   = DMHelper.getDownloaderParamFromUrl(url)
     printDBG(params)
     uri = urlparser.decorateUrl(uri, params)
     
     if uri.meta.get('iptv_proto', '') in ['http', 'https']:
         urlSupport = self.up.checkHostSupport( uri )
     else:
         urlSupport = 0
     if 1 == urlSupport:
         retTab = self.up.getVideoLinkExt( uri )
         videoUrls.extend(retTab)
     elif 0 == urlSupport and self._uriIsValid(uri):
         if uri.split('?')[0].endswith('.m3u8'):
             retTab = getDirectM3U8Playlist(uri)
             videoUrls.extend(retTab)
         elif uri.split('?')[0].endswith('.f4m'):
             retTab = getF4MLinksWithMeta(uri)
             videoUrls.extend(retTab)
         else:
             videoUrls.append({'name':'direct link', 'url':uri})
     return videoUrls
示例#5
0
 def _startDownloader(self, sts, reason):
     if sts:
         self.downloader.subscribeFor_Finish(self.downloadFinished)
         url,downloaderParams = DMHelper.getDownloaderParamFromUrl(self.currItem.get('url', ''))
         self.downloader.start(url, GetTmpDir(self._TMP_FILE_NAME), downloaderParams)
     else:
         self["console"].setText(_("Download can not be started.\nDownloader %s not working correctly.\nStatus[%s]"))
示例#6
0
 def getResolvedURL(self, url):
     printDBG("LocalMedia.getResolvedURL [%s]" % url)
     videoUrls = []
     
     if url.startswith('/') and fileExists(url):
         url = 'file://'+url
     
     uri, params   = DMHelper.getDownloaderParamFromUrl(url)
     printDBG(params)
     uri = urlparser.decorateUrl(uri, params)
     
     if uri.meta.get('iptv_proto', '') in ['http', 'https']:
         urlSupport = self.up.checkHostSupport( uri )
     else:
         urlSupport = 0
     if 1 == urlSupport:
         retTab = self.up.getVideoLinkExt( uri )
         videoUrls.extend(retTab)
     elif 0 == urlSupport and self._uriIsValid(uri):
         if uri.split('?')[0].endswith('.m3u8'):
             retTab = getDirectM3U8Playlist(uri)
             videoUrls.extend(retTab)
         elif uri.split('?')[0].endswith('.f4m'):
             retTab = getF4MLinksWithMeta(uri)
             videoUrls.extend(retTab)
         else:
             videoUrls.append({'name':'direct link', 'url':uri})
     return videoUrls
示例#7
0
 def startDownloader(self, sts, reason):
     if sts:
         url,downloaderParams = DMHelper.getDownloaderParamFromUrl( self.cover['src'] )
         self.cover['downloader'] .subscribeFor_Finish(self.downloaderEnd)
         self.cover['downloader'] .start(url, self._getDownloadFilePath(), downloaderParams)
         self.showSpinner()
     else: self.session.openWithCallback(self.close, MessageBox, _("Downloading cannot be started.\n Downloader [%s] not working properly.\n Status[%s]") % (self.cover['downloader'].getName(), reason.strip()), type = MessageBox.TYPE_ERROR, timeout = 10 )        
 def onStart(self):
     self.onLayoutFinish.remove(self.onStart)
     self['progressBar'].value = 0
     self['bufferingBar'].range = (0, 100000)
     self['bufferingBar'].value = 0
     self.initGuiComponentsPos()
     if 'gstplayer' == self.player:
         gstplayerPath = config.plugins.iptvplayer.gstplayerpath.value
         #'export GST_DEBUG="*:6" &&' + 
         cmd = gstplayerPath  + ' "%s"' % self.fileSRC
         if "://" in self.fileSRC: 
             cmd += ' "%s" "%s"  "%s"  "%s" ' % (self.gstAdditionalParams['download-buffer-path'], self.gstAdditionalParams['ring-buffer-max-size'], self.gstAdditionalParams['buffer-duration'], self.gstAdditionalParams['buffer-size'])
             tmp = strwithmeta(self.fileSRC)
             url,httpParams = DMHelper.getDownloaderParamFromUrl(tmp)
             for key in httpParams: cmd += (' "%s=%s" ' % (key, httpParams[key]) )
             if 'http_proxy' in tmp.meta:
                 tmp = tmp.meta['http_proxy']
                 if '://' in tmp:
                     if '@' in tmp:
                         tmp = re.search('([^:]+?://)([^:]+?):([^@]+?)@(.+?)$', tmp)
                         if tmp: cmd += (' "proxy=%s" "proxy-id=%s" "proxy-pw=%s" ' % (tmp.group(1)+tmp.group(4), tmp.group(2), tmp.group(3)) )
                     else: cmd += (' "proxy=%s" ' % tmp)
     else:
         cmd = 'exteplayer3 "%s"' % self.fileSRC + " > /dev/null"
     
     self.console = eConsoleAppContainer()
     self.console_appClosed_conn = eConnectCallback(self.console.appClosed, self.eplayer3Finished)
     self.console_stderrAvail_conn = eConnectCallback(self.console.stderrAvail, self.eplayer3DataAvailable)
     #if 'gstplayer' == self.player: 
     #    self.console_stdoutAvail_conn = eConnectCallback(self.console.stdoutAvail, self.eplayer3DataAvailable2 ) # work around to catch EOF event after seeking, pause .etc
     printDBG("onStart cmd[%s]" % cmd)
     self.console.execute( cmd )
     self['statusIcon'].setPixmap( self.playback['statusIcons']['Play'] ) # sulge for test
示例#9
0
 def _startDownloader(self, sts, reason):
     if sts:
         self.downloader.subscribeFor_Finish(self.downloadFinished)
         url, downloaderParams = DMHelper.getDownloaderParamFromUrl(self.uri)
         self.downloader.start(url, self.outFile, downloaderParams)
     else:
         error, desc = self.downloader.getLastError()
         self["console"].setText(_("Download can not be started.\nDownloader %s not working correctly.\nLast error \"%s (%s)\".") % (self.downloader.getName(), desc, error))
示例#10
0
 def _doStart(self, force=False):
     if self.autoRefresh or force:
         self.refreshing = True
         self.downloader = DownloaderCreator(self.url)
         
         url,downloaderParams = DMHelper.getDownloaderParamFromUrl(self.url)
         self.downloader.subscribeFor_Finish(self.downloaderEnd)
         self.downloader.start(url, self._getDownloadFilePath(), downloaderParams)
         self.setMainTimerSts(True)
     else: self.refreshing = False
示例#11
0
 def _startDownloader(self, sts, reason):
     if sts:
         url,downloaderParams = DMHelper.getDownloaderParamFromUrl(self.url)
         if url.split('?', 1)[0].lower().endswith('.mp4'):
             self.clouldBeMP4 = True
         self.downloader.start(url, self.filePath, downloaderParams)
         self.setMainTimerSts(True)
         self.canRunMoviePlayer = True
     else:
         self.session.openWithCallback(self.iptvDoClose, MessageBox, _("Downloading can not be started.\n Downloader %s does not work properly.\nStatus[%s]") % (self.downloader.getName(), reason.strip()), type = MessageBox.TYPE_ERROR, timeout = 10 )
示例#12
0
 def _startDownloader(self, sts, reason):
     if sts:
         url,downloaderParams = DMHelper.getDownloaderParamFromUrl(self.url)
         if self._isFlvInfiniteFile(self.url):
             ret = touch(self.GST_FLV_DEMUX_IS_DEMUXING_INFINITE_FILE) # TODO: check returns value, and display message in case of False
         self.downloader.start(url, self.filePath, downloaderParams)
         self.setMainTimerSts(True)
         self.canRunMoviePlayer = True
     else:
         self.session.openWithCallback(self.close, MessageBox, _("Pobieranie nie może zostać rozpoczęte.\n Downloader %s nie działa prawidłowo.\nStatus[%s]") % (self.downloader.getName(), reason.strip()), type = MessageBox.TYPE_ERROR, timeout = 10 )
    def onStart(self):
        self.onLayoutFinish.remove(self.onStart)
        self['progressBar'].value = 0
        self['bufferingBar'].range = (0, 100000)
        self['bufferingBar'].value = 0
        self.initGuiComponentsPos()
        if 'gstplayer' == self.player:
            gstplayerPath = config.plugins.iptvplayer.gstplayerpath.value
            #'export GST_DEBUG="*:6" &&' +
            cmd = gstplayerPath + ' "%s"' % self.fileSRC
            if "://" in self.fileSRC:
                cmd += ' "%s" "%s"  "%s"  "%s" ' % (
                    self.gstAdditionalParams['download-buffer-path'],
                    self.gstAdditionalParams['ring-buffer-max-size'],
                    self.gstAdditionalParams['buffer-duration'],
                    self.gstAdditionalParams['buffer-size'])
                tmp = strwithmeta(self.fileSRC)
                url, httpParams = DMHelper.getDownloaderParamFromUrl(tmp)
                for key in httpParams:
                    cmd += (' "%s=%s" ' % (key, httpParams[key]))
                if 'http_proxy' in tmp.meta:
                    tmp = tmp.meta['http_proxy']
                    if '://' in tmp:
                        if '@' in tmp:
                            tmp = re.search(
                                '([^:]+?://)([^:]+?):([^@]+?)@(.+?)$', tmp)
                            if tmp:
                                cmd += (
                                    ' "proxy=%s" "proxy-id=%s" "proxy-pw=%s" '
                                    % (tmp.group(1) + tmp.group(4),
                                       tmp.group(2), tmp.group(3)))
                        else:
                            cmd += (' "proxy=%s" ' % tmp)
        else:
            cmd = 'exteplayer3 "%s"' % self.fileSRC + " > /dev/null"

        self.console = eConsoleAppContainer()
        self.console_appClosed_conn = eConnectCallback(self.console.appClosed,
                                                       self.eplayer3Finished)
        self.console_stderrAvail_conn = eConnectCallback(
            self.console.stderrAvail, self.eplayer3DataAvailable)
        #if 'gstplayer' == self.player:
        #    self.console_stdoutAvail_conn = eConnectCallback(self.console.stdoutAvail, self.eplayer3DataAvailable2 ) # work around to catch EOF event after seeking, pause .etc
        printDBG("onStart cmd[%s]" % cmd)
        self.console.execute(cmd)
        self['statusIcon'].setPixmap(
            self.playback['statusIcons']['Play'])  # sulge for test
示例#14
0
    def runCMD(self, item):
        printDBG("runCMD for downloadIdx[%d]" % item.downloadIdx)
        
        if DMHelper.DOWNLOAD_TYPE.INITIAL == item.tries:
           item.fileName = DMHelper.makeUnikalFileName(item.fileName, False, False)

        printDBG("Downloading started downloadIdx[%s] File[%s] URL[%s]" % (item.downloadIdx, item.fileName, item.url) )
      
        listUDIdx = self.findIdxInQueueUD(item.downloadIdx)
        self.queueUD[listUDIdx].status      = DMHelper.STS.DOWNLOADING
        self.queueUD[listUDIdx].fileName    = item.fileName
        
        url, downloaderParams = DMHelper.getDownloaderParamFromUrl(item.url)
        self.queueUD[listUDIdx].downloader = DownloaderCreator(url)
        self.queueUD[listUDIdx].callback   = boundFunction(self.cmdFinished, item.downloadIdx)
        self.queueUD[listUDIdx].downloader.subscribeFor_Finish( self.queueUD[listUDIdx].callback )
        self.queueUD[listUDIdx].downloader.start(url, item.fileName, downloaderParams)
示例#15
0
    def runCMD(self, item):
        printDBG("runCMD for downloadIdx[%d]" % item.downloadIdx)
        
        if DMHelper.DOWNLOAD_TYPE.INITIAL == item.tries:
           item.fileName = DMHelper.makeUnikalFileName(item.fileName, False, False)

        printDBG("Downloading started downloadIdx[%s] File[%s] URL[%s]" % (item.downloadIdx, item.fileName, item.url) )
      
        listUDIdx = self.findIdxInQueueUD(item.downloadIdx)
        self.queueUD[listUDIdx].status      = DMHelper.STS.DOWNLOADING
        self.queueUD[listUDIdx].fileName    = item.fileName
        
        url, downloaderParams = DMHelper.getDownloaderParamFromUrl(item.url)
        self.queueUD[listUDIdx].downloader = DownloaderCreator(url)
        self.queueUD[listUDIdx].callback   = boundFunction(self.cmdFinished, item.downloadIdx)
        self.queueUD[listUDIdx].downloader.subscribeFor_Finish( self.queueUD[listUDIdx].callback )
        self.queueUD[listUDIdx].downloader.start(url, item.fileName, downloaderParams)
示例#16
0
 def _startDownloader(self, sts, reason):
     if sts:
         url, downloaderParams = DMHelper.getDownloaderParamFromUrl(
             self.url)
         if self._isFlvInfiniteFile(self.url):
             ret = touch(
                 self.GST_FLV_DEMUX_IS_DEMUXING_INFINITE_FILE
             )  # TODO: check returns value, and display message in case of False
         self.downloader.start(url, self.filePath, downloaderParams)
         self.setMainTimerSts(True)
         self.canRunMoviePlayer = True
     else:
         self.session.openWithCallback(
             self.close,
             MessageBox,
             _("Pobieranie nie może zostać rozpoczęte.\n Downloader %s nie działa prawidłowo.\nStatus[%s]"
               ) % (self.downloader.getName(), reason.strip()),
             type=MessageBox.TYPE_ERROR,
             timeout=10)
示例#17
0
    def getLinksForVideo(self, cItem):
        printDBG("Urllist.getLinksForVideo url[%s]" % cItem['url'])
        videoUrls = []
        uri, params = DMHelper.getDownloaderParamFromUrl(cItem['url'])
        printDBG(params)
        uri = urlparser.decorateUrl(uri, params)

        urlSupport = self.up.checkHostSupport(uri)
        if 1 == urlSupport:
            retTab = self.up.getVideoLinkExt(uri)
            videoUrls.extend(retTab)
        elif 0 == urlSupport and self._uriIsValid(uri):
            if uri.split('?')[0].endswith('.m3u8'):
                retTab = getDirectM3U8Playlist(uri)
                videoUrls.extend(retTab)
            elif uri.split('?')[0].endswith('.f4m'):
                retTab = getF4MLinksWithMeta(uri)
                videoUrls.extend(retTab)
            else:
                videoUrls.append({'name': 'direct link', 'url': uri})
        return videoUrls
示例#18
0
 def getLinksForVideo(self, cItem):
     printDBG("Urllist.getLinksForVideo url[%s]" % cItem['url'])
     videoUrls = []
     uri, params   = DMHelper.getDownloaderParamFromUrl(cItem['url'])
     printDBG(params)
     uri = urlparser.decorateUrl(uri, params)
     
     urlSupport = self.up.checkHostSupport( uri )
     if 1 == urlSupport:
         retTab = self.up.getVideoLinkExt( uri )
         videoUrls.extend(retTab)
     elif 0 == urlSupport and self._uriIsValid(uri):
         if uri.split('?')[0].endswith('.m3u8'):
             retTab = getDirectM3U8Playlist(uri)
             videoUrls.extend(retTab)
         elif uri.split('?')[0].endswith('.f4m'):
             retTab = getF4MLinksWithMeta(uri)
             videoUrls.extend(retTab)
         else:
             videoUrls.append({'name':'direct link', 'url':uri})
     return videoUrls
示例#19
0
 def DownloadMovieLink(self, url):
     from Plugins.Extensions.IPTVPlayer.iptvdm.iptvdownloadercreator import IsUrlDownloadable, DownloaderCreator
     if IsUrlDownloadable(url):
         from Plugins.Extensions.IPTVPlayer.iptvdm.iptvdh import DMHelper
         url, downloaderParams = DMHelper.getDownloaderParamFromUrl(url)
         currentDownloader = DownloaderCreator(
             url)  #correct downloader is assigned (eg wget
         MovieRecordFileName = config.plugins.iptvplayer.NaszaSciezka.value + self.movieTitle.replace(
             '/', '-').replace(':', '-').replace('*', '-').replace(
                 '?', '-').replace('"', '-').replace('<', '-').replace(
                     '>', '-').replace('|', '-')
         MovieRecordFileNameExt = MovieRecordFileName[-4:]
         if not MovieRecordFileNameExt in ('.mpg', '.flv', '.mp4'):
             MovieRecordFileName += ".mp4"
         currentDownloader.start(url, MovieRecordFileName, downloaderParams)
         print "Downloading in background...\n   %s\n" % MovieRecordFileName
         time.sleep(5)
     else:
         print "\n" + _("No valid links available.")
         time.sleep(10)
     time.sleep(20)
     return
示例#20
0
    def start(self, uri, mode='loop'):
        self.uri = uri
        self.playMode = mode

        gstplayerPath = config.plugins.iptvplayer.gstplayerpath.value
        #'export GST_DEBUG="*:6" &&' +
        cmd = gstplayerPath + ' "%s"' % self.uri
        if "://" in self.uri:
            cmd += ' "%s" "%s"  "%s"  "%s" ' % (
                self.gstAdditionalParams['download-buffer-path'],
                self.gstAdditionalParams['ring-buffer-max-size'],
                self.gstAdditionalParams['buffer-duration'],
                self.gstAdditionalParams['buffer-size'])
            tmp = strwithmeta(self.uri)
            url, httpParams = DMHelper.getDownloaderParamFromUrl(tmp)
            for key in httpParams:
                cmd += (' "%s=%s" ' % (key, httpParams[key]))
            if 'http_proxy' in tmp.meta:
                tmp = tmp.meta['http_proxy']
                if '://' in tmp:
                    if '@' in tmp:
                        tmp = re.search('([^:]+?://)([^:]+?):([^@]+?)@(.+?)$',
                                        tmp)
                        if tmp:
                            cmd += (
                                ' "proxy=%s" "proxy-id=%s" "proxy-pw=%s" ' %
                                (tmp.group(1) + tmp.group(4), tmp.group(2),
                                 tmp.group(3)))
                    else:
                        cmd += (' "proxy=%s" ' % tmp)
        else:
            cmd = 'exteplayer3 "%s"' % self.uri + " > /dev/null"
        self.console = eConsoleAppContainer()
        self.console_appClosed_conn = eConnectCallback(self.console.appClosed,
                                                       self._playerFinished)
        printDBG("IPTVSimpleAudioPlayer.start cmd[%s]" % cmd)
        self.console.execute(E2PrioFix(cmd))
        self.stopped = False
示例#21
0
    def updateDisplay(self):
        printDBG("updateDisplay")
        if self.inMoviePlayer:
            printDBG("updateDisplay aborted - we are in moviePlayer")
            return

        if not self.mainTimerEnabled:
            printDBG("updateDisplay aborted - timer stoped")
            return

        self.downloader.updateStatistic()
        localSize  = self.downloader.getLocalFileSize()
        remoteSize = self.downloader.getRemoteFileSize()
        
        if self.checkMOOVAtom and \
           localSize > 10240:
            self.checkMOOVAtom = False
            
            if remoteSize > self.maxMOOVAtomSize and \
               self.downloader.getName() == "wget" and \
               (self.clouldBeMP4 or (None != self.downloader.getMimeType() and \
               'mp4' in self.downloader.getMimeType())):
                # check moov atom position
                # if it is located at the begining of MP4 file
                # it should be just after ftyp atom
                try:
                    f = open(self.filePath, "rb")
                    currOffset = 0
                    while currOffset < localSize:
                        rawSize =  ReadUint32(f.read(4), False)
                        rawType = f.read(4)
                        printDBG(">> rawType [%s]" % rawType)
                        printDBG(">> rawSize [%d]" % rawSize)
                        if currOffset == 0 and rawType != "ftyp":
                            # this does not looks like MP4 file
                            break
                        else:
                            if rawType == "moov":
                                self.moovAtomOffset = currOffset
                                self.moovAtomSize = rawSize
                                self.isMOOVAtomAtTheBeginning = True
                                break
                            elif rawType == "mdat":
                                # we are not sure if after mdat will be moov atom but 
                                # if this will be max last 10MB of file then 
                                # we will download it
                                self.moovAtomOffset = currOffset + rawSize
                                self.moovAtomSize = remoteSize - self.moovAtomOffset
                                self.isMOOVAtomAtTheBeginning = False
                                break
                            currOffset += rawSize
                        f.seek(currOffset, 0)
                    printDBG(">> moovAtomOffset[%d]" % self.moovAtomOffset)
                    printDBG(">> moovAtomSize[%d]" % self.moovAtomSize)
                except Exception:
                    printExc()
        
        if None != self.downloader and self.downloader.hasDurationInfo() \
           and self.downloader.getTotalFileDuration() > 0:
            totalDuration = self.downloader.getTotalFileDuration()
            downloadDuration = self.downloader.getDownloadedFileDuration()
            rFileSize = str(timedelta(seconds=totalDuration))
            lFileSize = str(timedelta(seconds=downloadDuration))
            if rFileSize.startswith('0:'):
                rFileSize = rFileSize[2:]
            if lFileSize.startswith('0:'):
                lFileSize = lFileSize[2:]
        else:
            # remote size
            if -1 == remoteSize: rFileSize = '??'
            else: rFileSize = formatBytes(float(remoteSize))
            # local size
            if -1 == localSize: lFileSize = '??'
            else: lFileSize = formatBytes(float(localSize))
        
        
        # download speed
        dSpeed = self.downloader.getDownloadSpeed()
        if dSpeed > -1 and localSize > 0:
            dSpeed = formatBytes(float(dSpeed))
        else:
            dSpeed = ''
        
        speed     = self.downloader.getDownloadSpeed()
        tmpStr    = ''
        if '??' != lFileSize:
            if '??' != rFileSize:
                tmpStr = "\n%s/%s" % (lFileSize, rFileSize)
            else:
                tmpStr = "\n%s" % (lFileSize)
            if '' != dSpeed:
               tmpStr += "\n%s/s" % (dSpeed)
        else:
            tmpStr += '\n\n'
        
        self["console"].setText(self.movieTitle + tmpStr)
        
        handled = False
        percentage = 0
        requestedBuffSize = -1
        tmpBuffSize = 0
        if self.isMOOVAtomAtTheBeginning == True:
            moovAtomDataSize = self.moovAtomOffset + self.moovAtomSize
            if moovAtomDataSize > localSize:
                if self.moovAtomStatus != self.MOOV_STS.DOWNLOADING:
                    self["addinfo"].setText(_("Please wait for initialization data."))
                    self.moovAtomStatus = self.MOOV_STS.DOWNLOADING
                remoteSize = self.moovAtomOffset + self.moovAtomSize
                if localSize > remoteSize: percentage = 100
                else: percentage = (100 * localSize) / remoteSize
            else:
                requestedBuffSize = self.requestedBuffSize
                if self.lastSize > moovAtomDataSize: tmpBuffSize = localSize - self.lastSize
                else: tmpBuffSize = localSize - moovAtomDataSize
                if tmpBuffSize > requestedBuffSize: percentage = 100
                else: percentage = (100 * tmpBuffSize) / requestedBuffSize
                if self.moovAtomStatus != self.MOOV_STS.DOWNLOADED:
                    self["addinfo"].setText("")
                    self.moovAtomStatus = self.MOOV_STS.DOWNLOADED
            handled = True
        elif self.isMOOVAtomAtTheBeginning == False and self.moovAtomStatus not in [self.MOOV_STS.WAITING, self.MOOV_STS.ERROR, self.MOOV_STS.DOWNLOADED]:
            # At now only exteplayer3 is able to use moov atom in separate file
            if self.activMoviePlayer == 'exteplayer' and self.moovAtomStatus == self.MOOV_STS.UNKNOWN:
                url, downloaderParams = DMHelper.getDownloaderParamFromUrl(self.url)
                downloaderParams['start_pos'] = self.moovAtomOffset
                self.moovAtomDownloader = DownloaderCreator(self.url)
                self.moovAtomDownloader.start(url, self.moovAtomPath, downloaderParams)
                self.moovAtomStatus = self.MOOV_STS.DOWNLOADING
                self["addinfo"].setText(_("Please wait - downloading initialization data."))
            elif self.moovAtomStatus == self.MOOV_STS.DOWNLOADING:
                self.moovAtomDownloader.updateStatistic()
                status = self.moovAtomDownloader.getStatus()
                moovLocalSize  = self.moovAtomDownloader.getLocalFileSize()
                moovRemoteSize = self.moovAtomDownloader.getRemoteFileSize()
                if status == DMHelper.STS.DOWNLOADING:
                    if moovLocalSize > 0 and self.moovAtomSize > 0:
                        if moovLocalSize > self.moovAtomSize: percentage = 100
                        else: percentage = (100 * moovLocalSize) / self.moovAtomSize
                elif status == DMHelper.STS.DOWNLOADED or (status == DMHelper.STS.INTERRUPTED and moovLocalSize == self.moovAtomSize):
                    self.moovAtomStatus = self.MOOV_STS.DOWNLOADED
                    self["addinfo"].setText("")
                else:
                    self.moovAtomStatus = self.MOOV_STS.ERROR
            
            handled = True
            if self.moovAtomStatus in [self.MOOV_STS.UNKNOWN, self.MOOV_STS.ERROR]:
                printDBG(">> [%s] [%s]" % (self.activMoviePlayer, self.moovAtomStatus))
                msg = [_("Whole file must be downloaded to start playback!")]
                if self.moovAtomStatus == self.MOOV_STS.UNKNOWN and self.activMoviePlayer != 'exteplayer':
                    msg.append(_("You can use external eplayer to start playback faster."))
                self["addinfo"].setText('\n'.join(msg))
                self.moovAtomStatus = self.MOOV_STS.WAITING
                handled = False
        
        if not handled and self.moovAtomStatus != self.MOOV_STS.WAITING:
            tmpBuffSize = localSize - self.lastSize + 1 # simple when getLocalFileSize() returns -1
            if self.downloader.getPlayableFileSize() > 0:
                requestedBuffSize = self.requestedBuffSize
                if tmpBuffSize > requestedBuffSize: percentage = 100
                else: percentage = (100 * tmpBuffSize) / requestedBuffSize
                handled = True
        
        if not handled and localSize > 0 and remoteSize > 0:
            if localSize > remoteSize: percentage = 100
            else: percentage = (100 * localSize) / remoteSize
        
        self["percentage"].setText(str(percentage))
        self["icon"].nextFrame()
        
        # check if we start movie player
        if self.canRunMoviePlayer:
            if (requestedBuffSize > -1 and tmpBuffSize >= requestedBuffSize) or \
               (self.downloader.getStatus() == DMHelper.STS.DOWNLOADED and 0 < localSize):
                self.runMovePlayer()
                return
        
        # check if it is downloading 
        if self.downloader.getStatus() not in [DMHelper.STS.POSTPROCESSING, DMHelper.STS.DOWNLOADING, DMHelper.STS.WAITING]:
            self.session.openWithCallback(self.iptvDoClose, MessageBox, _("Error occurs during download. \nStatus[%s], tmpBuffSize[%r], canRunMoviePlayer[%r]") % (self.downloader.getStatus(), tmpBuffSize, self.canRunMoviePlayer), type = MessageBox.TYPE_ERROR, timeout = 10 )
            self.canRunMoviePlayer = False
            # stop timer before message
            self.setMainTimerSts(False)

        return
示例#22
0
    def run(self):
        ret=None
        _temp = __import__('hosts.' + self.hostName, globals(), locals(), ['IPTVHost'], -1)
        self.title = _temp.gettytul()
        logState("Host title: %s\n" % self.title)
        self.host = _temp.IPTVHost()
        self.SelectedLink = ''
        try:
            if not isinstance(self.host, IHost):
                logState("Host [%r] inherits from IHost :)\n" % (self.hostName))
        except:
            logState( 'Cannot import class IPTVHost for host [%r]\n' %  self.hostName)
            self.stop()
            return

        hostconfig = __import__('hosts.' + self.hostName, globals(), locals(), ['GetConfigList'], -1)
        ConfList = hostconfig.GetConfigList()
        configureHOST(self.hostName)

        monitor = xbmc.Monitor()
        while not monitor.abortRequested() or xbmcgui.Window(10000).getProperty('plugin.video.IPTVplayer.HOST') == self.hostName:
            #logState("plugin.video.IPTVplayer.HOST=%s self.hostName=%s\n" %(xbmcgui.Window(10000).getProperty('plugin.video.IPTVplayer.HOST'),self.hostName))
            timestamp = long(myTime())
            xbmcgui.Window(10000).setProperty("kodiIPTVserviceHeartBeat", str(timestamp))
            # Sleep/wait for abort for 10 seconds
            if monitor.waitForAbort(1):
                break # Abort was requested while waiting. We should exit
            self.myCommand = getCMD()
            if self.myCommand == '':
                continue
            elif self.myCommand == 'STOPservice':
                self.stop()
                return
            elif self.myCommand == 'Title':
                myAnswer(self.title)
                continue
            elif self.myCommand == 'LogoPath':
                myAnswer(self.host.getLogoPath().value)
                continue
            elif self.myCommand == 'SupportedTypes':
                myAnswer(self.host.getSupportedFavoritesTypes().value)
                continue
            elif self.myCommand == 'InitList':
                ret = self.host.getInitList()
                if len(ConfList) > 0:
                    #### TBC    myAnswer(ToItemsListTable(ret.value, self.clientType) + ToConfigTable(ConfList, clientType)) #if host hasconfig, return it too
                    myAnswer(ToItemsListTable(ret.value, self.clientType)) #if host hasconfig, return it too
                else:
                    myAnswer(ToItemsListTable(ret.value, self.clientType))
                continue
            elif self.myCommand == 'RefreshList':
                ret = self.host.getCurrentList()
                myAnswer(ToItemsListTable(ret.value, self.clientType))
                continue
            elif self.myCommand == 'PreviousList':
                ret= self.host.getPrevList()
                myAnswer(ToItemsListTable(ret.value, self.clientType))
                continue
            elif self.myCommand.startswith('ListForItem='): #Param: item ID
                myID = self.myCommand.split('=')[1]
                if myID.isdigit():
                    myID = int(myID)
                    ret= self.host.getListForItem(myID,0,ret.value[myID])
                    myAnswer(ToItemsListTable(ret.value, self.clientType))
                else:
                    myAnswer('ERROR: wrong index')
                continue
            elif self.myCommand.startswith('getVideoLinks='): #Param: link ID
                myID = self.myCommand.split('=')[1]
                daemonLog("daemon:getVideoLinks=%s" % myID)
                if myID.isdigit():
                    myID = int(myID)
                    self.movieTitle = ret.value[myID].name.replace('"', "'")
                    try:
                        links = ret.value[myID].urlItems
                    except:
                        links='NOVALIDURLS'
                    try:
                        retUrl= self.host.getLinksForVideo(myID,ret.value[myID]) #returns "NOT_IMPLEMENTED" when host is using curlitem
                        myAnswer(ToUrlsTable(retUrl.value, self.clientType))
                        daemonLog("retUrl found")
                    except:
                        daemonLog("Exception running getLinksForVideo (means not implemented), using CUrlItem")
                        retUrl = RetHost(RetHost.NOT_IMPLEMENTED, value = [])
                    if retUrl.status == "NOT_IMPLEMENTED" and links != 'NOVALIDURLS': 
                        daemonLog("getLinksForVideo not implemented, using CUrlItem")
                        tempUrls=[]
                        daemonLog("Iterating links...")
                        iindex=1
                        for link in links:
                            if link.name == '':
                                tempUrls.append(CUrlItem('link %d' % iindex, link.url, link.urlNeedsResolve))
                            else:
                                tempUrls.append(CUrlItem(link.name, link.url, link.urlNeedsResolve))
                            iindex += 1
                        retUrl = RetHost(RetHost.OK, value = tempUrls)
                        myAnswer(ToUrlsTable(tempUrls, self.clientType))
                else:
                    myAnswer('ERROR: wrong index')
                continue
            #### ResolveURL ####
            elif self.myCommand.startswith('ResolveURL='): #Param: selected quality link ID
                myParm = self.myCommand.split('=')[1]
                url = "NOVALIDURLS"
                linksList = []
                if myParm.isdigit():
                    myID = int(myParm)
                    #czasami jest zwracana lista linkow wiec trzeba ja sparsowac
                    linksList = self.host.getResolvedURL(retUrl.value[myID].url).value
                    daemonLog("myParm.isdigit and points to:%s" % retUrl.value[myID].url)
                else:
                    linksList = self.host.getResolvedURL(myParm).value
                if len(linksList) == 0: #There is no free links for current video
                    daemonLog("linksList has no items :(")
                elif len(linksList) >1:
                    daemonLog('WARNING: more than one link returned, selecting first')
                if isinstance(linksList[0], CUrlItem):
                    if int(linksList[0].urlNeedsResolve) == 1:
                        daemonLog('ERROR: url should be already resolved. :(')
                    else:
                        url = linksList[0].url
                        daemonLog("CUrlItem url:%s" %url)
                elif isinstance(linksList[0], basestring):
                        url = linksList[0]
                        daemonLog("basestring url:%s" %url)
                elif isinstance(linksList, (list, tuple)):
                        url = linksList[0] 
                        daemonLog("list/tuple url:%s" %url)
                myAnswer( url )
            #### Download movie ####
            elif self.myCommand.startswith('DownloadURL='):  #Param: full download url
                url = self.myCommand[len('DownloadURL='):]   #using split results in wrong links
                from Plugins.Extensions.IPTVPlayer.iptvdm.iptvdownloadercreator import IsUrlDownloadable, DownloaderCreator
                if IsUrlDownloadable(url):
                    from Plugins.Extensions.IPTVPlayer.iptvdm.iptvdh import DMHelper
                    url, downloaderParams = DMHelper.getDownloaderParamFromUrl(url)
                    currentDownloader = DownloaderCreator(url) #correct downloader is assigned e.g. wget
                    MovieRecordFileName = os.path.join(config.plugins.iptvplayer.NaszaSciezka.value , getValidFileName(self.movieTitle))
                    MovieRecordFileNameExt = MovieRecordFileName[-4:]
                    if not MovieRecordFileNameExt in ('.mpg', '.flv', '.mp4'):
                        MovieRecordFileName += ".mp4"
                    currentDownloader.start(url, MovieRecordFileName, downloaderParams)
                    myAnswer(MovieRecordFileName)
                else:
                    myAnswer( 'ERROR:wrong url' )
            #### buffer movie ####
            elif self.myCommand.startswith('BufferURL='):  #Param: full download url
                url = self.myCommand[len('BufferURL='):]   #using split results in wrong links
                from Plugins.Extensions.IPTVPlayer.iptvdm.iptvdownloadercreator import IsUrlDownloadable, DownloaderCreator
                if IsUrlDownloadable(url):
                    from Plugins.Extensions.IPTVPlayer.iptvdm.iptvdh import DMHelper
                    url, downloaderParams = DMHelper.getDownloaderParamFromUrl(url)
                    currentDownloader = DownloaderCreator(url) #correct downloader is assigned e.g. wget
                    MovieRecordFileName = config.plugins.iptvplayer.NaszaSciezka.value + "iptv_buffering.mp4"
                    currentDownloader.start(url, MovieRecordFileName, downloaderParams)
                    myAnswer(MovieRecordFileName)
                else:
                    myAnswer( 'ERROR:wrong url' )
            #### Search items ####
            elif self.myCommand.startswith('Search='):  #Param: search pattern
                self.searchPattern = self.myCommand[len('Search='):] #param can contain '='. Using split function would brake everything ;)
                ret = self.host.getSearchResults(self.searchPattern)
                myAnswer(ToItemsListTable(ret.value, self.clientType))

            #### doCommand - not finished####
            elif self.myCommand.startswith('doCommand='): #Param: selected quality link ID
                execCMD = self.myCommand.replace('doCommand=','')
                try:
                    exec(execCMD)
                    myAnswer( 'OK' )
                except Exception:
                    myAnswer( 'ERROR executing command.')
            elif self.myCommand.startswith('doUnsafeCommand='): #Param: selected quality link ID
                execCMD = self.myCommand.replace('doUnsafeCommand=','')
                exec(execCMD)
                myAnswer( 'OK' )
            else:
                daemonLog("Unknown command:'%s'\n" % self.myCommand)
                myAnswer("ERROR: Unknown command:'%s'\n" % self.myCommand)
        self.stop()
        return