unaiverse.networking.p2p.files¶
A file message is a direct message whose FILE samples do not carry their bytes. The native networking library sends the files next to the message in chunks. It reads them from disk on the sender and writes them to disk on the receiver. This module holds the Python side of that path. It chooses the samples of an outgoing message that are streamed from disk. It also decides where a received file is written while its chunks arrive and where it is moved once its message is complete. Every function is called by P2P and never by the developer. The module uses the standard library only.
A file message needs the support of both ends. The sender streams a file only when its library supports it (P2P.supports_file_stream) and the Session of the peer announced CAP_FILE_STREAM in its handshake (see sess_msg). Any other peer receives the bytes inside the message. That message then obeys the size limits of a normal message (see Networking).
The life of a received file has three steps.
- While the chunks arrive, the library writes them to a
.partfile in the incoming folder of the instance (<downloads>/.incoming/<peer ID of the instance>/). - When the message is complete and popped,
P2P.get_messagescallsplace_received_filefor each file. The file is renamed to<downloads>/<handle>/<node name>/<filename>and the FILE sample of the message receives that path. - A message that cannot be delivered (undecodable, a sender mismatch, a file that cannot be placed) has its files removed with
remove_quietly.
The downloads folder is Custom.DOWNLOADS_DIR when that constant is not empty and ~/.unaiverse/Downloads otherwise (%APPDATA%\Local\unaiverse\Downloads on Windows). A file larger than Custom.MAX_FILE_SIZE bytes is refused (0, the default, means no limit) and Custom.ACCEPT_FILES = False makes the node refuse file messages altogether.
The name of the subfolder of the downloads folder where files are written while their chunks arrive (".incoming"). Several nodes of one machine can share the downloads folder because each P2P instance writes in its own subfolder named after its peer ID.
The name given to a received file whose name is empty once safe_name has cleaned it ("file").
downloads_dir
¶
Source code in unaiverse/networking/p2p/files.py
Returns the absolute path of the folder of the received files as a str. The path is Custom.DOWNLOADS_DIR with ~ expanded when that constant is not empty. Otherwise it is the Downloads subfolder of the application folder of the SDK, the same folder that holds the key of the node. The function creates the application folder when it does not exist. The Downloads folder itself is never created here.
>>> from unaiverse.networking.p2p import files
>>> files.downloads_dir()
'/home/ada/.unaiverse/Downloads'
incoming_dir
¶
Source code in unaiverse/networking/p2p/files.py
Returns <downloads_dir()>/.incoming as an absolute path. P2P.setup_library reads the value once per process and passes it to the native networking library as the place where incoming files are written.
clear_incoming
¶
Source code in unaiverse/networking/p2p/files.py
Deletes the incoming subfolder of one instance and its content. A previous run may have left there the .part files of messages that never completed and the files of messages that were never popped.
| Argument | Type | Meaning |
|---|---|---|
peer_id |
str |
The peer ID of the instance. The folder removed is incoming_dir()/safe_name(peer_id). |
Returns None. A missing folder is not an error and the removal ignores files it cannot delete. Only the folder of this peer ID is touched because the other instances of the machine may be receiving at that moment. When the library supports file messages, the P2P constructor calls it as soon as the peer ID of the instance is known.
safe_name
¶
Source code in unaiverse/networking/p2p/files.py
Turns a name chosen by a peer into one safe path component. A file name comes from the network and could otherwise escape the downloads folder (../../.bashrc) or carry control characters.
| Argument | Type | Meaning |
|---|---|---|
name |
str \| None |
The name to clean. None counts as an empty name. |
The function normalizes the name to Unicode NFC, replaces /, \, : and every character of a Unicode control category (C*) with _, strips spaces and leading dots and keeps the first 200 characters. A name that ends up empty, . or .. becomes FALLBACK_NAME. It returns the cleaned str and never raises.
>>> safe_name("../../etc/passwd")
'_.._etc_passwd'
>>> safe_name(" .hidden ")
'hidden'
>>> safe_name(None)
'file'
unique_path
¶
Source code in unaiverse/networking/p2p/files.py
Returns a path in folder for a file called filename that does not exist yet. The first candidate is folder/filename. As long as the candidate exists, the function inserts a counter before the extension and tries report (1).pdf, report (2).pdf and so on.
| Argument | Type | Meaning |
|---|---|---|
folder |
str |
The folder. |
filename |
str |
A name already cleaned by safe_name. |
Because the check and the later creation are two separate steps, the result alone does not protect against a race. place_received_file closes that race with an exclusive creation.
place_received_file
¶
place_received_file(incoming_path: str, owner: tuple[str, str] | None, sender_peer_id: str, filename: str | None) -> str
Source code in unaiverse/networking/p2p/files.py
Moves a received file from the incoming folder to its final place and returns the new path. P2P.get_messages calls it once per file of a complete file message.
| Argument | Type | Meaning |
|---|---|---|
incoming_path |
str |
Where the native networking library wrote the file. |
owner |
tuple[str, str] \| None |
The handle and node name of the sender that P2P.file_owner_of returns. None when the profile of the sender is unknown. |
sender_peer_id |
str |
The peer ID of the sender. |
filename |
str \| None |
The name the sender gave to the file. |
The destination folder is <downloads>/<handle>/<node name>/ or <downloads>/unknown/<peer ID>/ when owner is None. Every component goes through safe_name and the folder is created when missing. The function reserves the name by creating an empty file with O_CREAT | O_EXCL (mode 0o600) and tries the next free name when another node of the machine took it first. It then moves the received file onto the empty one with os.replace (a plain rename when both paths are on one filesystem). A file already in the folder is therefore never overwritten. An OSError of the creation or of the move propagates to P2P.get_messages. The caller then removes the files of the message and drops it.
>>> place_received_file("/home/ada/.unaiverse/Downloads/.incoming/12D3KooW.../a1.part",
... ("ada", "lab-robot"), "12D3KooW...", "scan.png")
'/home/ada/.unaiverse/Downloads/ada/lab-robot/scan.png'
streamed_files
¶
Source code in unaiverse/networking/p2p/files.py
Lists the samples of an outgoing message whose files can travel from disk. P2P.send calls it before encoding a message.
| Argument | Type | Meaning |
|---|---|---|
content_type |
str |
The content type of the message. Only "stream_sample" can carry files. |
content |
Any |
The content of the message. For a stream sample it is a dict stream name -> {"data": ..., "data_tag": ..., "data_uuid": ...}. |
A sample qualifies when its data has a non-None path attribute. A FileContainer built from a file on disk has one. The result is a list[dict] with one entry per such sample: "key" (the stream name), "path" (the absolute path of the file) and "name" (its filename truncated to 255 bytes of UTF-8, the name that the receiver shows in its progress). The list is empty for any other content type or content. Nothing is read from disk at this point.
remove_quietly
¶
Removes each path of a list and ignores every OSError (a file that is already gone is no error). The function returns None. P2P.get_messages calls it on the files of a message that it drops.