Exemplo n.º 1
0
    def __init__(self, url, idFilme, pastaData, temporada, episodio, nome, ano, logo, serieNome):
        xbmc.Player.__init__(self)
        self.url=url
        self.temporada=temporada
        self.episodio=episodio
        self.playing = True
        self.tempo = 0
        self.tempoTotal = 0
        self.idFilme = idFilme
        self.pastaData = xbmc.translatePath(pastaData)
        self.nome = nome
        self.ano = ano
        self.logo = logo
        self.serieNome = serieNome

        if not xbmcvfs.exists(os.path.join(pastaData,'tracker')):
            xbmcvfs.mkdirs(os.path.join(pastaData,'tracker'))


        if self.temporada != 0 and self.episodio != 0:
            self.pastaVideo = os.path.join(self.pastaData,'tracker',str(self.idFilme)+'S'+str(self.temporada)+'x'+str(self.episodio)+'.mrpiracy')
            self.content = 'episode'
        else:
            self.pastaVideo = os.path.join(self.pastaData,'tracker',str(self.idFilme)+'.mrpiracy')
            self.content = 'movie'
def Download(file_name, file_directory, season, episode):
  subtitle_list = []
  ## Cleanup temp dir, we recomend you download/unzip your subs in temp folder and
  ## pass that to XBMC to copy and activate
  if xbmcvfs.exists(__temp__):
    shutil.rmtree(__temp__)
  xbmcvfs.mkdirs(__temp__)

  file_data = geturl('http://subsfactory.it/subtitle/index.php?action=downloadfile&filename=' + file_name + '&directory=' + file_directory +'&', None)
  subs_files = []

  # Check if subtitle is downloaded
  if file_data:
    # Save file to the temp folder
    local_file_handle = open(os.path.join(__temp__, 'subsfactory.tmp'), 'wb')
    local_file_handle.write(file_data)
    local_file_handle.close()

    #Check archive type (rar/zip/else) through the file header (rar=Rar!, zip=PK)
    tmp_file = open(os.path.join(__temp__, 'subsfactory.tmp'), 'rb')
    tmp_file.seek(0)
    if tmp_file.read(1) == 'R':
      ext = 'rar'
      packed = True
    else:
      tmp_file.seek(0)
      if tmp_file.read(1) == 'P':
        ext = 'zip'
        packed = True
      else:
        ext = 'srt'
        packed = False
    tmp_file.close()
    # Rename file with the good ext
    os.rename(os.path.join(__temp__, 'subsfactory.tmp'), os.path.join(__temp__, 'subsfactory.' + ext))

    if packed:
      # Extract subs
      xbmc.sleep(500)
      xbmc.executebuiltin(('XBMC.Extract(' + os.path.join(__temp__, 'subsfactory.' + ext) + ',' + __temp__ +')').encode('utf-8'), True)

      if season is not None:
        episode_file = searchEpisode(season, episode)
        if episode_file is not None:
          subs_files.append(episode_file)
      else:
        folders = [__temp__]

        for folder in folders:
          newFolders = getFolders(folder)
          for newFolder in newFolders:
            folders.append(newFolder)
          for file in os.listdir(folder):
            if os.path.splitext(file)[1] in allowed_exts:
              subs_files.append(os.path.join(folder, file))
    else:
      subs_files.append(os.path.join(__temp__, 'subsfactory.' + ext))

  # Send the subtitle list to xbmc
  return subs_files
Exemplo n.º 3
0
def writeMediaList(url, name, cType='Other'):
    utils.addon_log('writeMediaList')
    existInList = False
    thelist = []
    thefile = xbmc.translatePath(os.path.join(profile, 'MediaList.xml'))
    theentry = '|'.join([cType, name.decode("utf-8"), url]) + '\n'  
    
    if not xbmcvfs.exists(profile): 
        xbmcvfs.mkdirs(profile)
    if not xbmcvfs.exists(thefile):
        open(thefile, 'a').close()
    
    fle = codecs.open(thefile, "r", 'UTF-8')
    thelist = fle.readlines()
    fle.close()
    del fle
    
    if len(thelist) > 0:
        for i in thelist:
            if i.split('|',2)[1] == name:
                thelist = stringUtils.replaceStringElem(thelist, theentry, theentry)
                existInList = True     
    if existInList != True:
        thelist.append(theentry)
        
    with open(thefile.decode("utf-8"), 'w') as output_file: 
        for linje in thelist:
            if not linje.startswith('\n'):
                output_file.write(linje.strip().encode('utf-8') + '\n')
            else:
                output_file.write(linje.strip())
Exemplo n.º 4
0
def makeSTRM(filepath, filename, url):
    filepath = stringUtils.multiRstrip(filepath.decode("utf-8"))
    filename = filename.decode("utf-8")
    
    utils.addon_log('makeSTRM')
    filepath = os.path.join(STRM_LOC, filepath)
    
    if not xbmcvfs.exists(filepath): 
        xbmcvfs.mkdirs(filepath)
    fullpath = xbmc.translatePath(os.path.join(filepath, filename + '.strm'))

    if xbmcvfs.exists(fullpath):
        if addon.getSetting('Clear_Strms') == 'true':
            x = 0 #xbmcvfs.delete(fullpath)
        else:
            return fullpath
    else:
        try:
            fle = open(fullpath.encode("utf-8"), "w")
        except:
            fle = open(fullpath.decode("utf-8"), "w")
            pass
        fle.write("%s" % url)
        fle.close()
        del fle
        return fullpath
Exemplo n.º 5
0
    def saveTorrent(self, torrentUrl):
        #if not xbmcvfs.exists(torrentUrl) or re.match("^http.+$", torrentUrl):
        if re.match("^magnet\:.+$", torrentUrl):
            self.magnetLink = torrentUrl
            self.magnetToTorrent(torrentUrl)
            self.magnetLink = None
            return self.torrentFile
        else:
            if not xbmcvfs.exists(self.torrentFilesPath): xbmcvfs.mkdirs(self.torrentFilesPath)
            torrentFile = os.path.join(self.torrentFilesPath, self.md5(torrentUrl) + '.torrent')
            try:
                if not re.match("^[htps]+?://.+$|^://.+$", torrentUrl):
                    log('xbmcvfs.File for %s' % torrentUrl)
                    content = xbmcvfs.File(torrentUrl, "rb").read()
                else:
                    log('request for %s' % torrentUrl)
                    content = self.makeRequest(torrentUrl)

                localFile = xbmcvfs.File(torrentFile, "w+b")
                localFile.write(content)
                localFile.close()
            except Exception, e:
                log('Unable to rename torrent file from %s to %s in AnteoLoader::saveTorrent. Exception: %s' %
                        (torrentUrl, torrentFile, str(e)))
                return
Exemplo n.º 6
0
def mkdirs(path):
    # Will create all folders in path if needed
    try:
        xbmcvfs.mkdirs(path)
    except:
        os.makedirs(path)
    return
Exemplo n.º 7
0
def playlist_path(pcs_file_path, stream):
    user_info = get_user_info()
    user_name = user_info['username']
    user_cookie = user_info['cookie']
    user_tokens = user_info['tokens']

    if stream:
        playlist_data = pcs.get_streaming_playlist(user_cookie, pcs_file_path, stream)
        if playlist_data:
            raw_dir = os.path.dirname(pcs_file_path)
            m = re.search('\/(.*)', raw_dir)
            dirname = m.group(1)
            basename = os.path.basename(pcs_file_path)
            r = re.search('(.*)\.(.*)$', basename)
            filename = ''.join([r.group(1), stream, '.m3u8'])
            dirpath = os.path.join(utils.data_dir(), user_name, dirname)
            if not xbmcvfs.exists(dirpath):
                xbmcvfs.mkdirs(dirpath)
            filepath = os.path.join(dirpath, filename)
            tmpFile = xbmcvfs.File(filepath, 'w')
            tmpFile.write(bytearray(playlist_data, 'utf-8'))
            return filepath
        else:
            dialog.notification('', u'无法打开视频,请尝试其他清晰度', xbmcgui.NOTIFICATION_INFO, 6000)
            return None
    else:
        url = pcs.get_download_link(user_cookie, user_tokens, pcs_file_path)
        return url
Exemplo n.º 8
0
    def setThumbnail(self, service, url=''):

        #load cachePath if not already loaded
        if self.cachePath == '':
            self.cachePath = service.settings.cachePath


        # there is no cache path setting or the setting is unset -- we should assume user does not want to use caching
        if not service.settings.cacheThumbnails or self.cachePath == '':

            if url == '':
                return self.package.file.thumbnail
            else:
                return url

        if url == '':
            url = self.package.file.thumbnail

        #simply no thumbnail
        if url == '':
            return ""

        #user doesn't want to cache thumbnails
        if not service.settings.cacheThumbnails:
            return url

        cachePath = str(self.cachePath) + str(self.package.file.id) + '/'
        cacheFile = str(self.cachePath) + str(self.package.file.id) + '.jpg'
        if not xbmcvfs.exists(cachePath):
            xbmcvfs.mkdirs(cachePath)
        if not xbmcvfs.exists(cacheFile):
            cacheFile = service.downloadGeneralFile(url, cacheFile)
            if cacheFile is None:
                return url
        return cacheFile
 def sync(self):
     if self._state == self.OBJECT_SKIP:
         return
     try:
         self._state = self.inSync() 
         if self._state == self.OBJECT_2_DOWNLOAD:
             log_debug('Create folder: %s'%self._localPath)
             xbmcvfs.mkdirs( self._localPath.encode("utf-8") )
             self.updateTimeStamp()
         elif self._state == self.OBJECT_2_UPLOAD:
             log_error('Can\'t upload folder: %s'%self._localPath)
             #TODO Add files if new files found local
             #TODO: modify timestamp of dir...
         elif self._state == self.OBJECT_2_REMOVE:
             log_debug('Remove folder: %s'%self._localPath)
             shutil.rmtree(self._localPath)
         elif self._state == self.OBJECT_ADD_CHILD:
             #TODO
             pass
         elif self._state == self.OBJECT_IN_SYNC:
             pass
         else:
             log_error('Unknown folder status(%s) for : %s!'%(self._state, self.path))
     except Exception, e:
         log_error('Exception occurred for folder %s' % self._localPath)
         log_error( traceback.format_exc() )
         if(self._failure):
            #failure happened before... So skip this item in all the next syncs!
             self._state = self.OBJECT_SKIP
             log_error('Skipping folder in next syncs: %s'% self._localPath)
         self._failure = True
Exemplo n.º 10
0
 def get_database(self):
     '''get reference to our sqllite database - performs basic integrity check'''
     addon = xbmcaddon.Addon(ADDON_ID)
     dbpath = addon.getAddonInfo('profile')
     dbfile = xbmc.translatePath("%s/simplecache.db" % dbpath).decode('utf-8')
     if not xbmcvfs.exists(dbpath):
         xbmcvfs.mkdirs(dbpath)
     del addon
     try:
         connection = sqlite3.connect(dbfile, timeout=30, isolation_level=None)
         connection.execute('SELECT * FROM simplecache LIMIT 1')
         return connection
     except Exception as error:
         # our database is corrupt or doesn't exist yet, we simply try to recreate it
         if xbmcvfs.exists(dbfile):
             xbmcvfs.delete(dbfile)
         try:
             connection = sqlite3.connect(dbfile, timeout=30, isolation_level=None)
             connection.execute(
                 """CREATE TABLE IF NOT EXISTS simplecache(
                 id TEXT UNIQUE, expires INTEGER, data TEXT, checksum INTEGER)""")
             return connection
         except Exception as error:
             self.log_msg("Exception while initializing database: %s" % str(error), xbmc.LOGWARNING)
             self.close()
             return None
Exemplo n.º 11
0
def ensure_workdir(workdir):
    # Cleanup temp dir, we recommend you download/unzip your subs in temp
    # folder and pass that to XBMC to copy and activate
    if xbmcvfs.exists(workdir):
        removeAll(workdir)
    xbmcvfs.mkdirs(workdir)
    return xbmcvfs.exists(workdir)
Exemplo n.º 12
0
def add_to_library(video_type, url, title, img, year, imdbnum, movie_num=''):
    try: IW_addon.log('Creating .strm for %s %s %s %s %s %s' % (video_type, title, imdbnum, url, img, year))
    except: pass
    if video_type == 'tvshow':
        save_path = IW_addon.get_setting('tvshow-folder')
        save_path = xbmc.translatePath(save_path)
        strm_string = IW_addon.build_plugin_url(
            {'mode': 'NightlyNewsSubMenu','dialog': '1'})
        if year: title = '%s (%s)' % (title, year)
        filename = filename_from_title(title + ' s1e1', 'movie')
        title = re.sub(r'[^\w\-_\. ]', '_', title)
        titles = title
        final_path = os.path.join(save_path, title, filename)
        final_path = xbmc.makeLegalFilename(final_path)
        if not xbmcvfs.exists(os.path.dirname(final_path)):
            try:
                try: xbmcvfs.mkdirs(os.path.dirname(final_path))
                except: os.path.mkdir(os.path.dirname(final_path))
            except Exception, e:
                try: IW_addon.log('Failed to create directory %s' % final_path)
                except: pass
        try:
            file_desc = xbmcvfs.File(final_path, 'w')
            file_desc.write(strm_string)
            file_desc.close()
        except Exception, e:
            IW_addon.log('Failed to create .strm file: %s\n%s' % (final_path, e))
Exemplo n.º 13
0
 def _make_dir(self, path, dir):
     subpath = os.path.join(path, dir)
     try:
         if not xbmcvfs.exists(subpath): xbmcvfs.mkdirs(subpath)
     except:
         if not os.path.exists(subpath): os.makedirs(subpath)              
     return subpath
Exemplo n.º 14
0
  def __init__(self, path, **kwargs):
    """
    A :class:`pyfscache.FSCache` object is instantiated
    with a `path` and optional lifetime keyword arguments:

  .. code-block:: python

      >>> c = FSCache('cache/dir', days=7)

    Inits a new FSCache instance at the given `path`.
    If the `path` doesn't exist, one is made. New objects
    added to the cache are given a lifetime, expressed in the
    keyword arguments `kwargs` with potential keys of
    ``years``, ``months``, ``weeks``, ``days``,
    ``hours``, ``minutes``, ``seconds``. See :func:`to_seconds`.
    If no keyword arguments are given, then the lifetime
    is considered to be infinite.

    Creating a :class:`pyfscache.FSCache` object does not purge
    the cache in `path` if the cache already exists. Instead,
    the :class:`pyfscache.FSCache` object will begin to use the
    cache, loading items and storing items as necessary.
    """
    if kwargs:
      self._lifetime = to_seconds(**kwargs)
      if self._lifetime <= 0:
        msg = "Lifetime (%s seconds) is 0 or less." % self._lifetime
        raise LifetimeError, msg
    else:
      self._lifetime = None
    self._loaded = {}
    self._path = os.path.abspath(path)
    if not xbmcvfs.exists(self._path):
      xbmcvfs.mkdirs(self._path)
Exemplo n.º 15
0
def writeConfig(cfile, value=''):
    cfgfile = os.path.join(configpath, cfile)
    cfglockfile = os.path.join(configpath, cfile + '.lock')

    if not xbmcvfs.exists(configpath):
        xbmcvfs.mkdirs(configpath)

    while True:
        if not xbmcvfs.exists(cfglockfile):
            l = xbmcvfs.File(cfglockfile, 'w')
            l.write(str(time.time()))
            l.close()
            if value == '':
                xbmcvfs.delete(cfgfile)
            else:
                f = xbmcvfs.File(cfgfile, 'w')
                f.write(value.__str__())
                f.close()
            xbmcvfs.delete(cfglockfile)
            xbmcvfs.delete(cfglockfile)
            return True
        else:
            l = xbmcvfs.File(cfglockfile)
            modified = float(l.read())
            l.close()
            if time.time() - modified > 0.1:
                xbmcvfs.delete(cfglockfile)
Exemplo n.º 16
0
    def add_item_to_library(self, item_path, item_url):
        error = False
        new = False
        if item_path:
            item_path = xbmc.translatePath(item_path)
            dir = os.path.dirname(item_path)
            if not xbmcvfs.exists(dir):
                try:
                    xbmcvfs.mkdirs(dir)
                except Exception, e:
                    error = True
                    print('Failed to create directory 1', dir)

            if not xbmcvfs.exists(dir):
                error = True
                print('Failed to create directory 2', dir)

            if not xbmcvfs.exists(item_path):
                try:
                    file_desc = xbmcvfs.File(item_path, 'w')
                    file_desc.write(item_url)
                    file_desc.close()
                    new = True
                except Exception, e:
                    print('Failed to create .strm file: ', item_path, e)
                    error = True
Exemplo n.º 17
0
    def setCC(self, service):

        if not constants.CONST.CC:
            return

        #load cachePath if not already loaded
        if self.cachePath == '':
            self.cachePath = service.settings.cachePath

        # there is no cache path setting or the setting is unset -- we should assume user does not want to use caching
        # CC files need to be cached (so they can be converted to SRT) -- don't do anything if we don't have the cachePath
        if self.cachePath == '':
            return

        else:
            cachePath = str(self.cachePath) + '/' + str(self.package.file.id)+'/'
            if not xbmcvfs.exists(cachePath):
                xbmcvfs.mkdirs(cachePath)
            cachePath = str(cachePath) + str(self.package.file.id)
            cc = service.getTTS(self.package.file.srtURL)
            if cc:
                for file in cc:
                    if not xbmcvfs.exists(cachePath + str(file[0])):
                        service.downloadTTS(file[1], str(cachePath) + str(file[0]))
                    self.srt.append(str(cachePath) + str(file[0]))
Exemplo n.º 18
0
    def setSRT(self, service):

        if not constants.CONST.SRT:
            return

        #load cachePath if not already loaded
        if not service.settings.cacheSRT and self.cachePath == '':
            self.cachePath = service.settings.cachePath

        #only makes sense to cache SRT if the cachePath exists
        if service.settings.cacheSRT and self.cachePath != '':
            cachePath = str(self.cachePath) + '/' + str(self.package.file.id)+'/'

            if not xbmcvfs.exists(cachePath):
                xbmcvfs.mkdirs(cachePath)
            srt = service.getSRT(self.package)
            if srt:
                for file in srt:
                    if not xbmcvfs.exists(str(cachePath) + str(file[0])):
                        service.downloadGeneralFile(file[1], str(cachePath) + str(file[0]))
                    self.srt.append(str(cachePath) + str(file[0]))

        #fetch SRT URLs but we won't cache the files
        else:
            srt = service.getSRT(self.package)
            if srt:
                for file in srt:
                    self.srt.append(str(file[1]) + '|' + service.getHeadersEncoded())
def download(id, url, filename, search_string=""):
    subtitle_list = []
    exts = [".srt", ".sub", ".txt", ".smi", ".ssa", ".ass"]

    ## Cleanup temp dir, we recomend you download/unzip your subs
    ## in temp folder and pass that to XBMC to copy and activate
    if xbmcvfs.exists(__temp__):
        shutil.rmtree(__temp__)
    xbmcvfs.mkdirs(__temp__)

    filename = os.path.join(__temp__, filename + ".zip")
    req = urllib2.Request(url, headers={"User-Agent": "Kodi-Addon"})
    sub = urllib2.urlopen(req).read()
    with open(filename, "wb") as subFile:
        subFile.write(sub)
    subFile.close()

    xbmc.sleep(500)
    xbmc.executebuiltin(
        (
            'XBMC.Extract("%s","%s")' % (filename, __temp__,)
        ).encode('utf-8'), True)

    for file in xbmcvfs.listdir(__temp__)[1]:
        file = os.path.join(__temp__, file)
        if os.path.splitext(file)[1] in exts:
            if search_string and string.find(
                string.lower(file),
                string.lower(search_string)
            ) == -1:
                continue
            log(__name__, "=== returning subtitle file %s" % file)
            subtitle_list.append(file)

    return subtitle_list
Exemplo n.º 20
0
    def __init__(self):

        self.__dict__ = self._shared_state

        client_info = clientinfo.ClientInfo()
        self.emby = embyserver.Read_EmbyServer()

        version = client_info.get_version()
        device_name = client_info.get_device_name()
        device_id = client_info.get_device_id()
        self._connect = connectionmanager.ConnectionManager(appName="Kodi",
                                                            appVersion=version,
                                                            deviceName=device_name,
                                                            deviceId=device_id)
        path = xbmc.translatePath(
                   "special://profile/addon_data/plugin.video.emby/").decode('utf-8')

        if not xbmcvfs.exists(path):
            xbmcvfs.mkdirs(path)

        self._connect.setFilePath(path)

        if window('emby_state.json'):
            self.state = window('emby_state.json')

        elif not self.state:
            self.state = self._connect.connect()
            log.info("Started with: %s", self.state)
            window('emby_state.json', value=self.state)
Exemplo n.º 21
0
def unzip(zip_file,path):
    import shutil
    import zipfile
    zip_file = try_decode(zip_file)
    path = try_decode(path)
    logMsg("START UNZIP of file %s  to path %s " %(zipfile,path))
    f = zipfile.ZipFile(zip_file, 'r')
    for fileinfo in f.infolist():
        filename = fileinfo.filename
        filename = try_decode(filename)
        logMsg("unzipping " + filename)
        if "\\" in filename: xbmcvfs.mkdirs(os.path.join(path,filename.rsplit("\\", 1)[0]))
        elif "/" in filename: xbmcvfs.mkdirs(os.path.join(path,filename.rsplit("/", 1)[0]))
        filename = os.path.join(path,filename)
        logMsg("unzipping " + filename)
        try:
            #newer python uses unicode
            outputfile = open(filename, "wb")
        except:
            #older python uses utf-8
            outputfile = open(filename.encode("utf-8"), "wb")
        #use shutil to support non-ascii formatted files in the zip
        shutil.copyfileobj(f.open(fileinfo.filename), outputfile)
        outputfile.close()
    f.close()
    logMsg("UNZIP DONE of file %s  to path %s " %(zipfile,path))
def Download(ID,lang,filename,key):
  URLBASE=__addon__.getSetting("BASEURL")
  url=URLBASE+"/he/api/subtitle/download/"+lang+"/?sub_id="+ID+"&v="+ urllib.quote(filename, safe='')+"&key="+key
  subtitle_list = []
  if xbmcvfs.exists(__temp__):
     shutil.rmtree(__temp__)
  xbmcvfs.mkdirs(__temp__)
  the_page=get_token()
  values = {'token' : the_page['token'], 'user': the_page['user'] }
  data = urllib.urlencode(values)
  req = urllib2.Request(url, data)
  response = urllib2.urlopen(req)
  zipdata= response.read()
  zipfilename=os.path.join(__temp__,filename)
  output = open(zipfilename,'wb')
  output.write(zipdata)
  output.close()
  zfobj = zipfile.ZipFile(zipfilename)
  for subname in zfobj.namelist():
      if subname.find(".srt") >0:
          zfobj.extract(subname,__temp__)
          subtitle_list.append(os.path.join(__temp__,subname))



  return subtitle_list
Exemplo n.º 23
0
    def download_subtitle(self, url):
        url = BASE_URL + url
        (response, srt) = self.__get_url(url)
        if not hasattr(response, 'info') or 'Content-Disposition' not in response.info():
            return

        cd = response.info()['Content-Disposition']
        r = re.search('filename="(.*)"', cd)
        if r:
            filename = r.group(1)
        else:
            filename = 'addic7ed_subtitle.srt'
        filename = re.sub('[^\x00-\x7F]', '', filename)

        final_path = os.path.join(kodi.get_setting('subtitle-folder'), filename)
        final_path = kodi.translate_path(final_path)
        if not xbmcvfs.exists(os.path.dirname(final_path)):
            try:
                try: xbmcvfs.mkdirs(os.path.dirname(final_path))
                except: os.mkdir(os.path.dirname(final_path))
            except:
                log_utils.log('Failed to create directory %s' % os.path.dirname(final_path), log_utils.LOGERROR)
                raise

        with open(final_path, 'w') as f:
            f.write(srt)
        return final_path
Exemplo n.º 24
0
    def saveTorrent(self, torrentUrl):
        #if not xbmcvfs.exists(torrentUrl) or re.match("^http.+$", torrentUrl):
        if re.match("^magnet\:.+$", torrentUrl):
            self.magnetLink = torrentUrl
            self.magnetToTorrent(torrentUrl)
            self.magnetLink = None
            return self.torrentFile
        else:
            if not xbmcvfs.exists(self.torrentFilesPath): xbmcvfs.mkdirs(self.torrentFilesPath)
            torrentFile = os.path.join(self.torrentFilesPath, self.md5(torrentUrl) + '.torrent')
            try:
                if not re.match("^http\:.+$", torrentUrl):
                    content = xbmcvfs.File(torrentUrl, "rb").read()
                else:
                    request = urllib2.Request(torrentUrl)
                    request.add_header('Referer', torrentUrl)
                    request.add_header('Accept-encoding', 'gzip')
                    result = urllib2.urlopen(request)
                    if result.info().get('Content-Encoding') == 'gzip':
                        buf = StringIO(result.read())
                        decomp = zlib.decompressobj(16 + zlib.MAX_WBITS)
                        content = decomp.decompress(buf.getvalue())
                    else:
                        content = result.read()

                localFile = xbmcvfs.File(torrentFile, "w+b")
                localFile.write(content)
                localFile.close()
            except Exception, e:
                log('Unable to rename torrent file from %s to %s in InposLoader::saveTorrent. Exception: %s' %
                        (torrentUrl, torrentFile, str(e)))
                return
Exemplo n.º 25
0
 def mkdirs(fle):
     FileAccess.log('mkdirs ' + fle)
     try:
         xbmcvfs.mkdirs(fle)
         return True
     except:
         return False
Exemplo n.º 26
0
def add2lib( url, name, infol, img, fanart, year ):

    img = 'http://oi62.tinypic.com/dvgj1t.jpg'
    addon.log('Add To Library %s , %s, %s' % (name,year,url))

    path = xbmc.translatePath( addon.get_setting('movie-folder') )
    string = 'plugin://plugin.video.mutttsnutz/?mode=playstream&url='+url+'&name='+name+'&infol='
    filename = '%s.strm' % name
    path = xbmc.makeLegalFilename( xbmc.translatePath(os.path.join( path, name, filename )))

    if not xbmcvfs.exists(os.path.dirname(path)):
        try:
            try: xbmcvfs.mkdirs(os.path.dirname(path))
            except: os.mkdir(os.path.dirname(path))
        except:
            addon.log('FAILED to create directory')

    if xbmcvfs.exists(path):
        addon.log( name+' Already in the library' )
        notification( addon.get_name()+' allready added', name, img)
        return
    
    notification( addon.get_name()+' adding to library', name+' adding to library', img)
    strm = xbmcvfs.File(path, 'w')
    strm.write(string)
    strm.close()
    xbmc.executebuiltin("UpdateLibrary(video)")
Exemplo n.º 27
0
def resolve(url):
    actions = [
        ("plugin://plugin.video.yatp/?action=play&torrent=%s", "plugin.video.yatp", "YATP-Yet Another Torrent Player"),
        ("plugin://plugin.video.quasar/play?uri=%s", "plugin.video.quasar", "Quasar"),
    ]
    if not xbmcvfs.exists(os.path.dirname(torrent_path)):
        try:
            xbmcvfs.mkdirs(os.path.dirname(torrent_path))
        except:
            os.mkdir(os.path.dirname(torrent_path))

    file = urllib2.urlopen(url)
    output = open(torrent_path, "wb")
    output.write(file.read())
    output.close()

    choice = int(control.setting("torrentPlayer"))
    action = actions[choice]
    if choice == 0:
        url = torrent_path

    if addonInstaller.isInstalled(action[1]):
        return action[0] % url
    else:
        control.infoDialog(
            "Torrent player not installed. Install it or select a different torrent player.",
            heading=action[2],
            time=6000,
        )
    return ""
Exemplo n.º 28
0
def setAddonsettings():
    if not xbmcvfs.exists(SETTING("pvrthumbspath")):
        xbmcvfs.mkdirs(SETTING("pvrthumbspath"))
    if not xbmcvfs.exists("special://profile/addon_data/script.skin.helper.service/musicart/"):
        xbmcvfs.mkdirs("special://profile/addon_data/script.skin.helper.service/musicart/")
    #get the addonsettings and store them in memory
    WINDOW.setProperty("SkinHelper.pvrthumbspath",SETTING("pvrthumbspath"))
    WINDOW.setProperty("SkinHelper.cacheRecordings",SETTING("cacheRecordings"))
    WINDOW.setProperty("SkinHelper.cacheGuideEntries",SETTING("cacheGuideEntries"))
    WINDOW.setProperty("SkinHelper.customRecordingsPath",SETTING("customRecordingsPath"))
    WINDOW.setProperty("SkinHelper.useTMDBLookups",SETTING("useTMDBLookups"))
    WINDOW.setProperty("SkinHelper.useGoogleLookups",SETTING("useGoogleLookups"))
    WINDOW.setProperty("SkinHelper.useYoutubeLookups",SETTING("useYoutubeLookups"))
    WINDOW.setProperty("SkinHelper.useLocalLibraryLookups",SETTING("useLocalLibraryLookups"))
    WINDOW.setProperty("SkinHelper.customlookuppath",SETTING("customlookuppath"))
    WINDOW.setProperty("SkinHelper.useFanArtTv",SETTING("useFanArtTv"))
    WINDOW.setProperty("SkinHelper.ignorechannels",SETTING("ignorechannels"))
    WINDOW.setProperty("SkinHelper.ignoretitles",SETTING("ignoretitles"))
    WINDOW.setProperty("SkinHelper.stripwords",SETTING("stripwords"))
    WINDOW.setProperty("SkinHelper.directory_structure",SETTING("directory_structure"))
    WINDOW.setProperty("SkinHelper.lastUpdate","%s" %datetime.now())    
    WINDOW.setProperty("SkinHelper.enablewallbackgrounds",SETTING("enablewallbackgrounds"))
    WINDOW.setProperty("SkinHelper.enableMusicArtScraper",SETTING("enableMusicArtScraper"))
    WINDOW.setProperty("SkinHelper.downloadMusicArt",SETTING("downloadMusicArt"))
    WINDOW.setProperty("SkinHelper.enableLocalMusicArtLookup",SETTING("enableLocalMusicArtLookup"))
    WINDOW.setProperty("SkinHelper.enableDebugLog",SETTING("enableDebugLog"))
    WINDOW.setProperty("SkinHelper.maxNumFanArts",SETTING("maxNumFanArts"))
    WINDOW.setProperty("SkinHelper.splittitlechar",SETTING("splittitlechar"))
    WINDOW.setProperty("SkinHelper.enablePVRThumbsRecordingsOnly",SETTING("enablePVRThumbsRecordingsOnly"))
    WINDOW.setProperty("SkinHelper.preferOnlineMusicArt",SETTING("preferOnlineMusicArt"))
    WINDOW.setProperty("SkinHelper.enableWidgetsArtworkLookups",SETTING("enableWidgetsArtworkLookups"))
    WINDOW.setProperty("SkinHelper.enableSpecialsInWidgets",SETTING("enableSpecialsInWidgets"))
    WINDOW.setProperty("SkinHelper.enableWidgetsAlbumBrowse",SETTING("enableWidgetsAlbumBrowse"))
Exemplo n.º 29
0
    def __init__(self):
        run = Prop("run")
        if (run) and (time.time() < float(run) + 3):
            return

        Prop("run", str(time.time()))
        Prop("stamp", _stamp)

        self.once = True
        self.abort = False
        self.mesg = None
        self.station = None
        self.stations = None
        self.songs = {}
        self.pithos = mypithos.Pithos()
        self.player = xbmc.Player()
        self.playlist = xbmc.PlayList(xbmc.PLAYLIST_MUSIC)
        self.ahead = {}
        self.queue = collections.deque()
        self.prof = Val("prof")
        self.wait = {"auth": 0, "stations": 0, "flush": 0, "scan": 0, "next": 0}
        self.silent = xbmc.translatePath("special://home/addons/%s/resources/media/silent.m4a" % _id)

        musicbrainzngs.set_useragent("kodi.%s" % _id, Val("version"))
        xbmcvfs.mkdirs(xbmc.translatePath(Val("cache")).decode("utf-8"))
        xbmcvfs.mkdirs(xbmc.translatePath(Val("library")).decode("utf-8"))
Exemplo n.º 30
0
    def saveTorrent(self, torrentUrl):
        if not xbmcvfs.exists(torrentUrl) or re.match("^http.+$", torrentUrl):
            if re.match("^magnet\:.+$", torrentUrl):
                self.magnetLink = torrentUrl
                self.magnetToTorrent(torrentUrl)
                self.magnetLink = None
                return self.torrentFile
            else:
                if not xbmcvfs.exists(self.torrentFilesPath): xbmcvfs.mkdirs(self.torrentFilesPath)
                torrentFile = os.path.join(self.torrentFilesPath, self.md5(torrentUrl) + '.torrent')
                try:
                    if not re.match("^http\:.+$", torrentUrl):
                        content = xbmcvfs.File(torrentUrl, "rb").read()
                    else:
                        request = urllib2.Request(torrentUrl)
                        request.add_header('Referer', torrentUrl)
                        request.add_header('Accept-encoding', 'gzip')
                        result = urllib2.urlopen(request)
                        if result.info().get('Content-Encoding') == 'gzip':
                            buf = StringIO(result.read())
                            f = gzip.GzipFile(fileobj=buf)
                            content = f.read()
                        else:
                            content = result.read()

                    localFile = xbmcvfs.File(torrentFile, "w+b")
                    localFile.write(content)
                    localFile.close()
                except Exception, e:
                    print 'Unable to save torrent file from "' + torrentUrl + '" to "' + torrentFile + '" in Torrent::saveTorrent' + '. Exception: ' + str(
                        e)
                    return
Exemplo n.º 31
0
 def create(self):
     xbmcvfs.mkdirs(self.fullpath)
Exemplo n.º 32
0
def getExtraFanArt(embyId, embyPath):

    emby = embyserver.Read_EmbyServer()
    art = artwork.Artwork()

    # Get extrafanart for listitem
    # will be called by skinhelper script to get the extrafanart
    try:
        # for tvshows we get the embyid just from the path
        if not embyId:
            if "plugin.video.emby" in embyPath:
                embyId = embyPath.split("/")[-2]

        if embyId:
            #only proceed if we actually have a emby id
            log("Requesting extrafanart for Id: %s" % embyId, 0)

            # We need to store the images locally for this to work
            # because of the caching system in xbmc
            fanartDir = xbmc.translatePath("special://thumbnails/emby/%s/" %
                                           embyId).decode('utf-8')

            if not xbmcvfs.exists(fanartDir):
                # Download the images to the cache directory
                xbmcvfs.mkdirs(fanartDir)
                item = emby.getItem(embyId)
                if item:
                    backdrops = art.getAllArtwork(item)['Backdrop']
                    tags = item['BackdropImageTags']
                    count = 0
                    for backdrop in backdrops:
                        # Same ordering as in artwork
                        tag = tags[count]
                        if os.path.supports_unicode_filenames:
                            fanartFile = os.path.join(fanartDir,
                                                      "fanart%s.jpg" % tag)
                        else:
                            fanartFile = os.path.join(
                                fanartDir.encode("utf-8"),
                                "fanart%s.jpg" % tag.encode("utf-8"))
                        li = xbmcgui.ListItem(tag, path=fanartFile)
                        xbmcplugin.addDirectoryItem(handle=int(sys.argv[1]),
                                                    url=fanartFile,
                                                    listitem=li)
                        xbmcvfs.copy(backdrop, fanartFile)
                        count += 1
            else:
                log("Found cached backdrop.", 2)
                # Use existing cached images
                dirs, files = xbmcvfs.listdir(fanartDir)
                for file in files:
                    fanartFile = os.path.join(fanartDir, file.decode('utf-8'))
                    li = xbmcgui.ListItem(file, path=fanartFile)
                    xbmcplugin.addDirectoryItem(handle=int(sys.argv[1]),
                                                url=fanartFile,
                                                listitem=li)
    except Exception as e:
        log("Error getting extrafanart: %s" % e, 0)

    # Always do endofdirectory to prevent errors in the logs
    xbmcplugin.endOfDirectory(int(sys.argv[1]))
Exemplo n.º 33
0
 def make_dir(self, mypath):
     ''' Creates sub-directories if they are not found. '''
     try:
         if not xbmcvfs.exists(mypath): xbmcvfs.mkdirs(mypath)
     except:
         if not os.path.exists(mypath): os.makedirs(mypath)
Exemplo n.º 34
0
 def _init_filesystem_cache(self):
     from xbmcvfs import mkdirs
     from resources.lib.cache import BUCKET_NAMES
     for bucket in BUCKET_NAMES:
         mkdirs(xbmc.translatePath(os.path.join(self.CACHE_PATH, bucket)))
Exemplo n.º 35
0
__addon__ = xbmcaddon.Addon()
__author__     = __addon__.getAddonInfo('author')
__scriptid__   = __addon__.getAddonInfo('id')
__scriptname__ = __addon__.getAddonInfo('name')
__version__    = __addon__.getAddonInfo('version')
__language__   = __addon__.getLocalizedString

__cwd__        = xbmc.translatePath(__addon__.getAddonInfo('path')).decode("utf-8")
__profile__    = xbmc.translatePath(__addon__.getAddonInfo('profile')).decode("utf-8")
__resource__   = xbmc.translatePath(os.path.join(__cwd__, 'resources', 'lib')).decode("utf-8")
__temp__       = xbmc.translatePath(os.path.join(__profile__, 'temp', ''))

if xbmcvfs.exists(__temp__):
    shutil.rmtree(__temp__)
xbmcvfs.mkdirs(__temp__)

sys.path.append (__resource__)

from OSUtilities import OSDBServer, log, normalizeString
import requests
def Search(item):
    search_data = []
    try:
        search_data = OSDBServer().searchsubtitles(item)
    except:
        log(__name__, "failed to connect to service for subtitle search")
        xbmc.executebuiltin((u'Notification(%s,%s)' % (__scriptname__, __language__(32001))).encode('utf-8'))
        return
    if search_data != None:
        for item_data in search_data:
Exemplo n.º 36
0
from datetime import date, datetime, timedelta
import hashlib
import json
import gzip
import sys
import re

ADDON = xbmcaddon.Addon()
logger = logging.getLogger(ADDON.getAddonInfo('id'))
kodilogging.config()
plugin = routing.Plugin()

__profile__ = xbmc.translatePath(ADDON.getAddonInfo('profile'))

if not xbmcvfs.exists(__profile__):
    xbmcvfs.mkdirs(__profile__)

favorites_file_path = __profile__+"favorites.json"
favorites = {}

icon_path = ADDON.getAddonInfo('path')+"/resources/logos/{0}.png"

setContent(plugin.handle, '')

@plugin.route('/')
def index():
    icon = get_url(ids.collections_request_url.format(id=ids.icon_id, page="1"))
    live_icon = ""
    highlights_icon = ""
    highlights_id = ids.highlights_id
    mediathek_icon = ""
Exemplo n.º 37
0
def download_media(url, path, file_name):
    try:
        progress = int(kodi.get_setting('down_progress'))
        request = urllib2.Request(url)
        request.add_header('User-Agent', USER_AGENT)
        request.add_unredirected_header('Host', request.get_host())
        response = urllib2.urlopen(request)

        content_length = 0
        if 'Content-Length' in response.info():
            content_length = int(response.info()['Content-Length'])

        file_name = file_name.replace('.strm', get_extension(url, response))
        full_path = os.path.join(path, file_name)
        log_utils.log('Downloading: %s -> %s' % (url, full_path), log_utils.LOGDEBUG)

        path = xbmc.makeLegalFilename(path)
        if not xbmcvfs.exists(path):
            try:
                try: xbmcvfs.mkdirs(path)
                except: os.mkdir(path)
            except Exception as e:
                raise Exception(i18n('failed_create_dir'))

        file_desc = xbmcvfs.File(full_path, 'w')
        total_len = 0
        if progress:
            if progress == PROGRESS.WINDOW:
                dialog = xbmcgui.DialogProgress()
            else:
                dialog = xbmcgui.DialogProgressBG()

            dialog.create('Stream All The Sources', i18n('downloading') % (file_name))
            dialog.update(0)
        while True:
            data = response.read(CHUNK_SIZE)
            if not data:
                break

            if progress == PROGRESS.WINDOW and dialog.iscanceled():
                break

            total_len += len(data)
            if not file_desc.write(data):
                raise Exception('failed_write_file')

            percent_progress = (total_len) * 100 / content_length if content_length > 0 else 0
            log_utils.log('Position : %s / %s = %s%%' % (total_len, content_length, percent_progress), log_utils.LOGDEBUG)
            if progress == PROGRESS.WINDOW:
                dialog.update(percent_progress)
            elif progress == PROGRESS.BACKGROUND:
                dialog.update(percent_progress, 'Stream All The Sources')
        else:
            kodi.notify(msg=i18n('download_complete') % (file_name), duration=5000)
            log_utils.log('Download Complete: %s -> %s' % (url, full_path), log_utils.LOGDEBUG)

        file_desc.close()
        if progress:
            dialog.close()

    except Exception as e:
        log_utils.log('Error (%s) during download: %s -> %s' % (str(e), url, file_name), log_utils.LOGERROR)
        kodi.notify(msg=i18n('download_error') % (str(e), file_name), duration=5000)
Exemplo n.º 38
0
def main():
    """Main entry point of the script when it is invoked by XBMC."""
    global kodi_major_version
    # Get parameters from XBMC and launch actions
    params = get_params(sys.argv)
    action = params.get('action', 'Unknown')
    xbmc.log(u"SUBDIVX - Version: %s -- Action: %s" % (__version__, action),
             level=LOGNOTICE)
    kodi_major_version = int(
        xbmc.getInfoLabel('System.BuildVersion').split('.')[0])

    if action in ('search', 'manualsearch'):
        item = {
            'temp':
            False,
            'rar':
            False,
            'year':
            xbmc.getInfoLabel("VideoPlayer.Year"),
            'season':
            str(xbmc.getInfoLabel("VideoPlayer.Season")),
            'episode':
            str(xbmc.getInfoLabel("VideoPlayer.Episode")),
            'tvshow':
            normalize_string(xbmc.getInfoLabel("VideoPlayer.TVshowtitle")),
            # Try to get original title
            'title':
            normalize_string(xbmc.getInfoLabel("VideoPlayer.OriginalTitle")),
            # Full path of a playing file
            'file_original_path':
            unquote(xbmc.Player().getPlayingFile().decode('utf-8')),
            '3let_language': [],
            '2let_language': [],
            'manual_search':
            'searchstring' in params,
        }

        if 'searchstring' in params:
            item['manual_search_string'] = params['searchstring']

        for lang in unquote(params['languages']).decode('utf-8').split(","):
            item['3let_language'].append(
                xbmc.convertLanguage(lang, xbmc.ISO_639_2))
            item['2let_language'].append(
                xbmc.convertLanguage(lang, xbmc.ISO_639_1))

        if not item['title']:
            # No original title, get just Title
            item['title'] = normalize_string(
                xbmc.getInfoLabel("VideoPlayer.Title"))

        if "s" in item['episode'].lower():
            # Check if season is "Special"
            item['season'] = "0"
            item['episode'] = item['episode'][-1:]

        if "http" in item['file_original_path']:
            item['temp'] = True

        elif "rar://" in item['file_original_path']:
            item['rar'] = True
            item['file_original_path'] = os.path.dirname(
                item['file_original_path'][6:])

        elif "stack://" in item['file_original_path']:
            stackPath = item['file_original_path'].split(" , ")
            item['file_original_path'] = stackPath[0][8:]

        Search(item)
        # Send end of directory to XBMC
        xbmcplugin.endOfDirectory(int(sys.argv[1]))

    elif action == 'download':
        debug_dump_path(
            xbmc.translatePath(__addon__.getAddonInfo('profile')),
            "xbmc.translatePath(__addon__.getAddonInfo('profile'))")
        debug_dump_path(__profile__, '__profile__')
        xbmcvfs.mkdirs(__profile__)
        _cleanup_tempdirs(__profile__)
        workdir = tempfile.mkdtemp(dir=__profile__)
        # Make sure it ends with a path separator (Kodi 14)
        workdir = workdir + os.path.sep
        debug_dump_path(workdir, 'workdir')
        # We pickup our arguments sent from the Search() function
        subs = Download(params["id"], workdir)
        # We can return more than one subtitle for multi CD versions, for now
        # we are still working out how to handle that in XBMC core
        for sub in subs:
            # XXX: Kodi still can't handle multiple subtitles files returned
            # from an addon, it will always use the first file returned. So
            # there is no point in reporting a forced subtitle file to it.
            # See https://github.com/ramiro/service.subtitles.subdivx/issues/14
            if sub['forced']:
                continue
            listitem = xbmcgui.ListItem(label=sub['path'])
            xbmcplugin.addDirectoryItem(handle=int(sys.argv[1]),
                                        url=sub['path'],
                                        listitem=listitem,
                                        isFolder=False)
        # Send end of directory to XBMC
        xbmcplugin.endOfDirectory(int(sys.argv[1]))

        sleep(2)
        if __addon__.getSetting('show_nick_in_place_of_lang') == 'true':
            _double_dot_fix_hack(params['filename'].encode('utf-8'))
        _cleanup_tempdir(workdir, verbose=True)
Exemplo n.º 39
0
#xbmc.log("base_url: " + str(base_url) + " mode: " + str(mode), xbmc.LOGINFO)

if mode == constants.ADDALLTOLIBRARY:
    xbmc.log("Start of ADDALLTOLIBRARY, rootFolder=" + str(getRootFolder()),
             xbmc.LOGINFO)
    xbmc.executebuiltin(
        'Notification(VDR Recordings, ' +
        xbmcaddon.Addon(constants.ADDON_NAME).getLocalizedString(30109) + ')',
        False)
    # create list of old files
    old_files = {}
    recursive_add_files(constants.LIBRARY_MOVIES, old_files)
    recursive_add_files(constants.LIBRARY_TV_SHOWS, old_files)
    recursive_add_files(constants.LIBRARY_MUSIC_VIDEOS, old_files)
    # make directories (if required)
    xbmcvfs.mkdirs(constants.LIBRARY_MOVIES)
    xbmcvfs.mkdirs(constants.LIBRARY_TV_SHOWS)
    xbmcvfs.mkdirs(constants.LIBRARY_MUSIC_VIDEOS)
    # add current (new) files
    new_files = {}
    xbmc.log("ADDALLTOLIBRARY, before adding all files", xbmc.LOGINFO)
    kfolder.kFolder(getRootFolder()).parseFolder(-10, new_files)
    xbmc.log("ADDALLTOLIBRARY, after adding all files", xbmc.LOGINFO)
    ## compare list of old files with list of new files, clean up library for files which do no longer exist
    for file in old_files.keys() - new_files.keys():
        # files do no longer exist -> delete
        xbmcvfs.delete(file)
        file_base, ext = os.path.splitext(file)
        if ext != ".strm" and ext != ".nfo": xbmcvfs.delete(file_base + ".edl")
# delete all empty directries
    recursive_delete_empty_dirs(constants.LIBRARY_MOVIES)
Exemplo n.º 40
0
def download(link, episode=""):
    subtitle_list = []
    exts = [".srt", ".sub", ".txt", ".smi", ".ssa", ".ass"]
    downloadlink_pattern = "...<a href=\"(.+?)\" rel=\"nofollow\" onclick=\"DownloadSubtitle"

    uid = uuid.uuid4()
    tempdir = os.path.join(TEMP, unicode(uid))
    xbmcvfs.mkdirs(tempdir)

    content, response_url = geturl(link)
    match = re.compile(downloadlink_pattern).findall(content)
    if match:
        downloadlink = main_url + match[0]
        viewstate = 0
        previouspage = 0
        subtitleid = 0
        typeid = "zip"
        filmid = 0

        postparams = urllib.urlencode(
            {'__EVENTTARGET': 's$lc$bcr$downloadLink', '__EVENTARGUMENT': '', '__VIEWSTATE': viewstate,
             '__PREVIOUSPAGE': previouspage, 'subtitleId': subtitleid, 'typeId': typeid, 'filmId': filmid})

        useragent = ("User-Agent=Mozilla/5.0 (Windows; U; Windows NT 6.1; en-US; rv:1.9.2.3) "
                       "Gecko/20100401 Firefox/3.6.3 ( .NET CLR 3.5.30729)")
        headers = {'User-Agent': useragent, 'Referer': link}
        log(__name__, "Fetching subtitles using url '%s' with referer header '%s' and post parameters '%s'" % (
            downloadlink, link, postparams))
        request = urllib2.Request(downloadlink, postparams, headers)
        response = urllib2.urlopen(request)

        if response.getcode() != 200:
            log(__name__, "Failed to download subtitle file")
            return subtitle_list

        local_tmp_file = os.path.join(tempdir, "subscene.xxx")
        packed = False

        try:
            log(__name__, "Saving subtitles to '%s'" % local_tmp_file)
            local_file_handle = xbmcvfs.File(local_tmp_file, "wb")
            local_file_handle.write(response.read())
            local_file_handle.close()

            # Check archive type (rar/zip/else) through the file header (rar=Rar!, zip=PK)
            myfile = xbmcvfs.File(local_tmp_file, "rb")
            myfile.seek(0,0)
            if myfile.read(1) == 'R':
                typeid = "rar"
                packed = True
                log(__name__, "Discovered RAR Archive")
            else:
                myfile.seek(0,0)
                if myfile.read(1) == 'P':
                    typeid = "zip"
                    packed = True
                    log(__name__, "Discovered ZIP Archive")
                else:
                    typeid = "srt"
                    packed = False
                    log(__name__, "Discovered a non-archive file")
            myfile.close()
            local_tmp_file = os.path.join(tempdir, "subscene." + typeid)
            xbmcvfs.rename(os.path.join(tempdir, "subscene.xxx"), local_tmp_file)
            log(__name__, "Saving to %s" % local_tmp_file)
        except:
            log(__name__, "Failed to save subtitle to %s" % local_tmp_file)

        if packed:
            xbmc.sleep(500)
            xbmc.executebuiltin(('XBMC.Extract("%s","%s")' % (local_tmp_file, tempdir,)).encode('utf-8'), True)

        episode_pattern = None
        if episode != '':
            episode_pattern = re.compile(get_episode_pattern(episode), re.IGNORECASE)

        for dir in xbmcvfs.listdir(tempdir)[0]:
            for file in xbmcvfs.listdir(os.path.join(tempdir, dir))[1]:
                if os.path.splitext(file)[1] in exts:
                    log(__name__, 'match '+episode+' '+file)
                    if episode_pattern and not episode_pattern.search(file):
                        continue
                    log(__name__, "=== returning subtitle file %s" % file)
                    subtitle_list.append(os.path.join(tempdir, dir, file))

        for file in xbmcvfs.listdir(tempdir)[1]:
            if os.path.splitext(file)[1] in exts:
                log(__name__, 'match '+episode+' '+file)
                if episode_pattern and not episode_pattern.search(file):
                    continue
                log(__name__, "=== returning subtitle file %s" % file)
                subtitle_list.append(os.path.join(tempdir, file))

        if len(subtitle_list) == 0:
            if episode:
                _xbmc_notification(32002)
            else:
                _xbmc_notification(32003)

    return subtitle_list
Exemplo n.º 41
0
def rmtree(path):
    if isinstance(path, unicode):
        path = path.encode('utf-8')
    dirs, files = xbmcvfs.listdir(path)
    for dir in dirs:
        rmtree(os.path.join(path, dir))
    for file in files:
        xbmcvfs.delete(os.path.join(path, file))
    xbmcvfs.rmdir(path)


try:
    rmtree(TEMP)
except:
    pass
xbmcvfs.mkdirs(TEMP)


def find_movie(content, title, year):
    found_urls = {}
    found_movies = []

    h = HTMLParser.HTMLParser()
    for secmatches in re.finditer(search_section_pattern, content, re.IGNORECASE | re.DOTALL):
        log(__name__, secmatches.group('section'))
        for matches in re.finditer(movie_season_pattern, secmatches.group('content'), re.IGNORECASE | re.DOTALL):
            if matches.group('link') in found_urls:
                if secmatches.group('section') == 'close':
                    found_movies[found_urls[matches.group('link')]]['is_close'] = True
                if secmatches.group('section') == 'exact':
                    found_movies[found_urls[matches.group('link')]]['is_exact'] = True
Exemplo n.º 42
0
if __name__ == "__main__":

    log("#############################################################",
        xbmc.LOGNOTICE)
    for credit in __cdam__.credits():
        log("#  %-55s  #" % credit, xbmc.LOGNOTICE)
    log("#############################################################",
        xbmc.LOGNOTICE)

    log("Looking for settings.xml", xbmc.LOGNOTICE)
    if not xbmcvfs.exists(__cdam__.file_settings_xml()
                          ):  # Open Settings if settings.xml does not exists
        log("settings.xml File not found, creating path and opening settings",
            xbmc.LOGNOTICE)
        xbmcvfs.mkdirs(__cdam__.path_profile())
        __cfg__.open()
        soft_exit = True

    cu.settings_to_log(__cdam__.file_settings_xml())
    script_mode, provided_mbid, provided_dbid, media_type = get_script_mode()

    if xbmcgui.Window(10000).getProperty("cdart_manager_running") == "True":
        log("cdART Manager Already running, exiting...", xbmc.LOGNOTICE)
        soft_exit = True
    else:
        xbmcgui.Window(10000).setProperty("cdart_manager_running", "True")

    if not soft_exit:
        try:
            if __cfg__.enable_all_artists():
Exemplo n.º 43
0
def backup():
    ''' Jellyfin backup.
    '''
    from helper.utils import delete_folder, copytree

    path = settings('backupPath')
    folder_name = "Kodi%s.%s" % (xbmc.getInfoLabel('System.BuildVersion')[:2],
                                 xbmc.getInfoLabel('System.Date(dd-mm-yy)'))
    folder_name = dialog("input", heading=_(33089), defaultt=folder_name)

    if not folder_name:
        return

    backup = os.path.join(path, folder_name)

    if xbmcvfs.exists(backup + '/'):
        if not dialog("yesno", heading="{jellyfin}", line1=_(33090)):

            return backup()

        delete_folder(backup)

    addon_data = xbmc.translatePath(
        "special://profile/addon_data/plugin.video.jellyfin").decode('utf-8')
    destination_data = os.path.join(backup, "addon_data",
                                    "plugin.video.jellyfin")
    destination_databases = os.path.join(backup, "Database")

    if not xbmcvfs.mkdirs(path) or not xbmcvfs.mkdirs(destination_databases):

        LOG.info("Unable to create all directories")
        dialog("notification",
               heading="{jellyfin}",
               icon="{jellyfin}",
               message=_(33165),
               sound=False)

        return

    copytree(addon_data, destination_data)

    databases = Objects().objects

    db = xbmc.translatePath(databases['jellyfin']).decode('utf-8')
    xbmcvfs.copy(db, os.path.join(destination_databases,
                                  db.rsplit('\\', 1)[1]))
    LOG.info("copied jellyfin.db")

    db = xbmc.translatePath(databases['video']).decode('utf-8')
    filename = db.rsplit('\\', 1)[1]
    xbmcvfs.copy(db, os.path.join(destination_databases, filename))
    LOG.info("copied %s", filename)

    if settings('enableMusic.bool'):

        db = xbmc.translatePath(databases['music']).decode('utf-8')
        filename = db.rsplit('\\', 1)[1]
        xbmcvfs.copy(db, os.path.join(destination_databases, filename))
        LOG.info("copied %s", filename)

    LOG.info("backup completed")
    dialog("ok", heading="{jellyfin}", line1="%s %s" % (_(33091), backup))
def Download(url, filename, pack, language):  # standard input
    # Create some variables
    subtitles = []
    random = uuid.uuid4().hex
    extractPath = os.path.join(__temp__, "Extracted")

    cleanDirectory(__temp__)
    if not xbmcvfs.exists(extractPath):
        xbmcvfs.mkdirs(extractPath)

    FileContent, FileExt = LTV.Download(url)

    fname = "%s.%s" % (os.path.join(__temp__, random), FileExt)

    with open(fname, 'wb') as f:
        f.write(FileContent)

    translated_archive_url = 'archive://%s' % urllib.quote_plus(
        xbmc.translatePath(fname))
    extractedFileList, success = extractArchiveToFolder(
        translated_archive_url, extractPath)

    files = xbmc_walk(extractPath)

    temp = []
    for file in files:
        sub = urllib.unquote_plus(file)
        sub, ext = os.path.splitext(os.path.basename(file))
        sub_striped = LTV.CleanLTVTitle(sub)
        Ratio = LTV.CalculateRatio(sub_striped, LTV.CleanLTVTitle(filename))
        temp.append([Ratio, file, sub, ext])

    subtitles = sorted(temp, reverse=True)
    outputSub = []

    if len(subtitles) > 1:
        if pack:
            subtitles.append(["pack", "pack", __language__(32010), ""])
        dialog = xbmcgui.Dialog()
        sel = dialog.select(
            "%s\n%s" % (__language__(32001).encode("utf-8"), filename),
            [os.path.basename(b) for a, b, c, d in subtitles])
        if sel >= 0:
            subSelected = subtitles[sel][1]

            # Handling package import
            if subtitles[sel][0] == "pack":
                dir = os.path.dirname(
                    urllib.unquote(
                        xbmc.Player().getPlayingFile().decode('utf-8')))
                for f in xbmc_walk(dir):
                    if os.path.splitext(f)[1] in [
                            ".mkv", ".avi", ".vob", ".mov", ".mp4"
                    ]:
                        for x, s in subtitles:
                            se, fe = 0, 1
                            if re.search(r"s\d{2}e\d{2}", s.lower()):
                                se = re.findall(r"s\d{2}e\d{2}", s.lower())[0]
                            if re.search(r"s\d{2}e\d{2}", f.lower()):
                                fe = re.findall(r"s\d{2}e\d{2}", f.lower())[0]
                            if se == fe:
                                if os.path.basename(f) == os.path.basename(
                                        filename):
                                    outputSub.append(s)
                                name = os.path.splitext(f)[0]
                                ext = os.path.splitext(s)[1]
                                lang = "pt" if re.search(
                                    r"Portuguese", language) else "en"
                                out = "%s.%s%s" % (name, lang, ext)
                                xbmcvfs.copy(s, out)

            temp_sel = os.path.join(extractPath,
                                    "%s.%s" % (random, subtitles[sel][3]))
            xbmcvfs.copy(subSelected, temp_sel)
            outputSub.append(temp_sel)
    elif len(subtitles) == 1:
        subSelected = subtitles[0][1]
        temp_sel = os.path.join(extractPath,
                                "%s.%s" % (random, subtitles[0][3]))
        xbmcvfs.copy(subSelected, temp_sel)
        outputSub.append(temp_sel)

    return outputSub
Exemplo n.º 45
0
    def __init__(self):
        self._parse_argv()
        # If there are no custom library nodes in the profile directory, copy them from the Kodi install
        targetDir = os.path.join( xbmc.translatePath( "special://profile".decode('utf-8') ), "library", ltype )
        if True:
            if not os.path.exists( targetDir ):
                xbmcvfs.mkdirs( targetDir )
                originDir = os.path.join( xbmc.translatePath( "special://xbmc".decode( "utf-8" ) ), "system", "library", ltype )
                dirs, files = xbmcvfs.listdir( originDir )
                self.copyNode( dirs, files, targetDir, originDir )
        else:
            xbmcgui.Dialog().ok(ADDONNAME, LANGUAGE( 30400 ) )
            print_exc
            xbmcplugin.endOfDirectory(handle=int(sys.argv[1]))
            return
        # Create data if not exists
        if not os.path.exists(DATAPATH):
            xbmcvfs.mkdir(DATAPATH)
        if "type" in self.PARAMS:
            # We're performing a specific action
            if self.PARAMS[ "type" ] == "delete":
                message = LANGUAGE( 30401 )
                if self.PARAMS[ "actionPath" ] == targetDir:
                    # Ask the user is they want to reset all nodes
                    message = LANGUAGE( 30402 )
                result = xbmcgui.Dialog().yesno(ADDONNAME, message )
                if result:
                    if self.PARAMS[ "actionPath" ].endswith( ".xml" ):
                        # Delete single file
                        xbmcvfs.delete( self.PARAMS[ "actionPath" ] )
                    else:
                        # Delete folder
                        RULE.deleteAllNodeRules( self.PARAMS[ "actionPath" ] )
                        shutil.rmtree( self.PARAMS[ "actionPath" ] )
                else:
                    return
            elif self.PARAMS[ "type" ] == "deletenode":
                result = xbmcgui.Dialog().yesno(ADDONNAME, LANGUAGE( 30403 ) )
                if result:
                    self.changeViewElement( self.PARAMS[ "actionPath" ], self.PARAMS[ "node" ], "" )
            elif self.PARAMS[ "type" ] == "editlabel":
                if self.PARAMS[ "label" ].isdigit():
                    label = xbmc.getLocalizedString( int( self.PARAMS[ "label" ] ) )
                else:
                    label = self.PARAMS[ "label" ]
                # Get new label from keyboard dialog
                keyboard = xbmc.Keyboard( label, LANGUAGE( 30300 ), False )
                keyboard.doModal()
                if ( keyboard.isConfirmed() ):
                    newlabel = keyboard.getText().decode( "utf-8" )
                    if newlabel != "" and newlabel != label:
                        # We've got a new label, update the xml file
                        self.changeViewElement( self.PARAMS[ "actionPath" ], "label", newlabel )
                else:
                    return
            elif self.PARAMS[ "type" ] == "editvisibility":
                currentVisibility = self.getRootAttrib( self.PARAMS[ "actionPath" ], "visible" )
                # Get new visibility from keyboard dialog
                keyboard = xbmc.Keyboard( currentVisibility, LANGUAGE( 30301 ), False )
                keyboard.doModal()
                if ( keyboard.isConfirmed() ):
                    newVisibility = keyboard.getText()
                    if newVisibility != currentVisibility:
                        # We've got a new label, update the xml file
                        self.changeRootAttrib( self.PARAMS[ "actionPath" ], "visible", newVisibility )
                else:
                    return
            elif self.PARAMS[ "type" ] == "moveNode":
                self.indexCounter = -1

                # Get existing nodes
                nodes = {}
                self.listNodes( self.PARAMS[ "actionPath" ], nodes )

                # Get updated order
                newOrder = moveNodes.getNewOrder( nodes, int( self.PARAMS[ "actionItem" ] ) )

                if newOrder is not None:
                    # Update the orders
                    for i, node in enumerate( newOrder, 1 ):
                        path = urllib.unquote( node[ 2 ] )
                        if node[ 3 ] == "folder":
                            path = os.path.join( urllib.unquote( node[ 2 ] ), "index.xml" )
                        self.changeRootAttrib( path, "order", str( i * 10 ) )

            elif self.PARAMS[ "type" ] == "newView":
                # Get new view name from keyboard dialog
                keyboard = xbmc.Keyboard( "", LANGUAGE( 30316 ), False )
                keyboard.doModal()
                if ( keyboard.isConfirmed() ):
                    newView = keyboard.getText().decode( "utf-8" )
                    if newView != "":
                        # Ensure filename is unique
                        filename = self.slugify( newView.lower().replace( " ", "" ) )
                        if os.path.exists( os.path.join( self.PARAMS[ "actionPath" ], filename + ".xml" ) ):
                            count = 0
                            while os.path.exists( os.path.join( self.PARAMS[ "actionPath" ], filename + "-" + str( count ) + ".xml" ) ):
                                count += 1
                            filename = filename + "-" + str( count )
                        # Create a new xml file
                        tree = xmltree.ElementTree( xmltree.Element( "node" ) )
                        root = tree.getroot()
                        subtree = xmltree.SubElement( root, "label" ).text = newView
                        # Add any node rules
                        RULE.addAllNodeRules( self.PARAMS[ "actionPath" ], root )
                        # Write the xml file
                        self.indent( root )
                        tree.write( os.path.join( self.PARAMS[ "actionPath" ], filename + ".xml" ), encoding="UTF-8" )
                else:
                    return
            elif self.PARAMS[ "type" ] == "newNode":
                # Get new node name from the keyboard dialog
                keyboard = xbmc.Keyboard( "", LANGUAGE( 30303 ), False )
                keyboard.doModal()
                if ( keyboard.isConfirmed() ):
                    newNode = keyboard.getText().decode( "utf8" )
                    if newNode == "":
                        return
                    # Ensure foldername is unique
                    foldername = self.slugify( newNode.lower().replace( " ", "" ) )
                    if os.path.exists( os.path.join( self.PARAMS[ "actionPath" ], foldername + os.pathsep ) ):
                        count = 0
                        while os.path.exists( os.path.join( self.PARAMS[ "actionPath" ], foldername + "-" + str( count ) + os.pathsep ) ):
                            count += 1
                        foldername = foldername + "-" + str( count )
                    foldername = os.path.join( self.PARAMS[ "actionPath" ], foldername )
                    # Create new node folder
                    xbmcvfs.mkdir( foldername )
                    # Create a new xml file
                    tree = xmltree.ElementTree( xmltree.Element( "node" ) )
                    root = tree.getroot()
                    subtree = xmltree.SubElement( root, "label" ).text = newNode
                    # Ask user if they want to import defaults
                    if ltype.startswith( "video" ):
                        defaultNames = [ xbmc.getLocalizedString( 231 ), xbmc.getLocalizedString( 342 ), xbmc.getLocalizedString( 20343 ), xbmc.getLocalizedString( 20389 ) ]
                        defaultValues = [ "", "movies", "tvshows", "musicvideos" ]
                        selected = xbmcgui.Dialog().select( LANGUAGE( 30304 ), defaultNames )
                    else:
                        selected = 0
                    # If the user selected some defaults...
                    if selected != -1 and selected != 0:
                        try:
                            # Copy those defaults across
                            originDir = os.path.join( xbmc.translatePath( "special://xbmc".decode( "utf-8" ) ), "system", "library", ltype, defaultValues[ selected ] )
                            dirs, files = xbmcvfs.listdir( originDir )
                            for file in files:
                                if file != "index.xml":
                                    xbmcvfs.copy( os.path.join( originDir, file), os.path.join( foldername, file ) )
                            # Open index.xml and copy values across
                            index = xmltree.parse( os.path.join( originDir, "index.xml" ) ).getroot()
                            if "visible" in index.attrib:
                                root.set( "visible", index.attrib.get( "visible" ) )
                            icon = index.find( "icon" )
                            if icon is not None:
                                xmltree.SubElement( root, "icon" ).text = icon.text
                        except:
                            print_exc()
                    # Write the xml file
                    self.indent( root )
                    tree.write( os.path.join( foldername, "index.xml" ), encoding="UTF-8" )
                else:
                    return
            elif self.PARAMS[ "type" ] == "rule":
                # Display list of all elements of a rule
                RULE.displayRule( self.PARAMS[ "actionPath" ], self.PATH, self.PARAMS[ "rule" ] )
                return
            elif self.PARAMS[ "type" ] == "editMatch":
                # Editing the field the rule is matched against
                RULE.editMatch( self.PARAMS[ "actionPath" ], self.PARAMS[ "rule" ], self.PARAMS[ "content"], self.PARAMS[ "default" ] )
            elif self.PARAMS[ "type" ] == "editOperator":
                # Editing the operator of a rule
                RULE.editOperator( self.PARAMS[ "actionPath" ], self.PARAMS[ "rule" ], self.PARAMS[ "group" ], self.PARAMS[ "default" ] )
            elif self.PARAMS[ "type" ] == "editValue":
                # Editing the value of a rule
                RULE.editValue( self.PARAMS[ "actionPath" ], self.PARAMS[ "rule" ] )
            elif self.PARAMS[ "type" ] == "browseValue":
                # Browse for the new value of a rule
                RULE.browse( self.PARAMS[ "actionPath" ], self.PARAMS[ "rule" ], self.PARAMS[ "match" ], self.PARAMS[ "content" ] )
            elif self.PARAMS[ "type" ] == "deleteRule":
                # Delete a rule
                RULE.deleteRule( self.PARAMS[ "actionPath" ], self.PARAMS[ "rule" ] )
            elif self.PARAMS[ "type" ] == "editRulesMatch":
                # Editing whether any or all rules must match
                ATTRIB.editMatch( self.PARAMS[ "actionPath" ] )
            # --- Edit order-by ---
            elif self.PARAMS[ "type" ] == "orderby":
                # Display all elements of order by
                ORDERBY.displayOrderBy( self.PARAMS[ "actionPath" ] )
                return
            elif self.PARAMS[ "type" ] == "editOrderBy":
                ORDERBY.editOrderBy( self.PARAMS[ "actionPath" ], self.PARAMS[ "content" ], self.PARAMS[ "default" ] )
            elif self.PARAMS[ "type" ] == "editOrderByDirection":
                ORDERBY.editDirection( self.PARAMS[ "actionPath" ], self.PARAMS[ "default" ] )
            # --- Edit paths ---
            elif self.PARAMS[ "type" ] == "addPath":
                ATTRIB.addPath( self.PARAMS[ "actionPath" ] )
            elif self.PARAMS[ "type" ] == "editPath":
                ATTRIB.editPath( self.PARAMS[ "actionPath" ], self.PARAMS[ "value" ] )
            elif self.PARAMS[ "type" ] == "pathRule":
                PATHRULE.displayRule( self.PARAMS[ "actionPath" ], int( self.PARAMS[ "rule" ] ) )
                return
            elif self.PARAMS[ "type" ] == "deletePathRule":
                ATTRIB.deletePathRule( self.PARAMS[ "actionPath" ], int( self.PARAMS[ "rule" ] ) )
            elif self.PARAMS[ "type" ] == "editPathMatch":
                # Editing the field the rule is matched against
                PATHRULE.editMatch( self.PARAMS[ "actionPath" ], int( self.PARAMS[ "rule" ] ) )
            elif self.PARAMS[ "type" ] == "editPathValue":
                # Editing the value of a rule
                PATHRULE.editValue( self.PARAMS[ "actionPath" ], int( self.PARAMS[ "rule" ] ) )
            elif self.PARAMS[ "type" ] == "browsePathValue":
                # Browse for the new value of a rule
                PATHRULE.browse( self.PARAMS[ "actionPath" ], int( self.PARAMS[ "rule" ] ) )
            # --- Edit other attribute of view ---
            #  > Content
            elif self.PARAMS[ "type" ] == "editContent":
                ATTRIB.editContent( self.PARAMS[ "actionPath" ], "" ) # No default to pass, yet!
            #  > Grouping
            elif self.PARAMS[ "type" ] == "editGroup":
                ATTRIB.editGroup( self.PARAMS[ "actionPath" ], self.PARAMS[ "content" ], "" )
            #  > Limit
            elif self.PARAMS[ "type" ] == "editLimit":
                ATTRIB.editLimit( self.PARAMS[ "actionPath" ], self.PARAMS[ "value" ] )
            #  > Icon (also for node)
            elif self.PARAMS[ "type" ] == "editIcon":
                ATTRIB.editIcon( self.PARAMS[ "actionPath" ], self.PARAMS[ "value" ] )
            elif self.PARAMS[ "type" ] == "browseIcon":
                ATTRIB.browseIcon( self.PARAMS[ "actionPath" ] )
            # Refresh the listings and exit
            xbmc.executebuiltin("Container.Refresh")
            return
        if self.PATH.endswith( ".xml" ):
            self.RulesList()
        else:
            self.NodesList(targetDir)
Exemplo n.º 46
0
 def _create_db_path(self):
     if not xbmcvfs.exists(os.path.dirname(self.path)):
         xbmcvfs.mkdirs(os.path.dirname(self.path))
Exemplo n.º 47
0
def makedirs(path):
    xbmcvfs.mkdirs(path)
Exemplo n.º 48
0
    def addRecordingToLibrary(self, libraryPath, filename, current_files,
                              isMovie, nfoUrl):
        if len(self.getTsFiles()) == 0: return
        self.updateComskip()
        xbmcvfs.mkdirs(libraryPath)
        # can we use symlinks? (Otherwisae, edl / comskip does not work)
        use_symlinks = sys.platform.startswith(
            'linux') and self.getTsFiles()[0].startswith('/')
        use_symlinks = use_symlinks and (isMovie
                                         or len(self.getTsFiles()) == 1)
        # extension of the new file / new symbolic link (.ts or .vdr or .strm)
        ext = os.path.splitext(self.getTsFiles()[0])[1]
        if not use_symlinks: ext = ".strm"
        # basename of the new file / new symbolic link
        sanTitle = re.sub(r'[/\\?%*:|"<>]', '-', filename)
        base_name = os.path.join(libraryPath, sanTitle)
        # create a unique basename, in case of duplicates
        i = 1
        strmFileName = base_name + ext
        strmFileNameA = base_name + " part1" + ext
        while strmFileName in current_files or strmFileNameA in current_files:
            i = i + 1
            strmFileName = base_name + str(i) + ext
            strmFileNameA = base_name + str(i) + " part1" + ext
        if i > 1: base_name = base_name + str(i)
        # create nfo file
        if nfoUrl != "":
            if isMovie: nfoFileName = base_name + ".nfo"
            else: nfoFileName = os.path.join(libraryPath, "tvshow.nfo")
            xbmcvfs.delete(nfoFileName)
            current_files[nfoFileName] = True
            with xbmcvfs.File(nfoFileName, "w") as f_nfo:
                try:
                    f_nfo.write(nfoUrl)
                except:
                    xbmc.log("Cannot open for write: " + str(nfoFileName),
                             xbmc.LOGERROR)
        if use_symlinks:
            # create the symlinks
            stack_number = ""
            i = 1
            for tsFile in self.getTsFiles():
                if len(self.getTsFiles()) > 1: stack_number = " part" + str(i)
                i = i + 1
                strmFileName = base_name + stack_number + ext
                edlFileName = base_name + stack_number + ".edl"
                xbmcvfs.delete(strmFileName)
                xbmcvfs.delete(edlFileName)
                try:
                    os.symlink(tsFile, strmFileName)
                    os.symlink(
                        os.path.splitext(tsFile)[0] + ".edl", edlFileName)
                except:
                    xbmc.log("Cannot create symlink: " + str(strmFileName),
                             xbmc.LOGERROR)
                    return -1
                try:
                    os.utime(strmFileName,
                             times=(datetime.datetime.now().timestamp(),
                                    self.RecordingTime.timestamp()))
                except:
                    xbmc.log(
                        "Cannot update time of symlink: " + str(strmFileName),
                        xbmc.LOGERROR)
                current_files[strmFileName] = True
        else:
            # symlinks are not supported, use strm file
            strmFileName = base_name + ".strm"
            xbmcvfs.delete(strmFileName)
            with xbmcvfs.File(strmFileName, "w") as f_strm:
                try:
                    plu = constants.BASE_URL + '?' + urllib.parse.urlencode(
                        {
                            'mode': 'play',
                            'recordingFolder': self.path
                        })
                    f_strm.write(plu)
## use the plugin to play files with multiple *.ts files. Putting all these ts files in an strm file is broken for too many ts files
#           f_strm.write(self.getStackUrl())
                except:
                    xbmc.log("Cannot open for write: " + str(strmFileName),
                             xbmc.LOGERROR)
                    return -1
            try:
                os.utime(strmFileName,
                         times=(datetime.datetime.now().timestamp(),
                                self.RecordingTime.timestamp()))
            except:
                xbmc.log(
                    "Cannot update time of strm file: " + str(strmFileName),
                    xbmc.LOGERROR)
            current_files[strmFileName] = True
Exemplo n.º 49
0
    if not os.path.exists(ADDONS): os.makedirs(ADDONS)
    newpath = xbmc.translatePath(
        os.path.join('special://home/addons/', ADDONID))
    if os.path.exists(newpath):
        wiz.log("Folder already exists, cleaning House", xbmc.LOGNOTICE)
        wiz.cleanHouse(newpath)
        wiz.removeFolder(newpath)
    try:
        wiz.copytree(ADDONPATH, newpath)
    except Exception, e:
        pass
    wiz.forceUpdate(True)

try:
    mybuilds = xbmc.translatePath(MYBUILDS)
    if not os.path.exists(mybuilds): xbmcvfs.mkdirs(mybuilds)
except:
    pass

wiz.log("[Auto Install Repo] Started", xbmc.LOGNOTICE)
if AUTOINSTALL == 'Yes' and not os.path.exists(os.path.join(ADDONS, REPOID)):
    workingxml = wiz.workingURL(REPOADDONXML)
    if workingxml == True:
        ver = wiz.parseDOM(wiz.openURL(REPOADDONXML),
                           'addon',
                           ret='version',
                           attrs={'id': REPOID})
        if len(ver) > 0:
            installzip = '%s-%s.zip' % (REPOID, ver[0])
            workingrepo = wiz.workingURL(REPOZIPURL + installzip)
            if workingrepo == True:
Exemplo n.º 50
0

class MyMonitor(xbmc.Monitor):
    def __init__(self, *args, **kwargs):
        xbmc.Monitor.__init__(self)

    def onSettingsChanged(self):
        writeconfig()


# addon
__addon__ = xbmcaddon.Addon(id='service.net-snmp')
__addonpath__ = xbmc.translatePath(__addon__.getAddonInfo('path'))
__addonhome__ = xbmc.translatePath(__addon__.getAddonInfo('profile'))
if not xbmcvfs.exists(xbmc.translatePath(__addonhome__ + 'share/snmp/')):
    xbmcvfs.mkdirs(xbmc.translatePath(__addonhome__ + 'share/snmp/'))
config = xbmc.translatePath(__addonhome__ + 'share/snmp/snmpd.conf')
persistent = xbmc.translatePath(__addonhome__ + 'snmpd.conf')


def writeconfig():
    system("systemctl stop service.net-snmp.service")
    community = __addon__.getSetting("COMMUNITY")
    location = __addon__.getSetting("LOCATION")
    contact = __addon__.getSetting("CONTACT")
    snmpversion = __addon__.getSetting("SNMPVERSION")
    cputemp = __addon__.getSetting("CPUTEMP")
    gputemp = __addon__.getSetting("GPUTEMP")

    if xbmcvfs.exists(persistent):
        xbmcvfs.delete(persistent)
Exemplo n.º 51
0
    dataPath, 'my_TLC_favourites.txt').encode('utf-8').decode('utf-8')
defaultFanart = os.path.join(addonPath, 'fanart.jpg')
icon = os.path.join(addonPath, 'icon.png')
spPIC = os.path.join(addonPath, 'resources', 'media',
                     '').encode('utf-8').decode('utf-8')
useThumbAsFanart = addon.getSetting("useThumbAsFanart") == "true"
enableAdjustment = addon.getSetting("show_settings") == "true"
enableInputstream = addon.getSetting("inputstream") == "true"
baseURL = "https://www.tlc.de/"

xbmcplugin.setContent(int(sys.argv[1]), 'tvshows')

if xbmcvfs.exists(temp) and os.path.isdir(temp):
    shutil.rmtree(temp, ignore_errors=True)
    xbmc.sleep(500)
xbmcvfs.mkdirs(temp)
cookie = os.path.join(temp, 'cookie.lwp')
cj = LWPCookieJar()

if xbmcvfs.exists(cookie):
    cj.load(cookie, ignore_discard=True, ignore_expires=True)


def py2_enc(s, encoding='utf-8'):
    if PY2:
        if not isinstance(s, basestring):
            s = str(s)
        s = s.encode(encoding) if isinstance(s, unicode) else s
    return s

Exemplo n.º 52
0
def download_media(url, path, file_name, translations, progress=None):
    try:
        if progress is None:
            progress = int(kodi.get_setting('down_progress'))

        i18n = translations.i18n
        active = not progress == PROGRESS.OFF
        background = progress == PROGRESS.BACKGROUND

        with kodi.ProgressDialog(kodi.get_name(),
                                 i18n('downloading') % (file_name),
                                 background=background,
                                 active=active) as pd:
            try:
                headers = dict([
                    item.split('=') for item in (url.split('|')[1]).split('&')
                ])
                for key in headers:
                    headers[key] = urllib.unquote(headers[key])
            except:
                headers = {}
            if 'User-Agent' not in headers: headers['User-Agent'] = BROWSER_UA
            request = urllib2.Request(url.split('|')[0], headers=headers)
            response = urllib2.urlopen(request)
            if 'Content-Length' in response.info():
                content_length = int(response.info()['Content-Length'])
            else:
                content_length = 0

            file_name += '.' + get_extension(url, response)
            full_path = os.path.join(path, file_name)
            logger.log('Downloading: %s -> %s' % (url, full_path),
                       log_utils.LOGDEBUG)

            path = kodi.translate_path(xbmc.makeLegalFilename(path))
            try:
                try:
                    xbmcvfs.mkdirs(path)
                except:
                    os.makedirs(path)
            except Exception as e:
                logger.log('Path Create Failed: %s (%s)' % (e, path),
                           log_utils.LOGDEBUG)

            if not path.endswith(os.sep): path += os.sep
            if not xbmcvfs.exists(path):
                raise Exception(i18n('failed_create_dir'))

            file_desc = xbmcvfs.File(full_path, 'w')
            total_len = 0
            cancel = False
            while True:
                data = response.read(CHUNK_SIZE)
                if not data:
                    break

                if pd.is_canceled():
                    cancel = True
                    break

                total_len += len(data)
                if not file_desc.write(data):
                    raise Exception(i18n('failed_write_file'))

                percent_progress = (
                    total_len
                ) * 100 / content_length if content_length > 0 else 0
                logger.log(
                    'Position : %s / %s = %s%%' %
                    (total_len, content_length, percent_progress),
                    log_utils.LOGDEBUG)
                pd.update(percent_progress)

            file_desc.close()

        if not cancel:
            kodi.notify(msg=i18n('download_complete') % (file_name),
                        duration=5000)
            logger.log('Download Complete: %s -> %s' % (url, full_path),
                       log_utils.LOGDEBUG)

    except Exception as e:
        logger.log(
            'Error (%s) during download: %s -> %s' % (str(e), url, file_name),
            log_utils.LOGERROR)
        kodi.notify(msg=i18n('download_error') % (str(e), file_name),
                    duration=5000)
Exemplo n.º 53
0
def make_list(imdb_ids, order, list_type, export):
    if export == "True":
        xbmcvfs.mkdirs(
            'special://profile/addon_data/plugin.video.imdb.watchlists/Movies')
        xbmcvfs.mkdirs(
            'special://profile/addon_data/plugin.video.imdb.watchlists/TV')
    items = []
    for imdb_id in order:
        if plugin.get_setting(
                'hide_duplicates') == "true" and existInKodiLibrary(imdb_id):
            continue
        imdb_data = imdb_ids[imdb_id]
        title = imdb_data['title']
        year = imdb_data['year']
        type = imdb_data['type']
        plot = imdb_data['plot']
        cast = imdb_data['cast']
        thumbnail = imdb_data['thumbnail']
        rating = imdb_data['rating']
        votes = imdb_data['votes']
        genres = imdb_data['genres']
        certificate = imdb_data['certificate']
        runtime = imdb_data['runtime']

        meta_url = ''
        if type == "series":  #TODO episode
            trakt_type = 'shows'
            meta_url = "plugin://plugin.video.imdb.watchlists/meta_tvdb/%s/%s" % (
                imdb_id, urllib.quote_plus(title.encode("utf8")))
        elif type == "featureFilm":
            trakt_type = 'movies'
            meta_url = 'plugin://%s/movies/play/imdb/%s/library' % (
                plugin.get_setting('catchup.plugin').lower(), imdb_id)
        context_items = []
        try:
            if xbmcaddon.Addon('plugin.program.super.favourites'):
                context_items.append((
                    'iSearch',
                    'ActivateWindow(%d,"plugin://%s/?mode=%d&keyword=%s",return)'
                    % (10025, 'plugin.program.super.favourites', 0,
                       urllib.quote_plus(title.encode("utf8")))))
        except:
            pass
        context_items.append(
            ('Add to Library', 'XBMC.RunPlugin(%s)' %
             (plugin.url_for('add_to_library',
                             imdb_id=imdb_id,
                             type=type,
                             title=urllib.quote_plus(title.encode("utf8")),
                             year=year))))
        context_items.append(
            ('Delete from Library', 'XBMC.RunPlugin(%s)' % (plugin.url_for(
                'delete_from_library', imdb_id=imdb_id, type=type))))
        context_items.append(('Add to Trakt Watchlist', 'XBMC.RunPlugin(%s)' %
                              (plugin.url_for('add_to_trakt_watchlist',
                                              type=trakt_type,
                                              imdb_id=imdb_id,
                                              title=title.encode("utf8")))))
        context_items.append(('Add to Trakt Collection', 'XBMC.RunPlugin(%s)' %
                              (plugin.url_for('add_to_trakt_collection',
                                              type=trakt_type,
                                              imdb_id=imdb_id,
                                              title=title.encode("utf8")))))
        try:
            if type == 'featureFilm' and xbmcaddon.Addon(
                    'plugin.video.couchpotato_manager'):
                context_items.append((
                    'Add to Couch Potato',
                    "XBMC.RunPlugin(plugin://plugin.video.couchpotato_manager/movies/add-by-id/%s)"
                    % (imdb_id)))
        except:
            pass
        try:
            if type == 'series' and xbmcaddon.Addon('plugin.video.sickrage'):
                context_items.append((
                    'Add to Sickrage',
                    "XBMC.RunPlugin(plugin://plugin.video.sickrage?action=addshow&&show_name=%s)"
                    % (urllib.quote_plus(title.encode("utf8")))))
        except:
            pass

        item = {
            'label': title,
            'path': meta_url,
            'thumbnail': thumbnail,
            'info': {
                'title': title,
                'genre': ','.join(genres),
                'code': imdb_id,
                'year': year,
                'rating': rating,
                'plot': plot,
                'mpaa': certificate,
                'cast': cast,
                'duration': runtime,
                'votes': votes
            },
            'context_menu': context_items,
            'replace_context_menu': False,
        }
        if list_type == "tv":
            if type == "series":  #TODO episode
                items.append(item)
        elif list_type == "movies":
            if type == "featureFilm":
                items.append(item)
        else:
            items.append(item)

        if export == "True":
            add_to_library(imdb_id, type, title, year)

    plugin.set_content('movies')
    plugin.add_sort_method(xbmcplugin.SORT_METHOD_UNSORTED)
    plugin.add_sort_method(xbmcplugin.SORT_METHOD_TITLE)
    return items
Exemplo n.º 54
0
 def __create_folder(self, basepath, folder):
     new_folder = os.path.join(basepath, folder)
     if not xbmcvfs.exists(new_folder):
         xbmcvfs.mkdirs(new_folder)
Exemplo n.º 55
0
import os
# import tempfile

from ..compat import is_win32, is_py3

import xbmc, xbmcvfs

xdg_cache = tmp_dir = xbmc.translatePath('special://profile/addon_data/script.module.streamlink.base')

if not xbmcvfs.exists(tmp_dir):
    xbmcvfs.mkdirs(tmp_dir)

if is_win32:

    try:
        from ctypes import windll, cast, c_ulong, c_void_p, byref
    except MemoryError:
        pass

    PIPE_ACCESS_OUTBOUND = 0x00000002
    PIPE_TYPE_BYTE = 0x00000000
    PIPE_READMODE_BYTE = 0x00000000
    PIPE_WAIT = 0x00000000
    PIPE_UNLIMITED_INSTANCES = 255
    INVALID_HANDLE_VALUE = -1


class NamedPipe(object):

    def __init__(self, name):
        self.fifo = None
Exemplo n.º 56
0
    displayADDON.getAddonInfo('path')).encode('utf-8').decode('utf-8')
displayA_Profile = xbmc.translatePath(
    displayADDON.getAddonInfo('profile')).encode('utf-8').decode('utf-8')
displayA_Temp = xbmc.translatePath(os.path.join(
    displayA_Profile, 'temp', '')).encode('utf-8').decode('utf-8')
background = os.path.join(displayA_Path, "bg.png")

#wid = xbmcgui.getCurrentWindowId()
#window=xbmcgui.Window(wid)
#window.show()

wait_time = 160  # 180 seconds = 3 minutes - wait at KODI start
#loop_time = 60  # 60 seconds = 1 minute - time when the process started again

if not xbmcvfs.exists(displayA_Temp):
    xbmcvfs.mkdirs(displayA_Temp)


def py2_enc(s, encoding='utf-8'):
    if PY2 and isinstance(s, unicode):
        s = s.encode(encoding)
    return s


def py2_uni(s, encoding='utf-8'):
    if PY2 and isinstance(s, str):
        s = unicode(s, encoding)
    return s


def translation(id):
Exemplo n.º 57
0
 def __create_sqlite_db(self):
     if not xbmcvfs.exists(os.path.dirname(self.db_path)):
         try:
             xbmcvfs.mkdirs(os.path.dirname(self.db_path))
         except:
             os.mkdir(os.path.dirname(self.db_path))
Exemplo n.º 58
0
def makepath(path):
        if xbmcvfs.exists(path):
            return xbmc.translatePath(path)
        xbmcvfs.mkdirs(path)
        return xbmc.translatePath(path)
Exemplo n.º 59
0
def create_dir(dirname):
    if not xbmcvfs.exists(dirname):
        xbmcvfs.mkdirs(dirname)
Exemplo n.º 60
0
def Download(url):
    if not xbmcvfs.exists(__temp__.replace('\\', '/')):
        xbmcvfs.mkdirs(__temp__)
    dirs, files = xbmcvfs.listdir(__temp__)

    for file in files:
        xbmcvfs.delete(os.path.join(__temp__, file.decode("utf-8")))

    subtitle_list = []
    try:
        #data = GetHttpData(url)
        if re.match('https://', url) == None:
            if re.match('http://', url) != None:
                url = 'https://' + url[7:]
            else:
                dialog = xbmcgui.Dialog()
                ok = dialog.ok('错误提示', '非法url')

        ifbangumiurl = re.match('https://www.bilibili.com/bangumi/play/ss',
                                url)
        ifvideourl = re.match('https://www.bilibili.com/video/', url)
        if ifbangumiurl or ifvideourl != None:
            if ifbangumiurl != None:
                ssid = re.search(r'ss[0-9]+', url)
                ssid = ssid.group()
                ssid = ssid[2:]
                r = GetHttpData(
                    'http://api.bilibili.com/pgc/web/season/section?season_id='
                    + ssid)
                j = json.loads(r)

                titles = []
                cids = []
                for p in range(len(j['result']['main_section']['episodes'])):
                    titles.append(
                        u'正片 - ' +
                        j['result']['main_section']['episodes'][p]['title'])
                    cids.append(
                        j['result']['main_section']['episodes'][p]['cid'])
                for index in range(len(j['result']['section'])):
                    duopname = j['result']['section'][index]['title']
                    for i in range(
                            len(j['result']['section'][index]['episodes'])):
                        titles.append(duopname + u' - ' +
                                      j['result']['section'][index]['episodes']
                                      [i]['title'])
                        cids.append(j['result']['section'][index]['episodes']
                                    [i]['cid'])

            if ifvideourl != None:
                bvid = ''
                aid = ''
                if re.search(r'[Bb]{1}[Vv]{1}[a-zA-Z0-9]+', url):
                    bvid = re.search(r'[Bb]{1}[Vv]{1}[a-zA-Z0-9]+', url)
                    bvid = bvid.group()
                    vurl = 'https://api.bilibili.com/x/web-interface/view?bvid=' + bvid
                if re.search('[aA]{1}[vV]{1}[0-9]+', url):
                    aid = re.search(r'[aA]{1}[vV]{1}[0-9]+', url)
                    aid = aid.group()
                    aid = aid[2:]
                    vurl = 'https://api.bilibili.com/x/web-interface/view?aid=' + aid
                r = GetHttpData(vurl)
                j = json.loads(r)
                #bvid = j['data']['pages'][0]['bvid']
                titles = []
                cids = []
                for p in range(len(j['data']['pages'])):
                    titles.append(j['data']['pages'][p]['part'])
                    cids.append(j['data']['pages'][p]['cid'])
            if len(titles) > 1:
                sel = xbmcgui.Dialog().select('请选择分集的弹幕', titles)
                if sel == -1:
                    sel = 0
            else:
                sel = 0
        r = requests.get('https://api.bilibili.com/x/v1/dm/list.so?oid=' +
                         str(cids[sel]))
        r.encoding = 'utf-8'
        data = r.text
        pDialog = xbmcgui.DialogProgress()
        pDialog.create('获取弹幕', '初始化...')
        pDialog.update(50, '获取弹幕成功...')
        # dialog = xbmcgui.Dialog()
        # dialog.textviewer('错误提示', str(data.encode('utf-8')))
    except:
        return []
    if len(data) < 1024:
        return []
    tmpfile = os.path.join(
        __temp__,
        "cid%s%s.ass" % (str(cids[sel]), os.path.splitext(url)[1])).replace(
            '\\', '/')
    # dialog = xbmcgui.Dialog()
    # dialog.textviewer('错误提示', str(tmpfile))
    with open(tmpfile, "wb") as subFile:
        subFile.write(data.encode('utf-8'))
    pDialog.update(75, '写入xml成功...')
    xbmc.sleep(500)
    xml2ass.Danmaku2ASS(tmpfile, tmpfile, 960, 540, duration_marquee=10.0)
    pDialog.update(100, '转换ass成功...')
    pDialog.close()
    subtitle_list.append(tmpfile)
    return subtitle_list