Example #1
0
def checkCertificates():
	print "[WebInterface] checking for SSL Certificates"
	srvcert = '%sserver.pem' %resolveFilename(SCOPE_CONFIG) 
	cacert = '%scacert.pem' %resolveFilename(SCOPE_CONFIG)

	# Check whether there are regular certificates, if not copy the default ones over
	if not os_isfile(srvcert) or not os_isfile(cacert):
		return False
	
	else:
		return True
Example #2
0
def checkCertificates():
    print "[WebInterface] checking for SSL Certificates"
    srvcert = "%sserver.pem" % resolveFilename(SCOPE_CONFIG)
    cacert = "%scacert.pem" % resolveFilename(SCOPE_CONFIG)

    # Check whether there are regular certificates, if not copy the default ones over
    if not os_isfile(srvcert) or not os_isfile(cacert):
        return False

    else:
        return True
Example #3
0
	def setPixmapCB(self, picInfo = None):
		if os_isfile(self.tmpfile):
			if False:
				os_remove(self.tmpfile)
		ptr = self.picload.getData()
		if ptr and self.instance:
			self.instance.setPixmap(ptr.__deref__())
Example #4
0
 def setPixmapCB(self, picInfo=None):
     if os_isfile(self.tmpfile):
         if config.plugins.GoogleMaps.cache_enabled.value is not True:
             os_remove(self.tmpfile)
     ptr = self.picload.getData()
     if ptr and self.instance:
         self.instance.setPixmap(ptr)
Example #5
0
	def setPixmapCB(self, picInfo = None):
		if os_isfile(self.tmpfile):
			if config.plugins.GoogleMaps.cache_enabled.value is not True:
				os_remove(self.tmpfile)
		ptr = self.picload.getData()
		if ptr and self.instance:
			self.instance.setPixmap(ptr)
Example #6
0
	def onLoadFailed(self,error):
		print "WebPixmap:onLoadFAILED", error
		if self.default and self.instance:
			print "showing 404", self.default
			self.picload.startDecode(self.default)
		if os_isfile(self.tmpfile):
			os_remove(self.tmpfile)
Example #7
0
 def load(self, url=None):
     tmpfile = ''.join((self.cachedir, quote_plus(url), '.jpg'))
     if os_path_isdir(self.cachedir) is False:
         print "cachedir not existing, creating it"
         os_mkdir(self.cachedir)
     if os_isfile(tmpfile):
         self.tmpfile = tmpfile
         self.onLoadFinished(None)
     elif url is not None:
         self.tmpfile = tmpfile
         head = {
             "Accept": "image/png,image/*;q=0.8,*/*;q=0.5",
             "Accept-Language": "de",
             "Accept-Encoding": "gzip,deflate",
             "Accept-Charset": "ISO-8859-1,utf-8;q=0.7,*;q=0.7",
             "Keep-Alive": "300",
             "Referer": "http://maps.google.de/",
             "Cookie:":
             "khcookie=fzwq1BaIQeBvxLjHsDGOezbBcCBU1T_t0oZKpA; PREF=ID=a9eb9d6fbca69f5f:TM=1219251671:LM=1219251671:S=daYFLkncM3cSOKsF; NID=15=ADVC1mqIWQWyJ0Wz655SirSOMG6pXP2ocdXwdfBZX56SgYaDXNNySnaOav-6_lE8G37iWaD7aBFza-gsX-kujQeH_8WTelqP9PpaEg0A_vZ9G7r50tzRBAZ-8GUwnEfl",
             "Connection": "keep-alive"
         }
         agt = "Mozilla/5.0 (Windows; U; Windows NT 5.1; de; rv:1.9.0.2) Gecko/2008091620 Firefox/3.0.2"
         downloadPage(url, self.tmpfile, headers=head,
                      agent=agt).addCallback(
                          self.onLoadFinished).addErrback(self.onLoadFailed)
     elif self.default:
         self.picload.startDecode(self.default)
Example #8
0
 def onLoadFailed(self, error):
     print "WebPixmap:onLoadFAILED", error
     if self.default and self.instance:
         print "showing 404", self.default
         self.picload.startDecode(self.default)
     if os_isfile(self.tmpfile):
         os_remove(self.tmpfile)
Example #9
0
def step_impl(context,doc,save_dir):
    context.k_path = PY_PATH.rstrip('/') + '/' + save_dir + context.upload_file

    if hasattr(context,'files_created'):
        context.files_created.append(context.k_path)
    else:
        context.files_created  =   [context.k_path]

    assert_that(os_isfile(context.k_path),  equal_to(True))
Example #10
0
def manage_config(files):
    """Update the __configparser__ using the passed files.

:param files: List of strings representing paths or filenames
:type files: [strings]
:rtype: None
    """
    if not files or not all(os_isfile(x) for x in files):
        raise configparser.Error("One or more of the files passed as argument for config do not exist.\n")

    __configparser__.read(files)
Example #11
0
def check_file(item):
    filepath = None

    m = re.compile('^(?:file:\/\/)?(.*)').search(item)
    if m is not None:
        filename = m.group(1)
        from os.path import isfile as os_isfile
        fexists = os_isfile(filename)
        if fexists:
            filepath = filename

    return filepath
Example #12
0
def check_file(item):
    filepath = None

    m = re.compile('^(?:file:\/\/)?(.*)').search(item)
    if m is not None:
        filename = m.group(1)
        from os.path import isfile as os_isfile
        fexists = os_isfile(filename)
        if fexists:
            filepath = filename

    return filepath
Example #13
0
    def __init__(self, filename, mode='r', depth=16, rate=44100, channels=2):
        """ AudioIO(filename, [mode='r', depth=16, rate=44100, channels=2])
        -> Open an audio file for file like access to audio files.

        """

        if not all([i in self._supported_modes for i in mode]):
            raise ValueError("(%s) Mode has to be one of %s." %
                             (self.__class__.__name__,
                             self._supported_modes))

        if depth not in self._valid_depth:
            raise ValueError("(%s) Invalid depth %s, valid depths are %s" %
                             (self.__class__.__name__,
                              depth,
                              self._valid_depth))

        super(AudioIO, self).__init__()

        if filename:
            if 'r' in mode and not os_isfile(filename):
                if not filename.startswith('http://'):
                    raise(IOError("%s: No such file or directory" % filename))

        self.three_byte = False

        # self._buffer_size = 8192  # 16384 // (depth // (8 // channels))
        self._buffer_size = 8192  # 16384 // (depth // (8 // channels))

        self._filename = filename
        self._mode = mode

        self._depth = depth
        self._rate = rate
        self._channels = channels
        self._floatp = False

        self._width = self._depth // 8

        self._length = 1

        self._bigendian = False
        self._unsigned = False

        self._loops = -1
        self._loop_count = 0

        self._closed = True

        # The default name is the filename minus the extension.
        name = os_basename(self._filename.rsplit('.', 1)[0])

        self._info_dict = {'name': name}
Example #14
0
	def load(self, url = None):
		if url is None:
			self.instance.setPixmap(None)
			return
		url = isinstance(url,unicode) and url.encode('utf-8') or url
		if os_isfile(url):
			self.tmpfile = url
			self.onLoadFinished(None)
			return
		tmpfile = ''.join((self.cachedir, quote_plus(url), '.jpg'))
		if os_path_isdir(self.cachedir) is False:
			print "cachedir not existing, creating it"
			os_mkdir(self.cachedir)
		if os_isfile(tmpfile):
			self.tmpfile = tmpfile
			self.onLoadFinished(None)
		elif url is not None:
			self.tmpfile = tmpfile
			agt = "Mozilla/5.0 (Windows; U; Windows NT 5.1; de; rv:1.9.0.2) Gecko/2008091620 Firefox/3.0.2"
			downloadPage(url,self.tmpfile, agent=agt).addCallback(self.onLoadFinished).addErrback(self.onLoadFailed)
		elif self.default:
			self.picload.startDecode(self.default)
Example #15
0
    def __init__(self, filename, mode='r', depth=16, rate=44100, channels=2):
        """ AudioIO(filename, [mode='r', depth=16, rate=44100, channels=2])
        -> Open an audio file for file like access to audio files.

        """

        if not all([i in self._supported_modes for i in mode]):
            raise ValueError("(%s) Mode has to be one of %s." %
                             (self.__class__.__name__, self._supported_modes))

        if depth not in self._valid_depth:
            raise ValueError(
                "(%s) Invalid depth %s, valid depths are %s" %
                (self.__class__.__name__, depth, self._valid_depth))

        super(AudioIO, self).__init__()

        if filename:
            if 'r' in mode and not os_isfile(filename):
                if not filename.startswith('http://'):
                    raise (IOError("%s: No such file or directory" % filename))

        self.three_byte = False

        # self._buffer_size = 8192  # 16384 // (depth // (8 // channels))
        self._buffer_size = 8192  # 16384 // (depth // (8 // channels))

        self._filename = filename
        self._mode = mode

        self._depth = depth
        self._rate = rate
        self._channels = channels
        self._floatp = False

        self._width = self._depth // 8

        self._length = 1

        self._bigendian = False
        self._unsigned = False

        self._loops = -1
        self._loop_count = 0

        self._closed = True

        # The default name is the filename minus the extension.
        name = os_basename(self._filename.rsplit('.', 1)[0])

        self._info_dict = {'name': name}
Example #16
0
 def load(self, url=None):
     tmpfile = ''.join((self.cachedir, quote_plus(url), ''))
     if os_path_isdir(self.cachedir) is False:
         print "cachedir not existing, creating it"
         os_mkdir(self.cachedir)
     if os_isfile(tmpfile):
         self.tmpfile = tmpfile
         self.onLoadFinished(None)
     elif url is not None:
         self.tmpfile = tmpfile
         head = {}
         agt = "Mozilla/5.0 (Windows; U; Windows NT 5.1; de; rv:1.9.0.2) Gecko/2008091620 Firefox/3.0.2"
         downloadPage(url, self.tmpfile, headers=head, agent=agt).addCallback(self.onLoadFinished).addErrback(self.onLoadFailed)
     elif self.default:
         self.picload.startDecode(self.default)
Example #17
0
 def load(self, url = None):
     tmpfile = ''.join((self.cachedir, quote_plus(url), ''))
     if os_path_isdir(self.cachedir) is False:
         print "cachedir not existing, creating it"
         os_mkdir(self.cachedir)
     if os_isfile(tmpfile):
         self.tmpfile = tmpfile
         self.onLoadFinished(None)
     elif url is not None:
         self.tmpfile = tmpfile
         head = { }
         agt = "Mozilla/5.0 (Windows; U; Windows NT 5.1; de; rv:1.9.0.2) Gecko/2008091620 Firefox/3.0.2"
         downloadPage(url,self.tmpfile,headers=head,agent=agt).addCallback(self.onLoadFinished).addErrback(self.onLoadFailed)
     elif self.default:
         self.picload.startDecode(self.default)
Example #18
0
    def __init__(self, filename, mode='r', depth=16, rate=44100, channels=2,
                 bigendian=False, unsigned=False, quality=.5, comment_dict={},
                 **kwargs):
        """ VorbisFile(filename, mode='r', depth=16, channels=2,
        bigendian=False, unsigned=False,) -> Initialize the file object for
        reading and writing.

        """

        super(VorbisFile, self).__init__(filename=filename, mode=mode,
                                         depth=depth, rate=rate,
                                         channels=channels)

        self._signed = not unsigned
        self._unsigned = unsigned
        self._bigendian = bigendian

        if mode == 'r':
            if not os_isfile(filename):
                raise OSError("File not found: %s" % filename)

            self._vorbis_file = self._read_open(filename)

            file_pointer = _vorbisfile.pointer(self._vorbis_file)
            self._length = _vorbisfile.ov_pcm_total(file_pointer, -1)

            self._data = b''
        else:
            self._quality = quality
            self._comment_dict = comment_dict
            self._info_dict.update(self._comment_dict)

            self._stream_state = _vorbisenc.OggStreamState()
            self._page = _vorbisenc.OggPage()
            self._packet = _vorbisenc.OggPacket()

            self._info = _vorbisenc.VorbisInfo()
            self._comment = _vorbisenc.VorbisComment()

            self._comment.update(comment_dict)

            self._dsp_state = _vorbisenc.DspState()
            self._block = _vorbisenc.VorbisBlock()

            self._vorbis_file = self._write_open(filename)
Example #19
0
def traverse_dir(rootdir='.',
                 pathsep='/',
                 explicit_cwd=True,
                 *,
                 recurse=False,
                 subdirs_only=False,
                 files_only=False):

    if not is_windows_os:
        raise NotImplementedError('only available on windows OS')

    if (subdirs_only is False) and (files_only is False):
        subdirs_only = True
        files_only   = True

    rootdir = standardize_dir(rootdir, pathsep, explicit_cwd)

    if recurse:
        args = 'dir /b /s "{}"'.format(rootdir)
    else:
        args = 'dir /b "{}"'.format(rootdir)

    with os.popen(args) as os_cmd:
        out = os_cmd.read()
        out = out.split('\n')
        out.sort()

    if out and out[0] == '':
        del out[0]

    if recurse is False:
        out = [rootdir + p for p in out]

    if subdirs_only and files_only:
        return out
    elif subdirs_only:
        return [path for path in out
                     if os_isdir(path)]
    elif files_only:
        return [path for path in out
                     if os_isfile(path)]
    def read_config_file(self,
                         config_file_path: str,
                         only_read=False,
                         overwrite=True) -> dict:
        """
        Выполняет чтение настроек из файла и возвращает их в случаи успеха.
        Если файла с настройками нет, то создается новый файл с параметрами по умолчанию.
        Если overwrite = True, то все прочитанные настройки обновляют (заменяют) текущие значения экземпляра.
        Если overwrite = False, то все прочитанные настройки объединяются с текущими значениями экземпляра.
        Если only_read = True, то значения будут только прочитаны, но обновление значений экземпляра не произойдет.
        """

        if not os_isfile(config_file_path):
            # Если файл с настройками отсутствует, то создаем файл с дефолтными настройками
            self.write_config_file(config_file_path)
        else:
            with open(config_file_path, "r") as yml_file:
                try:
                    cfg_dict = yaml.load(yml_file, Loader=yaml.CLoader)
                except ScannerError:
                    return {}
                else:
                    if isinstance(cfg_dict, dict):
                        for key in self.hide_fields:
                            cfg_dict, _ = set_value_for_key(
                                cfg_dict, key, self.__decoder_string)
                        pass
                    if not only_read:
                        if overwrite:
                            self.replace_config(cfg_dict)
                        else:
                            self.add_new_config_params(cfg_dict)
                    else:
                        if cfg_dict is not None:
                            return dict(cfg_dict)
                        else:
                            return {}
        return self.as_dict()
Example #21
0
def get_xbrl_files(file, re_xbrl_file_match):
    """XBRLファイルデータ取得"""
    xbrl_files = OrderedDict()

    if not os_isfile(file):
        print('not found %s' % file)
        return xbrl_files

    # zipオブジェクト作成
    with ZipFile(file, 'r') as zip_obj:
        # ファイルリスト取得
        infos = zip_obj.infolist()

        # zipアーカイブから対象ファイルを読み込む
        od_xbrl = OrderedDict()
        for info in infos:
            filename = os_basename(info.filename)

            # zipからデータを読み込んで辞書に入れる
            if re_xbrl_file_match(info.filename):
                od_xbrl.update({filename: zip_obj.read(info.filename)})

    xbrl_files.update({'xbrl': od_xbrl})
    return xbrl_files
Example #22
0
	def load(self, url = None):
		tmpfile = ''.join((self.cachedir, quote_plus(url), '.jpg'))
		if os_path_isdir(self.cachedir) is False:
			print "cachedir not existing, creating it"
			os_mkdir(self.cachedir)
		if os_isfile(tmpfile):
			self.tmpfile = tmpfile
			self.onLoadFinished(None)
		elif url is not None:
			self.tmpfile = tmpfile
			head = {
				"Accept":"image/png,image/*;q=0.8,*/*;q=0.5",
				"Accept-Language":"de",
				"Accept-Encoding":"gzip,deflate",
				"Accept-Charset":"ISO-8859-1,utf-8;q=0.7,*;q=0.7",
				"Keep-Alive":"300",
				"Referer":"http://maps.google.de/",
				"Cookie:": "khcookie=fzwq1BaIQeBvxLjHsDGOezbBcCBU1T_t0oZKpA; PREF=ID=a9eb9d6fbca69f5f:TM=1219251671:LM=1219251671:S=daYFLkncM3cSOKsF; NID=15=ADVC1mqIWQWyJ0Wz655SirSOMG6pXP2ocdXwdfBZX56SgYaDXNNySnaOav-6_lE8G37iWaD7aBFza-gsX-kujQeH_8WTelqP9PpaEg0A_vZ9G7r50tzRBAZ-8GUwnEfl",
				"Connection":"keep-alive"
			}
			agt = "Mozilla/5.0 (Windows; U; Windows NT 5.1; de; rv:1.9.0.2) Gecko/2008091620 Firefox/3.0.2"
			downloadPage(url,self.tmpfile,headers=head,agent=agt).addCallback(self.onLoadFinished).addErrback(self.onLoadFailed)
		elif self.default:
			self.picload.startDecode(self.default)
Example #23
0
def main(args: dict) -> None:
    """ Encode args['filename'] times.

    """

    from os.path import basename as os_basename
    from os.path import isfile as os_isfile
    from os.path import splitext as os_splitext
    from sys import stdin as sys_stdin
    from select import select
    from time import sleep as time_sleep
    from termios import tcgetattr, tcsetattr, ECHO, ICANON, TCSANOW
    from termios import VMIN, VTIME

    from musio import open_file, open_device

    if args['debug']:
        from musio import io_util
        io_util.DEBUG = True

    filename = args['filename']
    output = os_splitext(os_basename(filename))[0] + '.' + args['filetype']
    output_bytes = output.encode('utf-8', 'surrogateescape')
    output_printable = output_bytes.decode('utf-8', 'ignore')
    if os_isfile(output):
        if input("Overwrite %s (y/n): " % output_printable).lower().startswith('n'):
            return

    # Save the current terminal state.
    normal = tcgetattr(sys_stdin)
    quiet = tcgetattr(sys_stdin)

    # Do not wait for key press and don't echo.
    quiet[3] &= ~(ECHO | ICANON)
    quiet[6][VMIN] = 0
    quiet[6][VTIME] = 0

    # Set the new terminal state.
    tcsetattr(sys_stdin, TCSANOW, quiet)

    # Value returned to tell the calling function whether to quit or
    # not.
    quit_val = True

    if args['filetype'].lower() == 'ogg':
        quality = args['quality'] / 10 if args['quality'] in range(-1, 11) else 0.5
    elif args['filetype'].lower() == 'mp3':
        quality = args['quality'] if args['quality'] in range(0, 10) else 2

    try:
        with open_file(**args) as in_file:
            in_file_title = in_file._info_dict.get('title',
                                                in_file._info_dict['name'])
            comment_dict = {'title': in_file_title}
            comment_dict.update(in_file._info_dict)
            for i in ['title', 'artist', 'album', 'year', 'comment',
                      'track', 'genre']:
                if args.get(i, ''):
                    comment_dict[i] = args[i]

            with open_file(output, 'w', depth=in_file.depth, rate=in_file.rate,
                        channels=in_file.channels, quality=quality,
                        comment_dict=comment_dict) as out_file:
                in_file.loops = 0

                if args['show_position']:
                    filename_bytes = filename.encode('utf-8', 'surrogateescape')
                    filename_printable = filename_bytes.decode('utf-8', 'ignore')
                    print("Encoding: %s to %s" % (filename_printable, output_printable))
                    print(in_file)

                for data in in_file:
                    if args['show_position']:
                        if in_file.length > 0:
                            # Calculate the percentage played.
                            pos = (in_file.position * 100) / in_file.length

                            # Make the string.
                            pos_str = 'Position: %.2f%%' % pos

                            # Find the length of the string.
                            format_len = len(pos_str) + 2

                            # Print the string and after erasing the old
                            # one using ansi escapes.
                            print('\033[%dD\033[K%s' % (format_len, pos_str),
                                  end='', flush=True)
                    out_file.write(data)

                    # Check for input.
                    r, _, _ = select([sys_stdin], [], [], 0)

                    # Get input if there was any otherwise continue.
                    if r:
                        command = r[0].readline().lower()
                        # Handle input commands.
                        if command.startswith('q'):
                            quit_val = False
                            break
                        elif command == '\n':
                            break

    except Exception as err:
        print("Error: %s" % err, flush=True)
        raise(err)
    finally:
        # Re-set the terminal state.
        tcsetattr(sys_stdin, TCSANOW, normal)

    if args['show_position']:
        print("\nDone.")

    return quit_val
 def r_update(self):
     """ Выполняет чтение значений из файлов в списке config_file_path_for_update """
     for file_path in self.config_file_path_for_update:
         if os_isfile(file_path):
             self.read_config_file(config_file_path=file_path,
                                   overwrite=True)
Example #25
0
def main(args: dict) -> int:
    """ Read the password file, decrypt it and print the requested info.

    """

    filename = args.pop('filename')
    account = args.pop('account')
    remove_account = args.pop('remove_account')
    password = args.pop('password')

    if account:
        # Get the sha256 hash of the account name.
        hashed_account = bytes_to_str(SHA256.new(account.encode()).digest())

        # Create the information dictionary from the info list supplied
        # by the user.
        info_dict = list_to_dict(args.pop('info_list'), args['info_seperator'])

        if info_dict:
            # Put the non hashed account name in the info dict so it is
            # not lost.
            info_dict['Account Name'] = account

            # Get the secret information.
            for key, value in info_dict.items():
                if value == '{secret}':
                    secret = get_pass(key)
                    info_dict[key] = secret
    else:
        # No account name was given.
        hashed_account = ''

    # Create the file if it doesn't exist.
    if not os_isfile(filename):
        open_mode = 'w+b'
    else:
        open_mode = 'rb'

    with open(filename, open_mode) as pass_file:
        # Read all the data from the file.
        lzma_data = pass_file.read()

    # Get the json data out of the file data or an empty json dict of
    # the file was empty.
    if lzma_data:
        json_data = lzma_decompress(lzma_data).decode()
    else:
        json_data = '{}'

    # Load the json data into a dictionary.
    accounts_dict = json_loads(json_data)

    aes_key_digest = bytes_to_str(SHA512.new(b'\x00aes_key\x00').digest())
    aes_key_enc = str_to_bytes(accounts_dict.pop(aes_key_digest, ''))
    aes_key_enc, aes_key = get_aes_key(aes_key_enc)

    if not hashed_account:
        if args.get('list_account_info', False):
            # List all accounts if none where given, but list was requested.
            account_str = ''
            for account_data in accounts_dict.values():
                # account_dict = crypt_to_dict(account_data, password)
                account_dict = crypt_to_dict_key(account_data, aes_key)
                if account_dict:
                    account_str += '\n' + dict_to_str(account_dict)
            import pydoc
            pydoc.pager(account_str)
        elif args.get('re-encrypt', False):
            # Try to re-encrypt every account.
            encrypt_pass = get_pass('encryption password')
            tmp_accounts_dict = accounts_dict.copy()
            for account_hash, account_data in accounts_dict.items():
                account_dict = crypt_to_dict(account_data, password=password,
                                             skip_invalid=True)
                # account_dict = crypt_to_dict_key(account_data, aes_key)
                if account_dict:
                    # new_account_data = dict_to_crypt(account_dict, encrypt_pass)
                    new_account_data = dict_to_crypt_key(account_dict, aes_key)
                else:
                    print("Invalid password.  Account will use the old password")
                tmp_accounts_dict[account_hash] = new_account_data
            tmp_accounts_dict[aes_key_digest] = bytes_to_str(aes_key_enc)
            write_file(filename, tmp_accounts_dict)
            return 0
        elif args.get('search', ''):
            search_str = args['search'].lower()

            # String to store all matching account information.
            account_str = ''

            for account_data in accounts_dict.values():
                # Search through every account that can be decrypted with
                # the password, or ask for a password for each account.
                # account_dict = crypt_to_dict(account_data, password=password,
                #                              skip_invalid=True)
                account_dict = crypt_to_dict_key(account_data, aes_key)

                # If the password could decrypt the account, info search
                # throuth every key and value in the account.
                if account_dict:
                    for key, value in account_dict.items():
                        if search_str in key.lower() or search_str in value.lower():
                            account_str += '\n' + dict_to_str(account_dict)
                            # Don't add the same account more than once.
                            break
            import pydoc
            pydoc.pager(account_str)
    else:
        # Pop the requested account out of the dictionary, so it can be
        # modified, removed, or just printed to stdout.
        account_data = accounts_dict.pop(hashed_account, '')

        # Don't do anything with the account_data if it is to be
        # removed.
        if remove_account:
            accounts_dict[aes_key_digest] = bytes_to_str(aes_key_enc)
            write_file(filename, accounts_dict)
            return 0

        # If there was account data, then put the decrypted dictionary in
        # account_dict.  Otherwise put an empty dictionary.
        if account_data:
            # account_dict = crypt_to_dict(account_data, skip_invalid=False)
            account_dict = crypt_to_dict_key(account_data, aes_key)
        else:
            account_dict = {}

        # Update the account info if new data was supplied.
        if info_dict:
            account_dict.update(info_dict)

            # Remove items from account_dict for which info_dict has an
            # empty value.  (i.e. to remove items from an accounts info
            # the user needs to supply and empty value after the
            # sperator.
            for key, value in info_dict.items():
                if not value.strip():
                    account_dict.pop(key)

            # Encrypt the account_dict.
            # account_data = dict_to_crypt(account_dict)
            account_data = dict_to_crypt_key(account_dict, aes_key)

        # Print the account info.
        if args.get('list_account_info', False) and account_dict:
            import pydoc
            pydoc.pager(dict_to_str(account_dict))

        # Put the accounts data back into the dictionary.
        accounts_dict[hashed_account] = account_data
        accounts_dict[aes_key_digest] = bytes_to_str(aes_key_enc)

        # Write accounts_dict to the password file.
        write_file(filename, accounts_dict)

    return 0
Example #26
0
	'genre_relation':{
		'query':'create table genre_relation (seriesid integer, genreid integer)'
		,'attributes':['seriesid','genreid']},
	'actor':{
		'query':'create table actor (actorid integer primary key' + 
			', image text, name text)'
		,'attributes':['actorid','image','name']},
	'acts':{
		'query':'create table acts (seriesid integer' + 
			', role text, actorid text, sortorder integer)'
		,'attributes':['seriesid','role','actorid','sortorder']}
}
_INSERT_Q = 'insert into {table} ({query})'


if not os_isfile(_DB_PATH):
	try:
		db = sqlite3.connect()
		c = db.cursor()
		for key in _TABLE_NAMES:
			c.execute(_TABLE_NAMES[key]['query']
		db.commit()
	except sqlite3.DatabaseError as e:
		print(str(e))
	finally:
		db.close()

def storeData(table, data):
	try:
		db = sqlite3.connect()
		c = db.cursor()
Example #27
0
def main(args):
    """ Encode args['filename'] times.

    """

    from os.path import basename as os_basename
    from os.path import isfile as os_isfile
    from os.path import splitext as os_splitext
    from sys import stdin as sys_stdin
    from sys import stdout as sys_stdout
    from select import select
    from time import sleep as time_sleep
    from termios import tcgetattr, tcsetattr, ECHO, ICANON, TCSANOW
    from termios import VMIN, VTIME

    from musio import open_file, open_device

    if args['debug']:
        from musio import io_util
        io_util.DEBUG = True

    filename = args['filename']
    output = os_splitext(os_basename(filename))[0] + '.' + args['filetype']
    output_bytes = output.encode('utf-8', 'surrogateescape')
    output_printable = output_bytes.decode('utf-8', 'ignore')
    if os_isfile(output):
        if raw_input("Overwrite %s (y/n): " % output_printable).lower().startswith('n'):
            return

    # Save the current terminal state.
    normal = tcgetattr(sys_stdin)
    quiet = tcgetattr(sys_stdin)

    # Do not wait for key press and don't echo.
    quiet[3] &= ~(ECHO | ICANON)
    quiet[6][VMIN] = 0
    quiet[6][VTIME] = 0

    # Set the new terminal state.
    tcsetattr(sys_stdin, TCSANOW, quiet)

    # Value returned to tell the calling function whether to quit or
    # not.
    quit_val = True

    if args['filetype'].lower() == 'ogg':
        quality = args['quality'] / 10 if args['quality'] in range(-1, 11) else 0.5
    elif args['filetype'].lower() == 'mp3':
        quality = args['quality'] if args['quality'] in range(0, 10) else 2

    try:
        with open_file(**args) as in_file:
            in_file_title = in_file._info_dict.get('title',
                                                in_file._info_dict['name'])
            comment_dict = {'title': in_file_title}
            comment_dict.update(in_file._info_dict)
            for i in ['title', 'artist', 'album', 'year', 'comment',
                      'track', 'genre']:
                if args.get(i, ''):
                    comment_dict[i] = args[i]

            with open_file(output, 'w', depth=in_file.depth, rate=in_file.rate,
                        channels=in_file.channels, quality=quality,
                        comment_dict=comment_dict) as out_file:
                in_file.loops = 0

                if args['show_position']:
                    filename_bytes = filename.encode('utf-8', 'surrogateescape')
                    filename_printable = filename_bytes.decode('utf-8', 'ignore')
                    print("Encoding: %s to %s" % (filename, output))
                    print(in_file)

                for data in in_file:
                    if args['show_position']:
                        if in_file.length > 0:
                            # Calculate the percentage played.
                            pos = (in_file.position * 100) / float(in_file.length)

                            # Make the string.
                            pos_str = 'Position: %.2f%%' % pos

                            # Find the length of the string.
                            format_len = len(pos_str) + 2

                            # Print the string and after erasing the old
                            # one using ansi escapes.
                            print('\033[%dD\033[K%s' % (format_len, pos_str),
                                  end='')
                            sys_stdout.flush()
                    out_file.write(data)

                    # Check for input.
                    r, _, _ = select([sys_stdin], [], [], 0)

                    # Get input if there was any otherwise continue.
                    if r:
                        command = r[0].readline().lower()
                        # Handle input commands.
                        if command.startswith('q'):
                            quit_val = False
                            break
                        elif command == '\n':
                            break

    except Exception as err:
        print("Error: %s" % err)
        raise(err)
    finally:
        # Re-set the terminal state.
        tcsetattr(sys_stdin, TCSANOW, normal)

    if args['show_position']:
        print("\nDone.")

    return quit_val