Пример #1
0
def save_file():
    """
    This function retrieves file_name and data from request.
    and then save the data to the file
    """
    if request.data:
        file_data = json.loads(request.data, encoding='utf-8')

    # retrieve storage directory path
    storage_manager_path = get_storage_directory()

    # generate full path of file
    file_path = unquote(file_data['file_name'])
    if hasattr(str, 'decode'):
        file_path = unquote(
            file_data['file_name']
        ).encode('utf-8').decode('utf-8')

    try:
        Filemanager.check_access_permission(storage_manager_path, file_path)
    except Exception as e:
        return internal_server_error(errormsg=str(e))

    if storage_manager_path is not None:
        file_path = os.path.join(
            storage_manager_path,
            file_path.lstrip('/').lstrip('\\')
        )

    if hasattr(str, 'decode'):
        file_content = file_data['file_content']
    else:
        file_content = file_data['file_content'].encode()

    # write to file
    try:
        with open(file_path, 'wb+') as output_file:
            if hasattr(str, 'decode'):
                output_file.write(file_content.encode('utf-8'))
            else:
                output_file.write(file_content)
    except IOError as e:
        if e.strerror == 'Permission denied':
            err_msg = "Error: {0}".format(e.strerror)
        else:
            err_msg = "Error: {0}".format(e.strerror)
        return internal_server_error(errormsg=err_msg)
    except Exception as e:
        err_msg = "Error: {0}".format(e.strerror)
        return internal_server_error(errormsg=err_msg)

    return make_json_response(
        data={
            'status': True,
        }
    )
Пример #2
0
def save_file():
    """
    This function retrieves file_name and data from request.
    and then save the data to the file
    """
    if request.data:
        file_data = json.loads(request.data, encoding='utf-8')

    # retrieve storage directory path
    storage_manager_path = get_storage_directory()

    # generate full path of file
    file_path = unquote(file_data['file_name'])
    if hasattr(str, 'decode'):
        file_path = unquote(
            file_data['file_name']
        ).encode('utf-8').decode('utf-8')

    try:
        Filemanager.check_access_permission(storage_manager_path, file_path)
    except Exception as e:
        return internal_server_error(errormsg=str(e))

    if storage_manager_path is not None:
        file_path = os.path.join(
            storage_manager_path,
            file_path.lstrip('/').lstrip('\\')
        )

    if hasattr(str, 'decode'):
        file_content = file_data['file_content']
    else:
        file_content = file_data['file_content'].encode()

    # write to file
    try:
        with open(file_path, 'wb+') as output_file:
            if hasattr(str, 'decode'):
                output_file.write(file_content.encode('utf-8'))
            else:
                output_file.write(file_content)
    except IOError as e:
        if e.strerror == 'Permission denied':
            err_msg = "Error: {0}".format(e.strerror)
        else:
            err_msg = "Error: {0}".format(e.strerror)
        return internal_server_error(errormsg=err_msg)
    except Exception as e:
        err_msg = "Error: {0}".format(e.strerror)
        return internal_server_error(errormsg=err_msg)

    return make_json_response(
        data={
            'status': True,
        }
    )
Пример #3
0
def save_file():
    """
    This function retrieves file_name and data from request.
    and then save the data to the file
    """
    if request.data:
        file_data = json.loads(request.data, encoding='utf-8')

    # retrieve storage directory path
    storage_manager_path = get_storage_directory()

    # generate full path of file
    file_path = unquote(file_data['file_name'])

    try:
        Filemanager.check_access_permission(storage_manager_path, file_path)
    except Exception as e:
        return internal_server_error(errormsg=str(e))

    if storage_manager_path is not None:
        file_path = os.path.join(
            storage_manager_path,
            file_path.lstrip('/').lstrip('\\')
        )

    # Get value for encoding if file is already loaded to SQL editor
    def get_file_encoding_of_loaded_file(file_name):
        encoding = 'utf-8'
        for ele in Filemanager.loaded_file_encoding_list:
            if file_name in ele:
                encoding = ele[file_name]
        return encoding

    enc = get_file_encoding_of_loaded_file(os.path.basename(file_path))

    file_content = file_data['file_content'].encode(enc)

    # write to file
    try:
        with open(file_path, 'wb+') as output_file:
            output_file.write(file_content)
    except IOError as e:
        err_msg = gettext("Error: {0}").format(e.strerror)
        return internal_server_error(errormsg=err_msg)
    except Exception as e:
        err_msg = gettext("Error: {0}").format(e.strerror)
        return internal_server_error(errormsg=err_msg)

    return make_json_response(
        data={
            'status': True,
        }
    )
Пример #4
0
def load_file():
    """
    This function gets name of file from request data
    reads the data and sends back in reponse
    """
    if request.data:
        file_data = json.loads(request.data, encoding='utf-8')

    file_path = unquote(file_data['file_name'])
    if hasattr(str, 'decode'):
        file_path = unquote(
            file_data['file_name']).encode('utf-8').decode('utf-8')

    # retrieve storage directory path
    storage_manager_path = get_storage_directory()
    if storage_manager_path:
        # generate full path of file
        file_path = os.path.join(storage_manager_path,
                                 file_path.lstrip('/').lstrip('\\'))

    (status, err_msg, is_binary, is_startswith_bom,
     enc) = Filemanager.check_file_for_bom_and_binary(file_path)

    if not status:
        return internal_server_error(errormsg=gettext(err_msg))

    if is_binary:
        return internal_server_error(
            errormsg=gettext("File type not supported"))

    return Response(read_file_generator(file_path, enc), mimetype='text/plain')
Пример #5
0
def load_file():
    """
    This function gets name of file from request data
    reads the data and sends back in reponse
    """
    if request.data:
        file_data = json.loads(request.data, encoding='utf-8')

    file_path = unquote(file_data['file_name'])
    if hasattr(str, 'decode'):
        file_path = unquote(
            file_data['file_name']
        ).encode('utf-8').decode('utf-8')

    # retrieve storage directory path
    storage_manager_path = get_storage_directory()
    if storage_manager_path:
        # generate full path of file
        file_path = os.path.join(
            storage_manager_path,
            file_path.lstrip('/').lstrip('\\')
        )

    (status, err_msg, is_binary,
     is_startswith_bom, enc) = Filemanager.check_file_for_bom_and_binary(
        file_path
    )

    if not status:
        return internal_server_error(
            errormsg=gettext(err_msg)
        )

    if is_binary:
        return internal_server_error(
            errormsg=gettext("File type not supported")
        )

    return Response(read_file_generator(file_path, enc), mimetype='text/plain')
Пример #6
0
def dump_database_servers(output_file, selected_servers,
                          dump_user=current_user, from_setup=False):
    """Dump the server groups and servers.
    """
    user = _does_user_exist(dump_user, from_setup)
    if user is None:
        return False, USER_NOT_FOUND % dump_user

    user_id = user.id
    # Dict to collect the output
    object_dict = {}
    # Counters
    servers_dumped = 0

    # Dump servers
    servers = Server.query.filter_by(user_id=user_id).all()
    server_dict = {}
    for server in servers:
        if selected_servers is None or str(server.id) in selected_servers:
            # Get the group name
            group_name = ServerGroup.query.filter_by(
                user_id=user_id, id=server.servergroup_id).first().name

            attr_dict = {}
            add_value(attr_dict, "Name", server.name)
            add_value(attr_dict, "Group", group_name)
            add_value(attr_dict, "Host", server.host)
            add_value(attr_dict, "HostAddr", server.hostaddr)
            add_value(attr_dict, "Port", server.port)
            add_value(attr_dict, "MaintenanceDB", server.maintenance_db)
            add_value(attr_dict, "Username", server.username)
            add_value(attr_dict, "Role", server.role)
            add_value(attr_dict, "SSLMode", server.ssl_mode)
            add_value(attr_dict, "Comment", server.comment)
            add_value(attr_dict, "Shared", server.shared)
            add_value(attr_dict, "DBRestriction", server.db_res)
            add_value(attr_dict, "PassFile", server.passfile)
            add_value(attr_dict, "SSLCert", server.sslcert)
            add_value(attr_dict, "SSLKey", server.sslkey)
            add_value(attr_dict, "SSLRootCert", server.sslrootcert)
            add_value(attr_dict, "SSLCrl", server.sslcrl)
            add_value(attr_dict, "SSLCompression", server.sslcompression)
            add_value(attr_dict, "BGColor", server.bgcolor)
            add_value(attr_dict, "FGColor", server.fgcolor)
            add_value(attr_dict, "Service", server.service)
            add_value(attr_dict, "Timeout", server.connect_timeout)
            add_value(attr_dict, "UseSSHTunnel", server.use_ssh_tunnel)
            add_value(attr_dict, "TunnelHost", server.tunnel_host)
            add_value(attr_dict, "TunnelPort", server.tunnel_port)
            add_value(attr_dict, "TunnelUsername", server.tunnel_username)
            add_value(attr_dict, "TunnelAuthentication",
                      server.tunnel_authentication)

            servers_dumped = servers_dumped + 1

            server_dict[servers_dumped] = attr_dict

    object_dict["Servers"] = server_dict

    # retrieve storage directory path
    storage_manager_path = None
    if not from_setup:
        storage_manager_path = get_storage_directory(user)

    # generate full path of file
    file_path = unquote(output_file)

    from pgadmin.misc.file_manager import Filemanager
    try:
        Filemanager.check_access_permission(storage_manager_path, file_path)
    except Exception as e:
        return _handle_error(str(e), from_setup)

    if storage_manager_path is not None:
        file_path = os.path.join(
            storage_manager_path,
            file_path.lstrip('/').lstrip('\\')
        )

    # write to file
    file_content = json.dumps(object_dict, indent=4)
    error_str = "Error: {0}"
    try:
        with open(file_path, 'w') as output_file:
            output_file.write(file_content)
    except IOError as e:
        err_msg = error_str.format(e.strerror)
        return _handle_error(err_msg, from_setup)
    except Exception as e:
        err_msg = error_str.format(e.strerror)
        return _handle_error(err_msg, from_setup)

    msg = gettext("Configuration for %s servers dumped to %s" %
                  (servers_dumped, output_file.name))
    print(msg)

    return True, msg