Example #1
0
    def makeDir(self, path):
        path = sp(path)
        try:
            if not os.path.isdir(path):
                os.makedirs(path, Env.getPermission('folder'))
                os.chmod(path, Env.getPermission('folder'))
            return True
        except Exception as e:
            log.error('Unable to create folder "%s": %s', (path, e))

        return False
Example #2
0
    def makeDir(self, path):
        path = sp(path)
        try:
            if not os.path.isdir(path):
                os.makedirs(path, Env.getPermission('folder'))
                os.chmod(path, Env.getPermission('folder'))
            return True
        except Exception as e:
            log.error('Unable to create folder "%s": %s', (path, e))

        return False
Example #3
0
 def makeDir(self, path):
     try:
         if not os.path.isdir(path):
             os.makedirs(path, Env.getPermission('folder'))
         return True
     except Exception, e:
         log.error('Unable to create folder "%s": %s' % (path, e))
Example #4
0
    def createFile(self, path, content, binary = False):
        path = sp(path)

        self.makeDir(os.path.dirname(path))

        if os.path.exists(path):
            log.debug('%s already exists, overwriting file with new version', path)

        write_type = 'w+' if not binary else 'w+b'

        # Stream file using response object
        if isinstance(content, requests.models.Response):

            # Write file to temp
            with open('%s.tmp' % path, write_type) as f:
                for chunk in content.iter_content(chunk_size = 1048576):
                    if chunk:  # filter out keep-alive new chunks
                        f.write(chunk)
                        f.flush()

            # Rename to destination
            os.rename('%s.tmp' % path, path)

        else:
            try:
                f = open(path, write_type)
                f.write(content)
                f.close()
                os.chmod(path, Env.getPermission('file'))
            except:
                log.error('Unable to write file "%s": %s', (path, traceback.format_exc()))
                if os.path.isfile(path):
                    os.remove(path)
Example #5
0
 def makeDir(self, path):
     try:
         if not os.path.isdir(path):
             os.makedirs(path, Env.getPermission('folder'))
         return True
     except Exception, e:
         log.error('Unable to create folder "%s": %s' % (path, e))
Example #6
0
    def _createType(self, meta_name, root, movie_info, group, file_type, i):  # Get file path
        camelcase_method = underscoreToCamel(file_type.capitalize())
        name = getattr(self, 'get' + camelcase_method + 'Name')(meta_name, root, i)

        if name and (self.conf('meta_' + file_type) or self.conf('meta_' + file_type) is None):

            # Get file content
            content = getattr(self, 'get' + camelcase_method)(movie_info = movie_info, data = group, i = i)
            if content:
                log.debug('Creating %s file: %s', (file_type, name))
                if os.path.isfile(content):
                    content = sp(content)
                    name = sp(name)

                    if not os.path.exists(os.path.dirname(name)):
                        os.makedirs(os.path.dirname(name))

                    shutil.copy2(content, name)
                    shutil.copyfile(content, name)

                    # Try and copy stats seperately
                    try: shutil.copystat(content, name)
                    except: pass
                else:
                    self.createFile(name, content)
                    group['renamed_files'].append(name)

                try:
                    os.chmod(sp(name), Env.getPermission('file'))
                except:
                    log.debug('Failed setting permissions for %s: %s', (name, traceback.format_exc()))
Example #7
0
    def createFile(self, path, content, binary=False):
        path = sp(path)

        self.makeDir(os.path.dirname(path))

        if os.path.exists(path):
            log.debug('%s already exists, overwriting file with new version',
                      path)

        write_type = 'w+' if not binary else 'w+b'

        # Stream file using response object
        if isinstance(content, requests.models.Response):

            # Write file to temp
            with open('%s.tmp' % path, write_type) as f:
                for chunk in content.iter_content(chunk_size=1048576):
                    if chunk:  # filter out keep-alive new chunks
                        f.write(chunk)
                        f.flush()

            # Rename to destination
            os.rename('%s.tmp' % path, path)

        else:
            try:
                f = open(path, write_type)
                f.write(content)
                f.close()
                os.chmod(path, Env.getPermission('file'))
            except:
                log.error('Unable to write file "%s": %s',
                          (path, traceback.format_exc()))
                if os.path.isfile(path):
                    os.remove(path)
Example #8
0
    def moveFile(self, old, dest, forcemove = False):
        dest = ss(dest)
        try:
            if forcemove:
                shutil.move(old, dest)
            elif self.conf('file_action') == 'hardlink':
                link(old, dest)
            elif self.conf('file_action') == 'symlink':
                symlink(old, dest)
            elif self.conf('file_action') == 'copy':
                shutil.copy(old, dest)
            elif self.conf('file_action') == 'move_symlink':
                shutil.move(old, dest)
                symlink(dest, old)
            else:
                shutil.move(old, dest)

            try:
                os.chmod(dest, Env.getPermission('file'))
                if os.name == 'nt' and self.conf('ntfs_permission'):
                    os.popen('icacls "' + dest + '"* /reset /T')
            except:
                log.error('Failed setting permissions for file: %s, %s', (dest, traceback.format_exc(1)))

        except OSError, err:
            # Copying from a filesystem with octal permission to an NTFS file system causes a permission error.  In this case ignore it.
            if not hasattr(os, 'chmod') or err.errno != errno.EPERM:
                raise
            else:
                if os.path.exists(dest):
                    os.unlink(old)
Example #9
0
    def _createType(self, meta_name, root, movie_info, group, file_type, i):  # Get file path
        camelcase_method = underscoreToCamel(file_type.capitalize())
        name = getattr(self, 'get' + camelcase_method + 'Name')(meta_name, root, i)

        if name and (self.conf('meta_' + file_type) or self.conf('meta_' + file_type) is None):

            # Get file content
            content = getattr(self, 'get' + camelcase_method)(movie_info = movie_info, data = group, i = i)
            if content:
                log.debug('Creating %s file: %s', (file_type, name))
                if os.path.isfile(content):
                    content = sp(content)
                    name = sp(name)

                    if not os.path.exists(os.path.dirname(name)):
                        os.makedirs(os.path.dirname(name))

                    shutil.copy2(content, name)
                    shutil.copyfile(content, name)

                    # Try and copy stats seperately
                    try: shutil.copystat(content, name)
                    except: pass
                else:
                    self.createFile(name, content)
                    group['renamed_files'].append(name)

                try:
                    os.chmod(sp(name), Env.getPermission('file'))
                except:
                    log.debug('Failed setting permissions for %s: %s', (name, traceback.format_exc()))
Example #10
0
    def create(self, message=None, group=None):
        if self.isDisabled(): return
        if not group: group = {}

        log.info('Creating %s metadata.', self.getName())

        # Update library to get latest info
        try:
            updated_library = fireEvent('library.update.movie',
                                        group['library']['identifier'],
                                        force=True,
                                        single=True)
            group['library'] = mergeDicts(group['library'], updated_library)
        except:
            log.error('Failed to update movie, before creating metadata: %s',
                      traceback.format_exc())

        root_name = self.getRootName(group)
        meta_name = os.path.basename(root_name)
        root = os.path.dirname(root_name)

        movie_info = group['library'].get('info')

        for file_type in ['nfo', 'thumbnail', 'fanart']:
            try:
                # Get file path
                name = getattr(self, 'get' + file_type.capitalize() + 'Name')(
                    meta_name, root)

                if name and (self.conf('meta_' + file_type)
                             or self.conf('meta_' + file_type) is None):

                    # Get file content
                    content = getattr(self, 'get' + file_type.capitalize())(
                        movie_info=movie_info, data=group)
                    if content:
                        log.debug('Creating %s file: %s', (file_type, name))
                        if os.path.isfile(content):
                            shutil.copy2(content, name)
                            shutil.copyfile(content, name)

                            # Try and copy stats seperately
                            try:
                                shutil.copystat(content, name)
                            except:
                                pass
                        else:
                            self.createFile(name, content)
                            group['renamed_files'].append(name)

                        try:
                            os.chmod(name, Env.getPermission('file'))
                        except:
                            log.debug('Failed setting permissions for %s: %s',
                                      (name, traceback.format_exc()))

            except:
                log.error('Unable to create %s file: %s',
                          (file_type, traceback.format_exc()))
Example #11
0
    def moveFile(self, old, dest, forcemove = False):
        dest = ss(dest)
        try:
            if forcemove:
                try:
                    os.chmod(old,0777)
                except: pass # ignore all error, if important will raise error later
                shutil.move(old, dest)
            elif self.conf('file_action') == 'copy':
                try:
                    os.chmod(old,0777)
                except: pass # ignore all error, if important will raise error later
                shutil.copy(old, dest)
            elif self.conf('file_action') == 'link':
                # First try to hardlink
                try:
                    log.debug('Hardlinking file "%s" to "%s"...', (old, dest))
                    link(old, dest)
                except:
                    # Try to simlink next
                    log.debug('Couldn\'t hardlink file "%s" to "%s". Simlinking instead. Error: %s. ', (old, dest, traceback.format_exc()))
                    shutil.copy(old, dest)
                    try:
                        symlink(dest, old + '.link')
                        os.unlink(old)
                        os.rename(old + '.link', old)
                    except:
                        log.error('Couldn\'t symlink file "%s" to "%s". Copied instead. Error: %s. ', (old, dest, traceback.format_exc()))
            else:
                try:
                    os.chmod(old,0777)
                except: pass # ignore all error, if important will raise error later
                shutil.move(old, dest)

            try:
                os.chmod(dest, Env.getPermission('file'))
                if os.name == 'nt' and self.conf('ntfs_permission'):
                    os.popen('icacls "' + dest + '"* /reset /T')
                if os.name != 'nt':
                    try:
                        uid = Env.getOwnership('user')
                        gid = Env.getOwnership('group')
                        os.chown(dest,uid,gid)
                    except:
                        log.error('Failed setting ownership for file: %s, %s', (dest, traceback.format_exc(1)))
            except:
                log.error('Failed setting permissions for file: %s, %s', (dest, traceback.format_exc(1)))

        except OSError, err:
            # Copying from a filesystem with octal permission to an NTFS file system causes a permission error.  In this case ignore it.
            if not hasattr(os, 'chmod') or err.errno != errno.EPERM:
                raise
            else:
                if os.path.exists(dest):
                    os.unlink(old)
Example #12
0
    def download(self, data=None, media=None, filedata=None):
        if not media:
            media = {}
        if not data:
            data = {}

        directory = self.conf("directory")
        if not directory or not os.path.isdir(directory):
            log.error("No directory set for blackhole %s download.", data.get("protocol"))
        else:
            try:
                if not filedata or len(filedata) < 50:
                    try:
                        if data.get("protocol") == "torrent_magnet":
                            filedata = self.magnetToTorrent(data.get("url"))
                            data["protocol"] = "torrent"
                    except:
                        log.error("Failed download torrent via magnet url: %s", traceback.format_exc())

                    if not filedata or len(filedata) < 50:
                        log.error("No nzb/torrent available: %s", data.get("url"))
                        return False

                file_name = self.createFileName(data, filedata, media)
                full_path = os.path.join(directory, file_name)

                if self.conf("create_subdir"):
                    try:
                        new_path = os.path.splitext(full_path)[0]
                        if not os.path.exists(new_path):
                            os.makedirs(new_path)
                            full_path = os.path.join(new_path, file_name)
                    except:
                        log.error("Couldnt create sub dir, reverting to old one: %s", full_path)

                try:
                    if not os.path.isfile(full_path):
                        log.info("Downloading %s to %s.", (data.get("protocol"), full_path))
                        with open(full_path, "wb") as f:
                            f.write(filedata)
                        os.chmod(full_path, Env.getPermission("file"))
                        return self.downloadReturnId("")
                    else:
                        log.info("File %s already exists.", full_path)
                        return self.downloadReturnId("")

                except:
                    log.error("Failed to download to blackhole %s", traceback.format_exc())
                    pass

            except:
                log.info("Failed to download file %s: %s", (data.get("name"), traceback.format_exc()))
                return False

        return False
Example #13
0
    def createFile(self, path, content, binary = False):

        self.makeDir(os.path.dirname(path))

        try:
            f = open(path, 'w' if not binary else 'wb')
            f.write(content)
            f.close()
            os.chmod(path, Env.getPermission('file'))
        except Exception, e:
            log.error('Unable writing to file "%s": %s' % (path, e))
Example #14
0
    def download(self, data = None, movie = None, filedata = None):
        if not movie: movie = {}
        if not data: data = {}

        directory = self.conf('directory')
        if not directory or not os.path.isdir(directory):
            log.error('No directory set for blackhole %s download.', data.get('protocol'))
        else:
            try:
                if not filedata or len(filedata) < 50:
                    try:
                        if data.get('protocol') == 'torrent_magnet':
                            filedata = self.magnetToTorrent(data.get('url'))
                            data['protocol'] = 'torrent'
                    except:
                        log.error('Failed download torrent via magnet url: %s', traceback.format_exc())

                    if not filedata or len(filedata) < 50:
                        log.error('No nzb/torrent available: %s', data.get('url'))
                        return False

                file_name = self.createFileName(data, filedata, movie)
                full_path = os.path.join(directory, file_name)

                if self.conf('create_subdir'):
                    try:
                        new_path = os.path.splitext(full_path)[0]
                        if not os.path.exists(new_path):
                            os.makedirs(new_path)
                            full_path = os.path.join(new_path, file_name)
                    except:
                        log.error('Couldnt create sub dir, reverting to old one: %s', full_path)

                try:
                    if not os.path.isfile(full_path):
                        log.info('Downloading %s to %s.', (data.get('protocol'), full_path))
                        with open(full_path, 'wb') as f:
                            f.write(filedata)
                        os.chmod(full_path, Env.getPermission('file'))
                        return True
                    else:
                        log.info('File %s already exists.', full_path)
                        return True

                except:
                    log.error('Failed to download to blackhole %s', traceback.format_exc())
                    pass

            except:
                log.info('Failed to download file %s: %s', (data.get('name'), traceback.format_exc()))
                return False

        return False
Example #15
0
    def createFile(self, path, content, binary=False):
        path = ss(path)

        self.makeDir(os.path.dirname(path))

        try:
            f = open(path, 'w+' if not binary else 'w+b')
            f.write(content)
            f.close()
            os.chmod(path, Env.getPermission('file'))
        except Exception, e:
            log.error('Unable writing to file "%s": %s', (path, e))
Example #16
0
    def download(self, data = None, media = None, filedata = None):
        if not media: media = {}
        if not data: data = {}

        directory = self.conf('directory')
        if not directory or not os.path.isdir(directory):
            log.error('No directory set for blackhole %s download.', data.get('protocol'))
        else:
            try:
                if not filedata or len(filedata) < 50:
                    try:
                        if data.get('protocol') == 'torrent_magnet':
                            filedata = self.magnetToTorrent(data.get('url'))
                            data['protocol'] = 'torrent'
                    except:
                        log.error('Failed download torrent via magnet url: %s', traceback.format_exc())

                    if not filedata or len(filedata) < 50:
                        log.error('No nzb/torrent available: %s', data.get('url'))
                        return False

                file_name = self.createFileName(data, filedata, media)
                full_path = os.path.join(directory, file_name)

                if self.conf('create_subdir'):
                    try:
                        new_path = os.path.splitext(full_path)[0]
                        if not os.path.exists(new_path):
                            os.makedirs(new_path)
                            full_path = os.path.join(new_path, file_name)
                    except:
                        log.error('Couldnt create sub dir, reverting to old one: %s', full_path)

                try:
                    if not os.path.isfile(full_path):
                        log.info('Downloading %s to %s.', (data.get('protocol'), full_path))
                        with open(full_path, 'wb') as f:
                            f.write(filedata)
                        os.chmod(full_path, Env.getPermission('file'))
                        return self.downloadReturnId('')
                    else:
                        log.info('File %s already exists.', full_path)
                        return self.downloadReturnId('')

                except:
                    log.error('Failed to download to blackhole %s', traceback.format_exc())
                    pass

            except:
                log.info('Failed to download file %s: %s', (data.get('name'), traceback.format_exc()))
                return False

        return False
Example #17
0
    def createFile(self, path, content, binary=False):
        path = ss(path)

        self.makeDir(os.path.dirname(path))

        try:
            f = open(path, "w" if not binary else "wb")
            f.write(content)
            f.close()
            os.chmod(path, Env.getPermission("file"))
        except Exception, e:
            log.error('Unable writing to file "%s": %s', (path, e))
Example #18
0
    def create(self, message = None, group = None):
        if self.isDisabled(): return
        if not group: group = {}

        log.info('Creating %s metadata.', self.getName())

        # Update library to get latest info
        try:
            updated_library = fireEvent('library.update.movie', group['library']['identifier'], extended = True, single = True)
            group['library'] = mergeDicts(group['library'], updated_library)
        except:
            log.error('Failed to update movie, before creating metadata: %s', traceback.format_exc())

        root_name = self.getRootName(group)
        meta_name = os.path.basename(root_name)
        root = os.path.dirname(root_name)

        movie_info = group['library'].get('info')

        for file_type in ['nfo', 'thumbnail', 'fanart']:
            try:
                # Get file path
                name = getattr(self, 'get' + file_type.capitalize() + 'Name')(meta_name, root)

                if name and (self.conf('meta_' + file_type) or self.conf('meta_' + file_type) is None):

                    # Get file content
                    content = getattr(self, 'get' + file_type.capitalize())(movie_info = movie_info, data = group)
                    if content:
                        log.debug('Creating %s file: %s', (file_type, name))
                        if os.path.isfile(content):
                            content = sp(content)
                            name = sp(name)

                            shutil.copy2(content, name)
                            shutil.copyfile(content, name)

                            # Try and copy stats seperately
                            try: shutil.copystat(content, name)
                            except: pass
                        else:
                            self.createFile(name, content)
                            group['renamed_files'].append(name)

                        try:
                            os.chmod(sp(name), Env.getPermission('file'))
                        except:
                            log.debug('Failed setting permissions for %s: %s', (name, traceback.format_exc()))

            except:
                log.error('Unable to create %s file: %s', (file_type, traceback.format_exc()))
Example #19
0
    def download(self, data=None, movie=None, filedata=None):
        if not movie: movie = {}
        if not data: data = {}

        directory = self.conf('directory')
        if not directory or not os.path.isdir(directory):
            log.error('No directory set for blackhole %s download.',
                      data.get('protocol'))
        else:
            try:
                if not filedata or len(filedata) < 50:
                    try:
                        if data.get('protocol') == 'torrent_magnet':
                            filedata = self.magnetToTorrent(data.get('url'))
                            data['protocol'] = 'torrent'
                    except:
                        log.error('Failed download torrent via magnet url: %s',
                                  traceback.format_exc())

                    if not filedata or len(filedata) < 50:
                        log.error('No nzb/torrent available: %s',
                                  data.get('url'))
                        return False

                fullPath = os.path.join(
                    directory, self.createFileName(data, filedata, movie))

                try:
                    if not os.path.isfile(fullPath):
                        log.info('Downloading %s to %s.',
                                 (data.get('protocol'), fullPath))
                        with open(fullPath, 'wb') as f:
                            f.write(filedata)
                        os.chmod(fullPath, Env.getPermission('file'))
                        return True
                    else:
                        log.info('File %s already exists.', fullPath)
                        return True

                except:
                    log.error('Failed to download to blackhole %s',
                              traceback.format_exc())
                    pass

            except:
                log.info('Failed to download file %s: %s',
                         (data.get('name'), traceback.format_exc()))
                return False

        return False
Example #20
0
    def moveFile(self, old, dest):
        try:
            shutil.move(old, dest)

            try:
                os.chmod(dest, Env.getPermission("folder"))
            except:
                log.error("Failed setting permissions for file: %s" % dest)

        except:
            log.error("Couldn't move file '%s' to '%s': %s" % (old, dest, traceback.format_exc()))
            raise Exception

        return True
Example #21
0
    def moveFile(self, old, dest):
        try:
            shutil.move(old, dest)

            try:
                os.chmod(dest, Env.getPermission('file'))
            except:
                log.error('Failed setting permissions for file: %s, %s', (dest, traceback.format_exc(1)))

        except:
            log.error('Couldn\'t move file "%s" to "%s": %s', (old, dest, traceback.format_exc()))
            raise Exception

        return True
Example #22
0
 def makeDir(self, path):
     path = ss(path)
     try:
         if not os.path.isdir(path):
             os.makedirs(path, Env.getPermission('folder'))
             if os.name != 'nt':
                 try:
                     uid = Env.getOwnership('user')
                     gid = Env.getOwnership('group')
                     os.chown(path,uid,gid)
                 except:
                     log.error('Failed setting ownership for folder: %s, %s', (path, traceback.format_exc(1)))
         return True
     except Exception, e:
         log.error('Unable to create folder "%s": %s', (path, e))
Example #23
0
    def moveFile(self, old, dest):
        dest = ss(dest)
        try:
            shutil.move(old, dest)

            try:
                os.chmod(dest, Env.getPermission('file'))
            except:
                log.error('Failed setting permissions for file: %s, %s', (dest, traceback.format_exc(1)))

        except OSError, err:
            # Copying from a filesystem with octal permission to an NTFS file system causes a permission error.  In this case ignore it.
            if not hasattr(os, 'chmod') or err.errno != errno.EPERM:
                raise
            else:
                if os.path.exists(dest):
                    os.unlink(old)
Example #24
0
    def createFile(self, path, content, binary = False):
        path = ss(path)

        self.makeDir(os.path.dirname(path))

        if os.path.exists(path):
            log.debug('%s already exists, overwriting file with new version', path)

        try:
            f = open(path, 'w+' if not binary else 'w+b')
            f.write(content)
            f.close()
            os.chmod(path, Env.getPermission('file'))
        except:
            log.error('Unable writing to file "%s": %s', (path, traceback.format_exc()))
            if os.path.isfile(path):
                os.remove(path)
Example #25
0
    def createFile(self, path, content, binary = False):
        path = sp(path)

        self.makeDir(os.path.dirname(path))

        if os.path.exists(path):
            log.debug('%s already exists, overwriting file with new version', path)

        try:
            f = open(path, 'w+' if not binary else 'w+b')
            f.write(content)
            f.close()
            os.chmod(path, Env.getPermission('file'))
        except:
            log.error('Unable writing to file "%s": %s', (path, traceback.format_exc()))
            if os.path.isfile(path):
                os.remove(path)
Example #26
0
    def moveFile(self, old, dest):
        dest = ss(dest)
        try:
            shutil.move(old, dest)

            try:
                os.chmod(dest, Env.getPermission('file'))
            except:
                log.error('Failed setting permissions for file: %s, %s',
                          (dest, traceback.format_exc(1)))

        except OSError, err:
            # Copying from a filesystem with octal permission to an NTFS file system causes a permission error.  In this case ignore it.
            if not hasattr(os, 'chmod') or err.errno != errno.EPERM:
                raise
            else:
                if os.path.exists(dest):
                    os.unlink(old)
Example #27
0
    def download(self, data = {}, movie = {}, filedata = None):

        directory = self.conf('directory')
        if not directory or not os.path.isdir(directory):
            log.error('No directory set for blackhole %s download.', data.get('type'))
        else:
            try:
                if not filedata or len(filedata) < 50:
                    try:
                        if data.get('type') == 'torrent_magnet':
                            filedata = self.magnetToTorrent(data.get('url'))
                            data['type'] = 'torrent'
                    except:
                        log.error('Failed download torrent via magnet url: %s', traceback.format_exc())

                    if not filedata or len(filedata) < 50:
                        log.error('No nzb/torrent available: %s', data.get('url'))
                        return False

                fullPath = os.path.join(directory, self.createFileName(data, filedata, movie))

                try:
                    if not os.path.isfile(fullPath):
                        log.info('Downloading %s to %s.', (data.get('type'), fullPath))
                        with open(fullPath, 'wb') as f:
                            f.write(filedata)
                        os.chmod(fullPath, Env.getPermission('file'))
                        return True
                    else:
                        log.info('File %s already exists.', fullPath)
                        return True

                except:
                    log.error('Failed to download to blackhole %s', traceback.format_exc())
                    pass

            except:
                log.info('Failed to download file %s: %s', (data.get('name'), traceback.format_exc()))
                return False

        return False
Example #28
0
    def download(self, data=None, media=None, filedata=None):
        """ Send a torrent/nzb file to the downloader

        :param data: dict returned from provider
            Contains the release information
        :param media: media dict with information
            Used for creating the filename when possible
        :param filedata: downloaded torrent/nzb filedata
            The file gets downloaded in the searcher and send to this function
            This is done to have failed checking before using the downloader, so the downloader
            doesn't need to worry about that
        :return: boolean
            One fail returns false, but the downloader should log his own errors
        """

        if not media: media = {}
        if not data: data = {}

        log.debug('Sending "%s" to peerflix.', (data.get('name')))

        if not filedata and data.get('protocol') == 'torrent':
            log.error('Failed sending torrent, no data')
            return False

        torrent_hash = ''
        torrent_handle = ''
        if data.get('protocol') == 'torrent_magnet':
            torrent_handle = data.get('url')
            torrent_hash = re.findall('urn:btih:([\w]{32,40})',
                                      data.get('url'))[0].upper()

        if data.get('protocol') == 'torrent':
            info = bdecode(filedata)["info"]
            if not self.verifyTorrentCompatability(info):
                return False
            torrent_hash = sha1(bencode(info)).hexdigest()

            # Convert base 32 to hex
            if len(torrent_hash) == 32:
                torrent_hash = b16encode(b32decode(torrent_hash))

            # Create filename with imdb id and other nice stuff
            directory = self.conf('torrent_directory')
            file_name = self.createFileName(data, filedata, media)
            full_path = os.path.join(directory, file_name)  # Full torrent path
            # Write filedata to torrent file
            try:
                # Make sure the file doesn't exist yet, no need in overwriting it
                if not os.path.isfile(full_path):
                    log.info('Downloading %s to %s.',
                             (data.get('protocol'), full_path))
                    with open(full_path, 'wb') as f:
                        f.write(filedata)
                    os.chmod(full_path, Env.getPermission('file'))
                else:
                    log.info('File %s already exists.', full_path)
                torrent_handle = full_path

            except:
                log.error('Failed to write .torrent file to peerflix %s',
                          traceback.format_exc())
                pass

        peerflix_args = [
            self.conf('path'), torrent_handle, "-p " + self.conf('port'),
            "--" + self.conf('player')
        ]
        if self.conf('movie_directory'):
            peerflix_args.append("--path")
            """
            Depending upon how paths are formatted (using backslashes), this may not work on Windows. If so, try this:
            path = path.encode('string-escape')
            path = path.replace("\\", "/")
            """
            peerflix_args.append(self.conf('movie_directory'))
        if not self.conf('float_on_top'):
            peerflix_args.append('--not-on-top')
        if not self.conf('quit_peerflix_on_player_exit'):
            peerflix_args.append('--no-quit')
        if self.conf('delete_on_exit'):
            peerflix_args.append('--remove')
        if self.conf('player_options'):
            peerflix_args.append('-- ' + self.conf('player_options'))

        peerflix_args = [x.encode('utf-8') for x in peerflix_args]
        log.info('Peerflix args: "%s"', (peerflix_args))

        peerflix_proc = Popen(peerflix_args)  # , stderr=PIPE
        log.info('Peerflix PID: "%s"', (peerflix_proc.pid))
        log.info(
            'Movie available for streaming at http://localhost:%s. This address can be opened in your video player.',
            (self.conf('port')))
        #log.error('Peerflix: %s', peerflix_proc.stderr)

        return self.downloadReturnId(torrent_hash)
Example #29
0
    def download(self, data = None, media = None, filedata = None):
        """ Send a torrent/nzb file to the downloader

        :param data: dict returned from provider
            Contains the release information
        :param media: media dict with information
            Used for creating the filename when possible
        :param filedata: downloaded torrent/nzb filedata
            The file gets downloaded in the searcher and send to this function
            This is done to have failed checking before using the downloader, so the downloader
            doesn't need to worry about that
        :return: boolean
            One faile returns false, but the downloaded should log his own errors
        """

        if not media: media = {}
        if not data: data = {}

        directory = self.conf('directory')

        # The folder needs to exist
        if not directory or not os.path.isdir(directory):
            log.error('No directory set for blackhole %s download.', data.get('protocol'))
        else:
            try:
                # Filedata can be empty, which probably means it a magnet link
                if not filedata or len(filedata) < 50:
                    try:
                        if data.get('protocol') == 'torrent_magnet':
                            filedata = self.magnetToTorrent(data.get('url'))
                            data['protocol'] = 'torrent'
                    except:
                        log.error('Failed download torrent via magnet url: %s', traceback.format_exc())

                    # If it's still empty, either write the magnet link to a .magnet file, or error out.
                    if not filedata or len(filedata) < 50:
                        if self.conf('magnet_file'):
                            filedata = data.get('url') + '\n'
                            data['protocol'] = 'magnet'
                        else:
                            log.error('No nzb/torrent available: %s', data.get('url'))
                            return False

                # Create filename with imdb id and other nice stuff
                file_name = self.createFileName(data, filedata, media)
                full_path = os.path.join(directory, file_name)

                # People want thinks nice and tidy, create a subdir
                if self.conf('create_subdir'):
                    try:
                        new_path = os.path.splitext(full_path)[0]
                        if not os.path.exists(new_path):
                            os.makedirs(new_path)
                            full_path = os.path.join(new_path, file_name)
                    except:
                        log.error('Couldnt create sub dir, reverting to old one: %s', full_path)

                try:

                    # Make sure the file doesn't exist yet, no need in overwriting it
                    if not os.path.isfile(full_path):
                        log.info('Downloading %s to %s.', (data.get('protocol'), full_path))
                        with open(full_path, 'wb') as f:
                            f.write(filedata)
                        os.chmod(full_path, Env.getPermission('file'))
                        return self.downloadReturnId('')
                    else:
                        log.info('File %s already exists.', full_path)
                        return self.downloadReturnId('')

                except:
                    log.error('Failed to download to blackhole %s', traceback.format_exc())
                    pass

            except:
                log.info('Failed to download file %s: %s', (data.get('name'), traceback.format_exc()))
                return False

        return False
Example #30
0
    def download(self, data=None, media=None, filedata=None):
        """ Send a torrent/nzb file to the downloader

        :param data: dict returned from provider
            Contains the release information
        :param media: media dict with information
            Used for creating the filename when possible
        :param filedata: downloaded torrent/nzb filedata
            The file gets downloaded in the searcher and send to this function
            This is done to have failed checking before using the downloader, so the downloader
            doesn't need to worry about that
        :return: boolean
            One faile returns false, but the downloaded should log his own errors
        """

        if not media: media = {}
        if not data: data = {}

        directory = self.conf('directory')

        # The folder needs to exist
        if not directory or not os.path.isdir(directory):
            log.error('No directory set for blackhole %s download.',
                      data.get('protocol'))
        else:
            try:
                # Filedata can be empty, which probably means it a magnet link
                if not filedata or len(filedata) < 50:
                    try:
                        if data.get('protocol') == 'torrent_magnet':
                            filedata = self.magnetToTorrent(data.get('url'))
                            data['protocol'] = 'torrent'
                    except:
                        log.error('Failed download torrent via magnet url: %s',
                                  traceback.format_exc())

                    # If it's still empty, either write the magnet link to a .magnet file, or error out.
                    if not filedata or len(filedata) < 50:
                        if self.conf('magnet_file'):
                            filedata = data.get('url') + '\n'
                            data['protocol'] = 'magnet'
                        else:
                            log.error('No nzb/torrent available: %s',
                                      data.get('url'))
                            return False

                # Create filename with imdb id and other nice stuff
                file_name = self.createFileName(data, filedata, media)
                full_path = os.path.join(directory, file_name)

                # People want thinks nice and tidy, create a subdir
                if self.conf('create_subdir'):
                    try:
                        new_path = os.path.splitext(full_path)[0]
                        if not os.path.exists(new_path):
                            os.makedirs(new_path)
                            full_path = os.path.join(new_path, file_name)
                    except:
                        log.error(
                            'Couldnt create sub dir, reverting to old one: %s',
                            full_path)

                try:

                    # Make sure the file doesn't exist yet, no need in overwriting it
                    if not os.path.isfile(full_path):
                        log.info('Downloading %s to %s.',
                                 (data.get('protocol'), full_path))
                        with open(full_path, 'wb') as f:
                            f.write(filedata)
                        os.chmod(full_path, Env.getPermission('file'))
                        return self.downloadReturnId('')
                    else:
                        log.info('File %s already exists.', full_path)
                        return self.downloadReturnId('')

                except:
                    log.error('Failed to download to blackhole %s',
                              traceback.format_exc())
                    pass

            except:
                log.info('Failed to download file %s: %s',
                         (data.get('name'), traceback.format_exc()))
                return False

        return False