Welcome to PyFileBrowser’s documentation!¶
——–Proxy Server——–¶
Engine¶
- pyfilebrowser.proxy.main.epoch()¶
- pyfilebrowser.proxy.main.refresh_allowed_origins() None ¶
Refresh all the allowed origins.
See also
Triggered once during the proxy server starts up (by default).
Triggered repeatedly at given intervals as a background task (if
origin_refresh
is set).- The background task runs only when the env vars,
private_ip
orpublic_ip
is set to True,as they are the only dynamic values.
- async pyfilebrowser.proxy.main.incrementer(attempt: int) int ¶
Increments block time for a host address based on the number of failed attempts.
- Parameters:
attempt – Number of failed attempts.
- Returns:
Returns the appropriate block time in minutes.
- Return type:
int
- async pyfilebrowser.proxy.main.handle_auth_error(request: Request) None ¶
Handle authentication errors from the filebrowser API.
- Parameters:
request – The incoming request object.
- async pyfilebrowser.proxy.main.proxy_engine(proxy_request: Request) Response ¶
Proxy handler function to forward incoming requests to a target URL.
- Parameters:
proxy_request – The incoming request object.
- Returns:
The response object with the forwarded content and headers.
- Return type:
Response
Templates¶
Constructs an error page using jina template for service unavailable.
- Returns:
HTML content as string.
- Return type:
str
- pyfilebrowser.proxy.templates.templates.forbidden(origin: str) str ¶
Constructs an error page using jina template for forbidden response.
- Parameters:
origin – Origin that is forbidden.
- Returns:
HTML content as string.
- Return type:
str
- pyfilebrowser.proxy.templates.templates.unsupported_browser(user_agent: UserAgent) str ¶
Constructs a warning page using jina template for unsupported browsers.
- Parameters:
user_agent – User agent object.
- Returns:
HTML content as string.
- Return type:
str
Rate Limit¶
- class pyfilebrowser.proxy.rate_limit.RateLimiter(rps: RateLimit)¶
Object that implements the
RateLimiter
functionality.>>> RateLimiter
Instantiates the object with the necessary args.
- Parameters:
rps – RateLimit object with
max_requests
andseconds
.
- max_requests¶
Maximum requests to allow in a given time frame.
- seconds¶
Number of seconds after which the cache is set to expire.
- init(request: Request) None ¶
Checks if the number of calls exceeds the rate limit for the given identifier.
- Parameters:
request – The incoming request object.
- Raises:
429 – Too many requests.
Repeated Timer¶
- class pyfilebrowser.proxy.repeated_timer.RepeatedTimer(interval: int, function: Callable, args: Tuple = None, kwargs: Dict[str, Any] = None)¶
Instantiates RepeatedTimer object to kick off the threading.Timer object with custom intervals.
>>> RepeatedTimer
Repeats the
Timer
object from threading.- Parameters:
interval – Interval in seconds.
function – Function to trigger with intervals.
args – Arguments for the function.
kwargs – Keyword arguments for the function.
- _run()¶
Triggers the target function.
- start()¶
Trigger target function if timer isn’t running already.
- stop()¶
Stop the timer and cancel all futures.
- cancel()¶
Initiate cancellation.
Secure¶
- pyfilebrowser.proxy.secure.calculate_hash(value: Any) str ¶
Generate hash value for the given payload.
- pyfilebrowser.proxy.secure.base64_encode(value: Any) str ¶
Base64 encode the given payload.
- pyfilebrowser.proxy.secure.base64_decode(value: Any) str ¶
Base64 decode the given payload.
- pyfilebrowser.proxy.secure.hex_decode(value: Any) str ¶
Convert hex value to a string.
- pyfilebrowser.proxy.secure.hex_encode(value: str) str ¶
Convert string value to hex.
Server¶
- class pyfilebrowser.proxy.server.ProxyServer(config: Config)¶
Shared ProxyServer state that is available between all protocol instances.
>>> ProxyServer
References
https://github.com/encode/uvicorn/issues/742#issuecomment-674411676
- run_in_parallel(logger: Logger) None ¶
Initiates the server in a dedicated process.
- Parameters:
logger – Server’s original logger.
See also
Initiates a background task to refresh the allowed origins at given interval.
- pyfilebrowser.proxy.server.proxy_server(server: str, log_config: dict, auth_map: Dict[str, str]) None ¶
Triggers the proxy engine in parallel.
- Parameters:
server – Server URL that has to be proxied.
log_config – Server’s logger object.
auth_map – Server’s authorization mapping.
See also
Creates a logging configuration similar to the main logger.
Adds the rate limit dependency, per the user’s selection.
Adds CORS Middleware settings, and loads the uvicorn config.
Squire¶
- pyfilebrowser.proxy.squire.log_connection(request: Request) starlette.responses.HTMLResponse | None ¶
Logs the connection information and returns an HTML response if the browser is unsupported for video/audio.
See also
Only logs the first connection from a device.
This avoids multiple logs when same device is accessing different paths.
- Returns:
Returns an HTML response if the browser is unsupported for video/audio rendering.
- Return type:
HTMLResponse
- pyfilebrowser.proxy.squire.extract_credentials(authorization: bytes) Generator[str] ¶
Extract the credentials from
Authorization
headers and decode it before returning as a list of strings.- Parameters:
authorization – Authorization header value.
See also
Decodes the base64-encoded value (JavaScript’s built-in encoding
btoa
)Converts hex encoded value to string
// Converts a string into a hex async function ConvertStringToHex(str) { let arr = []; for (let i = 0; i < str.length; i++) { arr[i] = ("00" + str.charCodeAt(i).toString(16)).slice(-4); } return "\\u" + arr.join("\\u"); } // Expected encryption and encoding for authorization header let hex_user = await ConvertStringToHex(username); let signature = await CalculateHash(password); let hex_recaptcha = await ConvertStringToHex(recaptcha); let authHeader = btoa(hex_user + "," + signature + "," + hex_recaptcha) // eslint-disable-line
- Yields:
Generator[str] – Yields parts of the extracted credentials.
- pyfilebrowser.proxy.squire.proxy_auth(authorization: bytes | None) Optional[Dict[str, str]] ¶
Authenticate proxy request.
- Parameters:
authorization – Authorization header value.
See also
Creates a hash of the password with cryptographic encryption and compares with the received hash
// Converts a string into a hash using cryptographic encryption async function CalculateHash(message) { const encoder = new TextEncoder(); const data = encoder.encode(message); if (crypto.subtle === undefined) { const wordArray = CryptoJS.lib.WordArray.create(data); const hash = CryptoJS.SHA512(wordArray); return hash.toString(CryptoJS.enc.Hex); } else { const hashBuffer = await crypto.subtle.digest("SHA-512", data); const hashArray = Array.from(new Uint8Array(hashBuffer)); return hashArray.map((byte) => byte.toString(16).padStart(2, "0")).join(""); } }
- Returns:
Returns a dict of username, password and recaptcha value.
- Return type:
Dict[str, str]
Settings¶
- class pyfilebrowser.proxy.settings.Destination(pydantic.BaseModel)¶
Server’s destination settings.
>>> Destination
Create a new model by parsing and validating input data from keyword arguments.
Raises [ValidationError][pydantic_core.ValidationError] if the input data cannot be validated to form a valid model.
self is explicitly positional-only to allow self as a field name.
- url: Url¶
- auth_config: Dict[str, str]¶
- class pyfilebrowser.proxy.settings.EnvConfig(pydantic_settings.BaseSettings)¶
Configure all env vars and validate using
pydantic
to share across modules.>>> EnvConfig
Create a new model by parsing and validating input data from keyword arguments.
Raises [ValidationError][pydantic_core.ValidationError] if the input data cannot be validated to form a valid model.
self is explicitly positional-only to allow self as a field name.
- host: str¶
- port: int¶
- workers: int¶
- debug: bool¶
- origins: List[Url]¶
- database: str¶
- allow_public_ip: bool¶
- allow_private_ip: bool¶
- origin_refresh: Optional[int]¶
- unsupported_browsers: Union[str, List[str]]¶
- warn_page: Path¶
- error_page: Path¶
- classmethod parse_unsupported_browsers(unsupported_browsers: Union[str, List[str]]) Union[List[str], List] ¶
Validate unsupported_browsers and convert to list.
- classmethod parse_origins(origins: List[Url]) Union[List[str], List] ¶
Validate origins’ input as a URL, and stores only the host part of the URL.
- class pyfilebrowser.proxy.settings.RateLimit(pydantic.BaseModel)¶
Object to store the rate limit settings.
>>> RateLimit
Create a new model by parsing and validating input data from keyword arguments.
Raises [ValidationError][pydantic_core.ValidationError] if the input data cannot be validated to form a valid model.
self is explicitly positional-only to allow self as a field name.
- max_requests: int¶
- seconds: int¶
- class pyfilebrowser.proxy.settings.Session(pydantic.BaseModel)¶
Object to store session information.
>>> Session
Create a new model by parsing and validating input data from keyword arguments.
Raises [ValidationError][pydantic_core.ValidationError] if the input data cannot be validated to form a valid model.
self is explicitly positional-only to allow self as a field name.
- auth_counter: Dict[str, int]¶
- forbid: Set[str]¶
- info: Dict[str, str]¶
- rps: Dict[str, int]¶
- allowed_origins: Set[str]¶
——–PyFB API Client——–¶
Main Module¶
- class pyfilebrowser.main.FileBrowser(**kwargs)¶
Object to handle the filebrowser streaming.
>>> FileBrowser
Instantiates the object.
- Keyword Arguments:
logger – Bring your own logger.
proxy – Boolean flag to enable proxy.
extra_env – JSON or YAML filename to load extra settings.
See also
extra_env
is a feature to load additional configuration settings to the filebrowser server.This is useful when you want to load custom settings that are not available in the default configuration.
- The file should be a JSON or YAML file with the following structure:
The key should be the same as the configuration setting in the filebrowser. Example:
server
The value should also be a dictionary, with the custom setting.
The file should be placed in the same directory as the script that invokes the filebrowser.
The filename should be passed as a keyword argument to the
FileBrowser
object.
- cleanup(log: bool = True) None ¶
Removes the config and proxy database.
- exit_process() None ¶
Deletes the database file, and all the subtitles that were created by this application.
- run_subprocess(arguments: List[str] = None, failed_msg: str = None, stdout: bool = False) None ¶
Run
filebrowser
commands as subprocess.- Parameters:
arguments – Arguments to pass to the binary.
failed_msg – Failure message in case of bad return code.
stdout – Boolean flag to show/hide standard output.
- create_users() Dict[str, str] ¶
Creates the JSON file for user profiles.
- Returns:
Authentication map provided as environment variables.
- Return type:
Dict[str, str]
- create_config() None ¶
Creates the JSON file for configuration.
- import_config() None ¶
Imports the configuration file into filebrowser.
- import_users() Dict[str, str] ¶
Imports the user profiles into filebrowser.
- Returns:
Authentication map provided as environment variables.
- Return type:
Dict[str, str]
- background_tasks(auth_map: Dict[str, str]) None ¶
Initiates the proxy engine and subtitles’ format conversion as background tasks.
- Parameters:
auth_map – Authentication map provided as environment variables.
- start() None ¶
Handler for all the functions above.
Modals¶
Configuration¶
- class pyfilebrowser.modals.config.Server(pydantic_settings.BaseSettings)¶
Configuration settings [
server
section] for the server.>>> Server
Create a new model by parsing and validating input data from keyword arguments.
Raises [ValidationError][pydantic_core.ValidationError] if the input data cannot be validated to form a valid model.
self is explicitly positional-only to allow self as a field name.
- root: Path¶
- baseURL: Optional[str]¶
- socket: Optional[str]¶
- tlsKey: Optional[Union[Path, str]]¶
- tlsCert: Optional[Union[Path, str]]¶
- port: Optional[int]¶
- address: Optional[str]¶
- enableThumbnails: Optional[bool]¶
- resizePreview: Optional[bool]¶
- enableExec: Optional[bool]¶
- typeDetectionByHeader: Optional[bool]¶
- authHook: Optional[str]¶
- tokenExpirationTime: Optional[str]¶
- class pyfilebrowser.modals.config.Branding(pydantic_settings.BaseSettings)¶
Configuration for the custom branding settings for the server.
>>> Branding
See also
Environment variables should be prefixed with
branding_
, and present in.config.env
Create a new model by parsing and validating input data from keyword arguments.
Raises [ValidationError][pydantic_core.ValidationError] if the input data cannot be validated to form a valid model.
self is explicitly positional-only to allow self as a field name.
- name: Optional[str]¶
- disableExternal: Optional[bool]¶
- disableUsedPercentage: Optional[bool]¶
- files: Optional[Path]¶
- color: Optional[str]¶
- class pyfilebrowser.modals.config.Tus(pydantic_settings.BaseSettings)¶
Configuration for the upload settings in the server.
>>> Tus
See also
Environment variables should be prefixed with
tus_
, and present in.config.env
Create a new model by parsing and validating input data from keyword arguments.
Raises [ValidationError][pydantic_core.ValidationError] if the input data cannot be validated to form a valid model.
self is explicitly positional-only to allow self as a field name.
- chunkSize: Optional[int]¶
- retryCount: Optional[int]¶
- class pyfilebrowser.modals.config.Defaults(pydantic_settings.BaseSettings)¶
Configuration for all the default settings for the server.
>>> Defaults
See also
Environment variables should be prefixed with
defaults_
, and present in.config.env
Create a new model by parsing and validating input data from keyword arguments.
Raises [ValidationError][pydantic_core.ValidationError] if the input data cannot be validated to form a valid model.
self is explicitly positional-only to allow self as a field name.
- scope: Optional[str]¶
- locale: Optional[str]¶
- viewMode: Optional[str]¶
- singleClick: Optional[bool]¶
- commands: Optional[List[str]]¶
- hideDotfiles: Optional[bool]¶
- dateFormat: Optional[bool]¶
- class pyfilebrowser.modals.config.Commands(pydantic_settings.BaseSettings)¶
Configuration for list of the commands to be executed before or after a certain event.
>>> Commands
See also
The command runner is a feature that enables you to execute shell commands before or after a certain event.
Create a new model by parsing and validating input data from keyword arguments.
Raises [ValidationError][pydantic_core.ValidationError] if the input data cannot be validated to form a valid model.
self is explicitly positional-only to allow self as a field name.
- after_copy: Optional[List[str]]¶
- after_delete: Optional[List[str]]¶
- after_rename: Optional[List[str]]¶
- after_save: Optional[List[str]]¶
- after_upload: Optional[List[str]]¶
- before_copy: Optional[List[str]]¶
- before_delete: Optional[List[str]]¶
- before_rename: Optional[List[str]]¶
- before_save: Optional[List[str]]¶
- before_upload: Optional[List[str]]¶
- class pyfilebrowser.modals.config.Config(pydantic_settings.BaseSettings)¶
Configuration settings [
config
section] for the server.>>> Config
Create a new model by parsing and validating input data from keyword arguments.
Raises [ValidationError][pydantic_core.ValidationError] if the input data cannot be validated to form a valid model.
self is explicitly positional-only to allow self as a field name.
- signup: Optional[bool]¶
- createUserDir: Optional[bool]¶
- userHomeBasePath: Optional[str]¶
- authMethod: Optional[str]¶
- authHeader: Optional[str]¶
- shell_: Optional[List[str]]¶
- rules: Optional[List[str]]¶
- class pyfilebrowser.modals.config.ReCAPTCHA(pydantic.BaseModel)¶
Settings for ReCaptcha.
>>> ReCAPTCHA
Create a new model by parsing and validating input data from keyword arguments.
Raises [ValidationError][pydantic_core.ValidationError] if the input data cannot be validated to form a valid model.
self is explicitly positional-only to allow self as a field name.
- host: Optional[Url]¶
- key: Optional[str]¶
- secret: Optional[str]¶
- class pyfilebrowser.modals.config.Auther(pydantic_settings.BaseSettings)¶
Configuration settings [
server
section] for the server.>>> Auther
See also
Environment variables should be prefixed with
auth_
, and present in.config.env
Create a new model by parsing and validating input data from keyword arguments.
Raises [ValidationError][pydantic_core.ValidationError] if the input data cannot be validated to form a valid model.
self is explicitly positional-only to allow self as a field name.
- class pyfilebrowser.modals.config.ConfigSettings(pydantic.BaseModel)¶
Wrapper for all the configuration settings to form a nested JSON object.
>>> ConfigSettings
Create a new model by parsing and validating input data from keyword arguments.
Raises [ValidationError][pydantic_core.ValidationError] if the input data cannot be validated to form a valid model.
self is explicitly positional-only to allow self as a field name.
Models¶
- class pyfilebrowser.modals.models.Log(StrEnum)¶
Enum for different log options.
>>> Log
- stdout: Optional[str] = 'stdout'¶
- file: Optional[str] = 'file'¶
- class pyfilebrowser.modals.models.Theme(StrEnum)¶
Enum for different theme options.
>>> Theme
- light: Optional[str] = 'light'¶
- dark: Optional[str] = 'dark'¶
- blank: Optional[str] = ''¶
- class pyfilebrowser.modals.models.SortBy(StrEnum)¶
Enum for different sort-by options.
>>> SortBy
- name: str = 'name'¶
- size: str = 'size'¶
- modified: str = 'modified'¶
- class pyfilebrowser.modals.models.Sorting(pydantic.BaseModel)¶
Enum for different sorting options.
>>> Sorting
Create a new model by parsing and validating input data from keyword arguments.
Raises [ValidationError][pydantic_core.ValidationError] if the input data cannot be validated to form a valid model.
self is explicitly positional-only to allow self as a field name.
- by: str¶
- asc: bool¶
- class pyfilebrowser.modals.models.Perm(pydantic.BaseModel)¶
Permission settings for each user profile.
>>> Perm
Create a new model by parsing and validating input data from keyword arguments.
Raises [ValidationError][pydantic_core.ValidationError] if the input data cannot be validated to form a valid model.
self is explicitly positional-only to allow self as a field name.
- admin: bool¶
- execute: bool¶
- create: bool¶
- rename: bool¶
- modify: bool¶
- delete: bool¶
- download: bool¶
Users¶
- class pyfilebrowser.modals.users.Authentication(pydantic.BaseModel)¶
Authentication settings for each user profile.
>>> models.Perm
Create a new model by parsing and validating input data from keyword arguments.
Raises [ValidationError][pydantic_core.ValidationError] if the input data cannot be validated to form a valid model.
self is explicitly positional-only to allow self as a field name.
- username: Optional[str]¶
- password: Optional[str]¶
- admin: Optional[bool]¶
- class pyfilebrowser.modals.users.UserSettings(pydantic_settings.BaseSettings)¶
Profile settings for each user.
>>> UserSettings
See also
perm - Permissions are set based on the admin flag for each
Authentication
model.
Create a new model by parsing and validating input data from keyword arguments.
Raises [ValidationError][pydantic_core.ValidationError] if the input data cannot be validated to form a valid model.
self is explicitly positional-only to allow self as a field name.
- authentication: Optional[Authentication]¶
- scope: Optional[str]¶
- locale: Optional[str]¶
- lockPassword: Optional[bool]¶
- viewMode: Optional[str]¶
- singleClick: Optional[bool]¶
- commands: Optional[List[str]]¶
- rules: Optional[List[str]]¶
- hideDotfiles: Optional[bool]¶
- dateFormat: Optional[bool]¶
- classmethod from_env_file(env_file: Optional[str]) UserSettings ¶
Create UserSettings instance from environment file.
- Parameters:
env_file – Name of the env file.
- Returns:
Loads the
UserSettings
model.- Return type:
- classmethod validate_password_complexity(value: Authentication) Union[Authentication, Dict] ¶
Field validator for password.
- Parameters:
value – Value as entered by the user.
- Returns:
Returns an
Authentication
object or a dictionary with the authentication payload.- Return type:
Authentication | Dict
Squire¶
Download¶
- class pyfilebrowser.squire.download.Executable(pydantic.BaseModel)¶
Executable object to load all the objects to download the executable from releases.
>>> Executable
Create a new model by parsing and validating input data from keyword arguments.
Raises [ValidationError][pydantic_core.ValidationError] if the input data cannot be validated to form a valid model.
self is explicitly positional-only to allow self as a field name.
- system: str¶
- machine: str¶
- filebrowser_os: str¶
- filebrowser_bin: Path¶
- filebrowser_dl_ext: str¶
- filebrowser_arch: str¶
- filebrowser_file: Path¶
- filebrowser_db: Path¶
- class pyfilebrowser.squire.download.GitHub(pydantic.BaseSettings)¶
Custom GitHub account information loaded using multiple env prefixes.
>>> GitHub
Create a new model by parsing and validating input data from keyword arguments.
Raises [ValidationError][pydantic_core.ValidationError] if the input data cannot be validated to form a valid model.
self is explicitly positional-only to allow self as a field name.
- owner: str¶
- repo: str¶
- token: str | None¶
- version: str¶
- pyfilebrowser.squire.download.alias_choices(variable: str) AliasChoices ¶
Custom alias choices for environment variables for GitHub.
- Parameters:
variable – Variable name.
- Returns:
Returns the alias choices for the variable.
- Return type:
AliasChoices
Steward¶
- class pyfilebrowser.squire.steward.EnvConfig(pydantic.BaseModel)¶
Configure all env vars and validate using
pydantic
to share across modules.>>> EnvConfig
Create a new model by parsing and validating input data from keyword arguments.
Raises [ValidationError][pydantic_core.ValidationError] if the input data cannot be validated to form a valid model.
self is explicitly positional-only to allow self as a field name.
- user_profiles: List[UserSettings]¶
- config_settings: ConfigSettings¶
- classmethod load_user_profiles() List[UserSettings] ¶
Load UserSettings instances from .env files in the current directory.
- Returns:
Returns a list of
UserSettings
objects.- Return type:
List[users.UserSettings]
- class pyfilebrowser.squire.steward.FileIO(pydantic.BaseModel)¶
FileIO object to load the JSON files.
>>> FileIO
Create a new model by parsing and validating input data from keyword arguments.
Raises [ValidationError][pydantic_core.ValidationError] if the input data cannot be validated to form a valid model.
self is explicitly positional-only to allow self as a field name.
- settings_dir: Path¶
- config: Path¶
- users: Path¶
- pyfilebrowser.squire.steward.ordinal(n: int) str ¶
Returns the ordinal representation of a given number.
- Parameters:
n – The number for which the ordinal representation is to be determined.
- Returns:
The ordinal representation of the input number.
- Return type:
str
- pyfilebrowser.squire.steward.default_logger(log_to_file: bool) Logger ¶
Generates a default console logger.
- Parameters:
log_to_file – Boolean flag to stream logs to a file.
- Returns:
Logger object.
- Return type:
logging.Logger
- pyfilebrowser.squire.steward.hash_password(password: str) str ¶
Returns a salted hash for the given text.
- Parameters:
password – Password as plain text.
- Returns:
Decoded hashed password as a string.
- Return type:
str
- pyfilebrowser.squire.steward.validate_password(password: str, hashed_password: str) bool ¶
Validates whether the hashed password matches the text version.
- Parameters:
password – Password as plain text.
hashed_password – Hashed password.
- Returns:
Returns a boolean flag to indicate whether the password matches.
- Return type:
bool
- pyfilebrowser.squire.steward.remove_trailing_underscore(dictionary: dict) dict ¶
Iterates through the dictionary and removes any key ending with an ‘_’ underscore.
- Parameters:
dictionary – Any nested dictionary.
- Returns:
Returns the same nested dictionary, removing trailing underscore in the keys.
- Return type:
dict
- pyfilebrowser.squire.steward.remove_prefix(text: str) str ¶
Returns the message part from the default log output from filebrowser.
Struct¶
- class pyfilebrowser.squire.struct.LoggerConfig(logger: Logger)¶
Creates a dictionary of the given logger’s configuration.
>>> LoggerConfig
Instantiates the object.
- Parameters:
logger – Custom logger.
- extract() Tuple[dict, dict] ¶
Extracts the handlers and formatters.
- Returns:
Returns a tuple of handlers and formatters, each as dictionary representation.
- Return type:
Tuple[dict, dict]
- get() Dict[str, Union[dict, int, Dict[str, Dict[str, Union[str, int, bool, List[str]]]]]] ¶
Returns logger’s full configuration which can be re-used to create new logger objects with the same config.
- Returns:
Returns the log configration.
- Return type:
Dict[str, dict | int | Dict[str, Dict[str, str | int | bool | List[str]]]]
- pyfilebrowser.squire.struct.update_log_level(data: dict, new_value: Any) dict ¶
Recursively update the value where any key equals “level”, for loggers and handlers.
- Parameters:
data – The nested dictionary to traverse.
new_value – The new value to set where the key equals “level”.
- Returns:
The updated nested dictionary.
- Return type:
dict