1use ferogram_tl_types as tl;
18
19use crate::error::E2eError;
20use crate::transport::E2eTransport;
21
22fn upload_err(e: E2eError) -> E2eError {
24 match e {
25 E2eError::Transport(msg) => E2eError::UploadFailed(msg),
26 other => other,
27 }
28}
29
30const PART_SIZE: usize = 512 * 1024;
32const BIG_FILE_THRESHOLD: usize = 10 * 1024 * 1024;
34const MAX_FILE_SIZE: usize = 2 * 1024 * 1024 * 1024;
36
37pub async fn upload_encrypted_file<T: E2eTransport>(
44 client: &T,
45 ciphertext: &[u8],
46 key_fingerprint: i32,
47) -> Result<tl::enums::InputEncryptedFile, E2eError> {
48 if ciphertext.len() > MAX_FILE_SIZE {
49 return Err(E2eError::FileTooLarge);
50 }
51
52 let file_id: i64 = rand::random();
53 let is_big = ciphertext.len() >= BIG_FILE_THRESHOLD;
54 let total_parts = ciphertext.chunks(PART_SIZE).count() as i32;
55
56 for (part_idx, chunk) in ciphertext.chunks(PART_SIZE).enumerate() {
57 let part_no = part_idx as i32;
58 let bytes = chunk.to_vec();
59
60 if is_big {
61 client
62 .invoke(&tl::functions::upload::SaveBigFilePart {
63 file_id,
64 file_part: part_no,
65 file_total_parts: total_parts,
66 bytes,
67 })
68 .await
69 .map_err(upload_err)?;
70 } else {
71 client
72 .invoke(&tl::functions::upload::SaveFilePart {
73 file_id,
74 file_part: part_no,
75 bytes,
76 })
77 .await
78 .map_err(upload_err)?;
79 }
80 }
81
82 if is_big {
83 Ok(tl::enums::InputEncryptedFile::BigUploaded(
84 tl::types::InputEncryptedFileBigUploaded {
85 id: file_id,
86 parts: total_parts,
87 key_fingerprint,
88 },
89 ))
90 } else {
91 let md5 = format!("{:x}", md5::compute(ciphertext));
92 Ok(tl::enums::InputEncryptedFile::Uploaded(
93 tl::types::InputEncryptedFileUploaded {
94 id: file_id,
95 parts: total_parts,
96 md5_checksum: md5,
97 key_fingerprint,
98 },
99 ))
100 }
101}