Welcome to FileWare’s documentation!¶
Initialize¶
- fileware.__init__.initiate_connection(localhost: bool = True, secure: bool = True) Response ¶
Initiates file-server connection after trying to trigger ngrok tunnel.
- Parameters:
localhost – Takes a boolean value whether to host the server on 127.0.0.1 or local IP address.
secure – Takes a boolean flag whether to bind the ssl cert.
See also
Checks for
cert.pem
andkey.pem
files in~home/ssh
directory.If not, generates a self-signed certificate using
OpenSSL
If ngrok tunnel is running on the port already, initiates file server on localhost else uses local IP.
- fileware.__init__.is_port_in_use(port: int) bool ¶
Connect to a remote socket at address.
- Parameters:
port – Takes the port number as an argument.
- Returns:
A boolean flag to indicate whether a port is open.
- Return type:
bool
- fileware.__init__.serve(http_server: HTTPServer, process: Process = None) None ¶
Starts the file server session.
- Parameters:
http_server – Takes the HTTPServer object as an argument.
process – Process used to spin up ngrok tunnel.
- fileware.__init__.shutdown(http_server: HTTPServer, process: Process = None) None ¶
Terminates the web server and the ngrok process if available.
- Parameters:
http_server – Web server.
process – Ngrok process to end.
Server¶
- class fileware.server.Authenticator(*args: tuple, **kwargs: dict)¶
Main class to present webpages and authentication.
>>> Authenticator
Notes
Authenticator uses encrypted server side header authentication.
Browser’s default pop up will be shown prompting the user to enter the username and password.
Enter the Username and Password that was set in environment variables
The username and password are set as encoded auth headers, which are matched against the encoded env vars.
Upon successful authentication, a welcome page loads. Click on proceed to access the FileServer.
See also
To perform authentication, a do_AUTH() is implemented sending 401 and WWW-Authenticate header in response.
To handle POST requests, a do_POST() has been implemented, which reads content-length header.
Headers are read using rfile.read from the start of the optional input data.
Data is sent to server using, wfile.write which contains the output stream to write response to the client.
- disable_cache() None ¶
Headers to force no-cache and site-data to expire.
- do_AUTH() None ¶
Sends headers to authenticate the requester.
- do_GET() None ¶
Serve a front end with user authentication.
- do_HEAD() None ¶
Sends 200 response and sends headers when authentication is successful.
- do_POST() None ¶
Handles POST request and writes the received data into a yaml file.
- log_message(format_: str, *args: tuple) None ¶
Suppresses logs from
http.server
by holding the args.Overwrites the base method: BaseHTTPRequestHandler.log_message()
- Parameters:
format_ – String operator %s
*args – Logs from SimpleHTTPRequestHandler displaying request method type and HTTP status code.
Open SSL¶
- fileware.cert.generate_cert(common_name: str, email_address: str = None, country_name: str = None, locality_name: str = None, state_or_province_name: str = None, organization_name: str = None, organization_unit_name: str = 'Information Technology', validity_start_in_seconds: int = 0, validity_end_in_seconds: int = 315360000, key_file: str = 'key.pem', cert_file: str = 'cert.pem', key_size: int = 4096) bool ¶
Creates a private/self-signed certificate.
- Parameters:
common_name – DNS name of the origin.
email_address – Contact email address for the cert. Defaults to
USER@expose-localhost.com
country_name – Name of the country. Defaults to
US
locality_name – Name of the city. Defaults to
New York
state_or_province_name – Name of the state/province. Defaults to
New York
organization_name – Name of the organization. Defaults to
common_name
organization_unit_name – Name of the organization unit. Defaults to
Information Technology
validity_start_in_seconds – From when the cert validity begins. Defaults to
0
.validity_end_in_seconds – Expiration duration of the cert. Defaults to
10 years
key_file – Name of the key file.
cert_file – Name of the certificate.
key_size – Size of the public key. Defaults to 4096.
See also
Use
openssl x509 -inform pem -in cert.crt -noout -text
to look at the generated cert using openssl.- Returns:
Boolean flag to indicate whether
cert.pem
andkey.pem
files are empty.- Return type:
bool
- fileware.cert.ip_info() dict ¶
Gets public IP information.
- Returns:
JSON loaded information from public IP information.
- Return type:
dict
Response Decorator¶
- class fileware.responder.Response(dictionary: dict)¶
Class to format the response, so that it can be accessed as a property.
>>> Response
- json() dict ¶
Returns a dictionary of the argument that was received during class initialization.
- Returns:
Returns the dictionary received as arg.
- Return type:
dict
- property process: Process¶
Returns the extracted class variable.
- Returns:
Process for Ngrok.
- Return type:
Process
- property server: HTTPServer¶
Returns the extracted class variable.
- Returns:
Web Server object.
- Return type:
HTTPServer
- property url: str¶
Returns the extracted class variable.
- Returns:
Public URL from Ngrok or the local IP based endpoint.
- Return type:
str
Models¶
- class fileware.models.Config(*args, **kwargs)¶
Configuration for host and home directory.
>>> Config
- class fileware.models.EnvConfig(_case_sensitive: bool | None = None, _env_prefix: str | None = None, _env_file: DotenvType | None = PosixPath('.'), _env_file_encoding: str | None = None, _env_nested_delimiter: str | None = None, _secrets_dir: str | Path | None = None, *, username: str, password: str, port: int = 4443, host_dir: Path = '/Users/vicky', ngrok_auth: Optional[str] = None, **values: Any)¶
Env configuration.
>>> EnvConfig
References
https://docs.pydantic.dev/2.3/migration/#required-optional-and-nullable-fields
- class Config¶
Extra config for .env file and extra.
- model_config: ClassVar[SettingsConfigDict] = {'arbitrary_types_allowed': True, 'case_sensitive': False, 'env_file': '.env', 'env_file_encoding': None, 'env_nested_delimiter': None, 'env_prefix': '', 'extra': 'allow', 'protected_namespaces': ('model_', 'settings_'), 'secrets_dir': None, 'validate_default': True}¶
Configuration for the model, should be a dictionary conforming to [ConfigDict][pydantic.config.ConfigDict].
- model_fields: ClassVar[dict[str, FieldInfo]] = {'host_dir': FieldInfo(annotation=Path, required=False, default='/Users/vicky', metadata=[PathType(path_type='dir')]), 'ngrok_auth': FieldInfo(annotation=Union[str, NoneType], required=False), 'password': FieldInfo(annotation=str, required=True), 'port': FieldInfo(annotation=int, required=False, default=4443, metadata=[Gt(gt=0)]), 'username': FieldInfo(annotation=str, required=True)}¶
Metadata about the fields defined on the model, mapping of field names to [FieldInfo][pydantic.fields.FieldInfo].
This replaces Model.__fields__ from Pydantic V1.
- class fileware.models.LogConfig¶
Custom log configuration.
>>> LogConfig
- fileware.models.ngrok_logger() Logger ¶
Creates a log file for ngrok logs and configures the logging config for ngrok logger.
- Returns:
Returns logger config for ngrok.
- Return type:
logging.Logger
- fileware.models.server_logger() Logger ¶
Creates a log file for server logs and configures the logging config for server logger.
- Returns:
Returns logger config for server.
- Return type:
logging.Logger
Ngrok¶
- fileware.ngrok.connect(new_connection: bool = False) Union[Tuple[socket, Url], Tuple[None, None]] ¶
Creates an HTTP socket and uses pyngrok module to bind the socket.
- Parameters:
new_connection – Takes a boolean flag whether to spin up a new connection.
Once the socket is bound, the listener is activated and runs in a forever loop accepting connections.
See also
Run the following code to setup.
from pyngrok.conf import PyngrokConfig, get_default from pyngrok.ngrok import set_auth_token # Sets auth token only during run time without modifying global config. PyngrokConfig.auth_token = '<NGROK_AUTH_TOKEN>' # Uses auth token from the specified file without modifying global config. get_default().config_path = "/path/to/config.yml" # Changes auth token at $HOME/.ngrok2/ngrok.yml set_auth_token('<NGROK_AUTH_TOKEN>')
- Returns:
A tuple of the connected socket and the public URL.
- Return type:
Tuple[socket, HttpUrl]
- fileware.ngrok.get_ngrok(public: bool = True) str ¶
Identifies if an existing ngrok tunnel by sending a GET request to api/tunnels to get the ngrok public url.
- Parameters:
public – Boolean flag, whether to get the public or private endpoint.
See also
Checks for output from get_port function. If nothing, then ngrok isn’t running. However, as a sanity check, the script uses port number stored in env var to make a GET request.
- Returns:
On success, returns the ngrok public URL.
On failure, returns None to exit function.
- Return type:
str or None
- fileware.ngrok.tunnel(sock: socket) None ¶
Initiates tunneling in a never ending loop.
- Parameters:
sock – Takes the connected socket as an argument.
Settings¶
Place for all necessary arguments accessed across multiple modules.
Volume¶
- class fileware.helpers.volume.Volume(label)¶
Initiates Volume object to mount, unmount and stop the disk usage.
>>> Volume
- mount_disk_by_label() None ¶
Uses a terminal command to mount the disk using the volume name.
- mount_disk_by_uuid() None ¶
Tries to mount the disk using UUID which is updated by the unmount_disk function.
Calls mount_disk_by_label if UUID is None.
- stop_usage() None ¶
Kills all the background processes utilizing the volume to stop the disk usage.
- unmount_disk() None ¶
Ejects the disk from parent device.
- fileware.helpers.volume.device_model() str ¶
Uses sysctl command to get the device model and version information.
- Returns:
Model of the parent device.
- Return type:
str
- fileware.helpers.volume.extract_str(input_) str ¶
Extracts strings from the received input.
- Parameters:
input_ – Un-formatted string.
- Returns:
A perfect string.
- Return type:
str