Documentation#
Server#
Server.py contains two function: server.home_page()
processing server information output, and server.websocket_endpoint()
responds connections for clients.
MTP protocol#
Read fully description about stable version of MTP protocol to this link.
To work with MTP protocol server used protocol.mtp
module which included these classes:
MTPErrorResponse
MTProtocol
Response
Request
MTPErrorResponse#
Return response object with validation:
MTProtocol#
Processing all methods contains MTP protocol description:
Validations Response#
Processing results of MTPProtocol methods with following validation and generate response in JSON format:
Validations Request#
Processing response received from clients with following validation and generate error code when response not corresponds protocol methods:
Matrix protocol#
Read fully description about latest version of Matrix protocol to this link.
MatrixProtocol#
Processing half methods contains Matrix protocol description:
Validations Response#
Processing results of MatrixProtocol methods with following validation and generate response in JSON format:
Validations Request#
Processing response received from clients with following validation and generate error code when response not corresponds protocol methods:
Database#
DBhandler#
High layer class has to work with database without query in raw SQL:
- class mod.db.dbhandler.DBHandler(uri: str = 'sqlite:/:memory:', debug: bool = False, logger: str = 'stderr', loglevel: str = 'critical', path_to_models: str = 'mod.db.models')#
A layer for interaction with the database ORM. As a method prescribed frequently used actions with data from database.
- Parameters
uri – [name of DB-API]:/:[directory or url or ‘memory’] like that sqlite:/:memory:
debug – enable or disable debug messages
logger – name of logger
loglevel – standard logging levels: info, debug, error. or stderr, stdout
path_to_models – path to the location of the file describing database tables
- __read_db(table: str, get_one: bool, **kwargs) sqlobject.sresults.SelectResults | sqlobject.main.SQLObject #
Universal method for read data in database.
- Parameters
table – name of table
get_one – sets how many objects will be returned, True for one object or False for many object
**kwargs – dict contains name of column and data
- Returns
ORM object contains one or many row from database
- Raises
DatabaseReadError – occurs when there is no table in the database, there was a problem at the stage of reading from database
DatabaseAccessError – occurs when there is an unknown problem when reading from database
- __repr__() str #
Return class name and parameters send to class when is created.
- __search_db_in_models() tuple #
Search all class name which contains in models.
- Returns
name of table
- __str__() str #
Returned string which contains URI for connected database.
- __write_db(**kwargs) sqlobject.main.SQLObject #
Universal method for write data in database.
- Parameters
table – name of table
**kwargs – dict contains name of column and data
- Return type
(SQLObject)
- Raises
DatabaseWriteError – occurs when there is an unknown problem when writing to database
- _logger: Optional[str]#
- _loglevel: Optional[str]#
- add_admin(username: str, hash_password: str) sqlobject.main.SQLObject #
Added new admin to the Admin table.
- Parameters
username – name user which granted administrator rights
hash_password – hash-function generated from administrator password
- Return type
(SQLObject)
- add_flow(uuid: str, users: list | tuple, time_created: Optional[int] = None, flow_type: Optional[str] = None, title: Optional[str] = None, info: Optional[str] = None, owner: Optional[str] = None) sqlobject.main.SQLObject #
Added new flow to the Flow table.
- Parameters
uuid – unique identify number from flow
users – uuid user which used that flow
time_created – time when created flow
flow_type –
chat
orgroup
orchannel
title – name added in public information about flow
info – text added in public information about flow
owner – user uuid which created that flow
- Return type
(SQLObject)
- add_message(flow_uuid: str, user_uuid: str, message_uuid: str, time: int, text: Optional[str] = None, picture: Optional[bytes] = None, video: Optional[bytes] = None, audio: Optional[bytes] = None, document: Optional[bytes] = None, emoji: Optional[bytes] = None) sqlobject.main.SQLObject #
Added new message to the Message table.
Notes
Before adding a message to the “Message” table, the presence of “flow” and “user” in the database is checked.
- Parameters
flow_uuid – unique identify number from flow
user_uuid – unique user identify number
message_uuid – unique identify number from message
time – Unix-like time
text – message text
picture – appending image
video – appending video
audio – appending audio
document – appending document
emoji – appending emoji image
- Return type
(SQLObject)
- add_user(uuid: str, login: str, password: str, hash_password: Optional[str] = None, username: Optional[str] = None, is_bot: bool = False, auth_id: Optional[str] = None, token_ttl: Optional[int] = None, email: Optional[str] = None, avatar: Optional[bytes] = None, bio: Optional[str] = None, salt: Optional[bytes] = None, key: Optional[bytes] = None) sqlobject.main.SQLObject #
Added new user to the UserConfig table. If salt or key is None then used blank string converted to bytes.
- Parameters
uuid – unique user identify number
login – user login
password – user password
hash_password – hash from password
username – public username
is_bot – type of user
auth_id – authenticate token
token_ttl – time to live auth_id token
email – user email
avatar – user image or photo
bio – text information about user
salt – secret bytes string
key – secrets bytes string
- Return type
(SQLObject)
- create_table() None #
Create all table which contains in models.
- property debug: bool#
Shows is flag set in property debug.
- Returns
True or False
- delete_table() None #
Delete all table which contains in models.
- get_admin_by_name(username: str) sqlobject.main.SQLObject #
Gives user by name from Admin table.
- Parameters
username – name user which granted administrator rights
- Return type
(SQLObject)
- get_all_admin() sqlobject.sresults.SelectResults #
Gives out all users from Admin table.
- Return type
(SelectResults)
- get_all_flow() sqlobject.sresults.SelectResults #
Gives out all flow from Flow table.
- Return type
(SelectResults)
- get_all_message() sqlobject.sresults.SelectResults #
Gives out all message contains Message table.
- Return type
(SelectResults)
- get_all_user() sqlobject.sresults.SelectResults #
Gives out all user contains in UserConfig table.
- Return type
(SelectResult)
- static get_flow_by_exact_time(time: int) sqlobject.sresults.SelectResults #
Gives out flow by time == requested time.
- Parameters
time – Unix-like time
- Return type
(SelectResults)
- static get_flow_by_less_time(time: int) sqlobject.sresults.SelectResults #
Gives out flow by time <= requested time.
- Parameters
time – Unix-like time
- Return type
(SelectResults)
- static get_flow_by_more_time(time: int) sqlobject.sresults.SelectResults #
Gives flow by time => requested time.
- Parameters
time – Unix-like time
- Return type
(SelectResults)
- get_flow_by_title(title: str) sqlobject.sresults.SelectResults #
Gives out flow by title which contains in Flow table.
- Parameters
title – name added in public information about flow
- Return type
(SelectResults)
- get_flow_by_uuid(uuid: str) sqlobject.main.SQLObject #
Gives out one flow by uuid from Flow table.
- Parameters
uuid – unique user identify number
- Return type
(SQLObject)
- static get_message_by_exact_time(time: int) sqlobject.sresults.SelectResults #
Gives out message by time == requested time.
- Parameters
time – Unix-like time
- Return type
(SelectResults)
- get_message_by_exact_time_and_flow(flow_uuid: str, time: int) sqlobject.sresults.SelectResults #
Gives out message by flow and time == requested time.
- Parameters
flow_uuid – unique identify number from flow
time – Unix-like time
- Return type
(SelectResults)
- static get_message_by_less_time(time: int) sqlobject.sresults.SelectResults #
Gives out message by time <= requested time.
- Parameters
time – Unix-like time
- Return type
(SelectResults)
- get_message_by_less_time_and_flow(flow_uuid: str, time: int) sqlobject.sresults.SelectResults #
Gives out message by flow and time <= requested time.
- Parameters
flow_uuid – unique identify number from flow
time – Unix-like time
- Return type
(SelectResults)
- static get_message_by_more_time(time: int) sqlobject.sresults.SelectResults #
Gives out message by time >= requested time.
- Parameters
time – Unix-like time
- Return type
(SelectResults)
- get_message_by_more_time_and_flow(flow_uuid: str, time: int) sqlobject.sresults.SelectResults #
Gives out message by flow and time >= than requested.
- Parameters
flow_uuid – unique identify number from flow
time – Unix-like time
- Return type
(SelectResults)
- get_message_by_text(text: str) sqlobject.sresults.SelectResults #
Gives out all message which contains desired text string.
- Parameters
text – text string to be found
- Return type
(SelectResults)
- get_message_by_uuid(uuid: str) sqlobject.main.SQLObject #
Gives out one message by uuid which contains in Message table.
- Parameters
uuid – unique user identify number
- Return type
(SQLObject)
- get_table_count() Any #
Gives out quantity all row from Message, Flow or UserConfig table.
- Returns
where
user_count
- quantity all UserConfig rowflow_count
- quantity all Flow rowmessage_count
- quantity all Message row- Return type
(namedtuple)
- get_user_by_login(login: str) sqlobject.main.SQLObject #
Gives out user by login contains in UserConfig table.
- Parameters
login – user login
- Return type
(SQLObject)
- get_user_by_login_and_password(login: str, password: str) sqlobject.main.SQLObject #
Gives out user by login and password contains in UserConfig table.
- Parameters
login – user login
password – user password
- Return type
(SQLObject)
- get_user_by_uuid(uuid: str) sqlobject.main.SQLObject #
Gives out user by uuid contains in UserConfig table.
- Parameters
uuid – unique user identify number
- Return type
(SQLObject)
- update_flow(uuid: str, flow_type: Optional[str] = None, title: Optional[str] = None, info: Optional[str] = None, owner: Optional[str] = None) str #
Update information about flow which contains in Flow table.
- Parameters
uuid – unique identify number from flow
flow_type –
chat
orgroup
orchannel
title – name added in public information about flow
info – text added in public information about flow
owner – user uuid which created that flow
- Returns
“Updated” message
- update_message(uuid: str, text: Optional[str] = None, picture: Optional[bytes] = None, video: Optional[bytes] = None, audio: Optional[bytes] = None, document: Optional[bytes] = None, emoji: Optional[bytes] = None, edited_time: Optional[int] = None, edited_status: bool = False) str #
Update message content which contains in Message table.
- Parameters
uuid – unique identify number from message
text – message text
picture – appending image
video – appending video
audio – appending audio
document – appending document
emoji – appending emoji image
edited_time – time when user last time is corrected his message
edited_status – True if user corrected his message
- Returns
“Updated” message
- update_user(uuid: str, login: Optional[str] = None, password: Optional[str] = None, hash_password: Optional[str] = None, username: Optional[str] = None, is_bot: bool = False, auth_id: Optional[str] = None, token_ttl: Optional[int] = None, email: Optional[str] = None, avatar: Optional[bytes] = None, bio: Optional[str] = None, key: Optional[bytes] = None, salt: Optional[bytes] = None) str #
Updating information in the table UserConfig.
- Parameters
uuid – unique user identify number
login – user login
password – user password
hash_password – hash from password
username – public username
is_bot – type of user
auth_id – authenticate token
token_ttl – time to live auth_id token
email – user email
avatar – user image or photo
bio – text information about user
salt – secret bytes string
key – secrets bytes string
- Returns
“Updated” message
Models#
UserConfig#
UserConfig table where saving user secure and personal information:
- class mod.db.models.UserConfig(**kw)#
Table containing data about user and his settings.
- Parameters
uuid (
str, required, unique
) – unique user id which automated generating serverlogin (
str, required
) – name for authentication on serverpassword (
str, required
) – password for authentication on serverhash_password (
str, optional
) – hash-function generated from user passwordusername (
str, optional
) – name for added in information about useris_bot (
bool, optional
) – True if user not humanauth_id (
str, optional
) – authentication tokenemail (
str, optional
) – user email for added in information about useravatar (
str, optional
) – user image for added in information about userbio (
str, optional
) – text for added in information about usersalt (
str, optional
) – added in password string for create hash_passwordkey (
str, optional
) – added in password string for create hash_password
Flow#
Flow table where saving flow information:
- class mod.db.models.Flow(**kw)#
Flow table containing information about threads and their types.
- Parameters
uuid (
str, required, unique
) – unique flow id which automated generating servertime_created (
int, optional
) – data and time when flow is createdflow_type (
str, optional
) – which contains chat, channel, grouptitle (
str, optional
) – name added in public information about flowinfo (
str, optional
) – text added in public information about flow
Message#
Message table where saving message information:
- class mod.db.models.Message(**kw)#
Message table containing information about user messages.
- Parameters
uuid (
str, required, unique
) – unique flow id which automated generating servertext (
str, optional
) – contains message texttime (
int, optional
) – time when message is createdfile_picture (
byte, optional
) – contains appended imagefile_video (
byte, optional
) – contains appended videofile_audio (
byte, optional
) – contains appended audiofile_document (
byte, optional
) – contains appended documentemoji (
str, optional
) – contains appended image/emojiedited_time (
int, optional
) – time when user last time is corrected his messageedited_status (
bool, optional
) – True if user corrected his message
Admin#
Admin table where saving access rights for web administration panel:
- class mod.db.models.Admin(**kw)#
Admin table containing information about users with administrators role.
- Parameters
username (
str, required, unique
) – name user which granted administrator rightshash_password (
str, required
) – hash-function generated from administrator password
Controller#
MainHandler#
Class identifies and redirects requests with accordance type of protocol:
Error#
Contains several new error code which additional for standard HTTP error code:
- class mod.error.ServerStatus(value)#
Additional server status code and reason phrases.
Notes
CLIENT_CLOSED_REQUEST - 499
VERSION_NOT_SUPPORTED - 505
UNKNOWN_ERROR - 520
INVALID_SSL_CERTIFICATE - 526
Checking matching status code name and type of errors contains in class mod.error.ServerStatus
or HTTPStatus
- mod.error.check_error_pattern(status: str) mod.error.CatchError #
Checks error name against existing error types supported by server. The error name is passed as a “status” parameter.
- Parameters
status – error name
- Returns
named tuple with three value, where
value
- status code of errorphrase
- status name of errordescription
- short description of the error- Raises
AttributeError – raised when an error name is not found among the registered names (in classes ServerStatus and HTTPStatus)
TypeError – raised when Args status does not match String type
Additional module#
Admin#
admin
Config#
Module for working with the configuration file. Allows you to read and save the basic parameters to the settings file in the root directory of the project:
Hash#
Generating a hash for a password or session. Password hash verification. Generating a user authentication token.
- class mod.lib.Hash(password: str, uuid: int | str, salt: Optional[bytes] = None, key: Optional[bytes] = None, hash_password: Optional[str] = None, size_password: int = 32, size_auth_id: int = 16)#
Generates hashes. Hash for password, sessions, checks password hashes. Authenticator token.
- Parameters
password – password
uuid – unique user identity number
salt – additional unique identifier which added to the password when generating hash_password, there can be any line e.q. mother’s maiden name, favorite writer, etc.
key – additional argument, if value is None then function will generate it automatically.
hash_password – password hash (previously calculated).
size_password – size of output password in bytes, default 32.
size_auth_id – size of output auth_id in bytes, default 16.
- auth_id() str #
Generating authenticator token for client session connection to server.
- Returns
authenticate token
- check_password() bool #
Comparison of calculated hash and original password.
- Returns
True or False
- property get_key: bytes#
Getting the value of key.
- Returns
key
- property get_salt: bytes#
Getting the value of salt.
- Returns
salt
- password_hash() str #
Generates a password hash.
- Returns
returns blake2b hash
- Return type
hash password
Logging#
Adding and configuring project logging.
- mod.log_handler.add_logging(config_option: mod.config.models.ConfigModel) None #
Enable logging depending on start parameter uvicorn and choice their level. Logging information written in .log file which contains in /log folder and also duplicated in the console.
Note
application creates two log file contains in /log folder
one for error level - error.log
one for debug level - debug.log
Examples
Instead of print we use
logger.debug('debug message')
logger.info('info message')
logger.warning('warn message')
logger.error('error message')
logger.critical('critical message')
- Parameters
debug_status (
int, requires
) –where number corresponds its level
50 - CRITICAL
40 - ERROR
30 - WARNING
25 - SUCCESS
20 - INFO
10 - DEBUG
5 - TRACE