def __init__(self, iniFile):
     self.cache = StorageServer.StorageServer("Globosat", 12)
     self.plugin = FakePlugin(iniFile)
     self.api = globo.GloboApi(self.plugin, self.cache)
class GloboDownloader:
    def __init__(self, iniFile):
        self.cache = StorageServer.StorageServer("Globosat", 12)
        self.plugin = FakePlugin(iniFile)
        self.api = globo.GloboApi(self.plugin, self.cache)

    def download(self, url, fileName):
        if self.plugin.get_setting('download_command') != None:
            return self.download_native(url, fileName)

        return self.download_urlib(url, fileName)
    
    def download_native(self, url, fileName):
        print self.plugin.get_setting('download_command') % (fileName, url)
        retCode = subprocess.call(self.plugin.get_setting('download_command') % (fileName, url)  , shell=True)
        if retCode != 0 or not os.path.exists(fileName):
            print 'Error downloading file %s to %s' % (url, fileName )
            raise Exception('Error downloading file %s to %s' % (url, fileName ))
        return fileName


    def download_urlib(self, url, fileName):
        def getFileName(url,openUrl):
            if 'Content-Disposition' in openUrl.info():
                # If the response has Content-Disposition, try to get filename from it
                cd = dict(map(
                    lambda x: x.strip().split('=') if '=' in x else (x.strip(),''),
                    openUrl.info()['Content-Disposition'].split(';')))
                if 'filename' in cd:
                    filename = cd['filename'].strip("\"'")
                    if filename: return filename
            # if no filename was found above, parse it out of the final URL.
            return os.path.basename(urlparse.urlsplit(openUrl.url)[2])
    
        r = urllib2.urlopen(urllib2.Request(url))
        try:
            fileName = fileName or getFileName(url,r)
            with open(fileName, 'wb') as f:
                shutil.copyfileobj(r,f)
        finally:
            r.close()
    
        return fileName
    
    
    def printCategories(self):
        print '%-15s ==> %15s' % ('[CATEGORY NAME]','[CATEGORY]')
        categories = self.api.get_shows_by_categories()
        for slug, category in categories.items():
            print '%-15s ==> %15s' % (category['title'],slug)
    
    def printShows(self,category):
        if category not in self.api.get_shows_by_categories():
            print 'unkown category [%s]' % (category)
            return
    
        print '%-35s ==> %45s' % ('[SHOW NAME]','[URI]')
        shows = self.api.get_shows_by_categories()[category]['shows']
        for uri, name, icon in shows:
            print '%-35s ==> %45s' % (name, uri)
    
    def printShowRails(self,uri):
        print '%-35s ==> %35s' % ('[NAME]','[RAIL]')
        rails = self.api.get_rails(uri)
        for rail, name in rails:
            print '%-35s ==> %35s' % (name, rail)
    
    def printShowRailsVideos(self,uri,rail,page=1):
        kwargs = {
            'uri': uri,
            'rail': rail,
            'page': page,
            'timeout': 10,
            'retries': 10

        }
        
        print '%-55s ==> %10s' % ('[VIDEO TITLE]','[VIDEO ID]')
        programs = self.api.get_rail_videos(**kwargs)
        for program in programs.list:
            print '%-55s ==> %10s' % (program.title,program.id)
    
    def printVideosParts(self,videoId): 
        print '%-55s ==> %10s' % ('[VIDEO TITLE]','[VIDEO PART URL]')
        videos = self.api.get_videos(videoId) 
        for video in videos:
            print '%-55s ==> %10s' % (video.title, self.api.resolve_video_url(video.id))

    def downloadRailsVideos(self, uri, rail, downloadDir, force, combine,limit):
        kwargs = {
            'uri': uri,
            'rail': rail,
            'page': 1,
            'timeout': 10,
            'retries': 10
        }
        
        programs = self.api.get_rail_videos(**kwargs)
        for program in programs.list[:limit]:
            downloadFile = os.path.join(downloadDir,'%s.mp4' % (program.title.replace(' ','_').replace('/','_')).encode('ascii', 'ignore'))
            if os.path.exists(downloadFile) and not force:
                print 'File %s already exists. Skipping it.' % (downloadFile)
                continue
            videoPartsFiles = self.downloadVideoParts(program.id,downloadDir,force)
            if len(videoPartsFiles) > 0 and combine:
                self.combineVideoParts(downloadFile,videoPartsFiles)

    def downloadVideoParts(self, videoId, downloadDir, force):
        videosParts = self.api.get_videos(videoId)
        videoPartsFiles = []
        for video in videosParts:
            dowloadVideoPartFile = os.path.join(downloadDir,'%s.mp4' % (video.title.replace(' ','_').replace('/','_'))).encode('ascii', 'ignore')
            videoPartsFiles.append(dowloadVideoPartFile)
            if os.path.exists(dowloadVideoPartFile) and not force:
                print 'File %s already exists. Skipping it.' % (dowloadVideoPartFile)
                continue
            url = self.api.resolve_video_url(video.id)
            print "Downloading %s to %s" % (url,dowloadVideoPartFile)
            try:
                self.download(url,dowloadVideoPartFile)
                print "Downloaded %s" % (url)
            except:
                print 'Error downloading file %s' % (dowloadVideoPartFile)
                videoPartsFiles.remove(dowloadVideoPartFile)
                if os.path.exists(dowloadVideoPartFile):
                    print 'Deleting partial downloaded file %s' % ( dowloadVideoPartFile )
                    os.remove(dowloadVideoPartFile)
                raise
        return videoPartsFiles

    def combineVideoParts(self,outputFile,videos):
        intermediate_cmd = self.plugin.get_setting('ffmpeg_step')
        final_cmd = self.plugin.get_setting('ffmpeg_final')

        for video in videos:
            retCode = subprocess.call(intermediate_cmd % (video, video + '_intermediate.ts') , shell=True)
            if retCode != 0:
                print 'Error converting file %s to %s' % (video, video + '_intermediate.ts')
                return

        retCode = subprocess.call(final_cmd % ('_intermediate.ts|'.join(videos) + '_intermediate.ts', outputFile) , shell=True)
        if retCode != 0:
            print 'Error combining files %s to %s' % ('_intermediate.ts|'.join(videos) + '_intermediate.ts', outputFile)
            return

        for video in videos:
            os.remove(video)
            os.remove(video + '_intermediate.ts')