telers 1.0.0-beta.2

An asynchronous framework for Telegram Bot API written in Rust
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
use bytes::{Bytes, BytesMut};
use futures_util::{Stream, TryFutureExt as _, TryStreamExt as _};
use serde::{Serialize, Serializer};
use std::{
    ffi::OsStr,
    fmt::{self, Debug, Formatter},
    hash::{Hash, Hasher},
    io, mem,
    path::PathBuf,
};
use tokio_util::codec::{BytesCodec, FramedRead};
use uuid::Uuid;

const ATTACH_PREFIX: &str = "attach://";

pub const DEFAULT_CAPACITY: usize = 64 * 1024; // 64 KiB

/// This object represents the contents of a file to be uploaded.
/// # Notes
/// You can use instead of [`InputFile`] any type that implements [`Into<InputFile>`]:
/// - [`FileId`] (for example `FileId::new(file_id)`)
/// - [`UrlFile`] (for example `UrlFile::new(url)`)
/// - [`FSFile`] (for example `FSFile::new(path)`)
/// - [`BufferedFile`] (for example `BufferedFile::new(bytes)`)
/// - [`StreamFile`] (for example `StreamFile::new(stream)`)
/// # Documentation
/// <https://core.telegram.org/bots/api#inputfile>
#[derive(Debug, Hash, PartialEq)]
pub enum InputFile {
    Id(FileId),
    Url(UrlFile),
    FS(FSFile),
    Buffered(BufferedFile),
    Stream(StreamFile),
}

impl InputFile {
    /// Creates a new [`InputFile`] with [`FileId`]
    #[must_use]
    pub fn id(id: impl Into<String>) -> Self {
        Self::Id(FileId::new(id))
    }

    /// Creates a new [`InputFile`] with [`UrlFile`]
    #[must_use]
    pub fn url(url: impl Into<String>) -> Self {
        Self::Url(UrlFile::new(url))
    }

    /// Creates a new [`InputFile`] with [`FSFile`]
    #[must_use]
    pub fn fs(path: impl Into<PathBuf>) -> Self {
        Self::FS(FSFile::new(path))
    }

    /// Creates a new [`InputFile`] with [`FSFile`] and specified filename
    #[must_use]
    pub fn fs_with_name(path: impl Into<PathBuf>, name: impl Into<String>) -> Self {
        Self::FS(FSFile::new_with_name(path, name))
    }

    /// Creates a new [`InputFile`] with [`BufferedFile`]
    #[must_use]
    pub fn buffered(bytes: impl Into<Bytes>) -> Self {
        Self::Buffered(BufferedFile::new(bytes))
    }

    /// Creates a new [`InputFile`] with [`BufferedFile`] and specified filename
    #[must_use]
    pub fn buffered_with_name(bytes: impl Into<Bytes>, name: impl Into<String>) -> Self {
        Self::Buffered(BufferedFile::new_with_name(bytes, name))
    }

    /// Creates a new [`InputFile`] with [`StreamFile`]
    /// # Warning
    /// If stream is taken, default client implementation raises an error,
    /// so you need to use [`StreamFile::set_stream`] to set stream again.
    /// This need because the stream can't be restored after it was taken.
    ///
    /// Check [`StreamFile::take_stream`] and [`StreamFile::set_stream`] for more information.
    #[must_use]
    pub fn stream(
        stream: impl Stream<Item = Result<Bytes, io::Error>> + Unpin + Send + Sync + 'static,
    ) -> Self {
        Self::Stream(StreamFile::new(stream))
    }

    /// Creates a new [`InputFile`] with [`StreamFile`] and specified filename
    #[must_use]
    pub fn stream_with_name(
        stream: impl Stream<Item = Result<Bytes, io::Error>> + Unpin + Send + Sync + 'static,
        name: impl Into<String>,
    ) -> Self {
        Self::Stream(StreamFile::new_with_name(stream, name))
    }
}

impl InputFile {
    /// Some variants can be uploaded in `multipart/form-data` format,
    /// others can be uploaded as URL or path (depends on [`InputFile`]).
    /// If the file in `multipart/form-data` format,
    /// then `str_to_file` will indicate "path" to data in form (because `multipart/form-data` format),
    /// otherwise it will be just string, which itself indicate "path" to data (because URL and telegram file id).
    /// # Returns
    /// If this file should be uploaded in `multipart/form-data` format, returns `attach://{id}`.
    /// Otherwise returns string as URL or path (depends on [`InputFile`]).
    #[must_use]
    pub fn str_to_file(&self) -> &str {
        match self {
            Self::Id(file) => file.str_to_file(),
            Self::Url(file) => file.str_to_file(),
            Self::FS(file) => file.str_to_file(),
            Self::Buffered(file) => file.str_to_file(),
            Self::Stream(file) => file.str_to_file(),
        }
    }

    /// Some variants can be uploaded in `multipart/form-data` format,
    /// others can be uploaded as URL or path (depends on [`InputFile`]).
    /// # Returns
    /// If this file should be uploaded in `multipart/form-data` format, returns `true`.
    /// Otherwise returns `false` and file [`InputFile`] may be uploaded in any way (URL and telegram file id).
    #[must_use]
    pub const fn is_require_multipart(&self) -> bool {
        match self {
            Self::Id(file) => file.is_require_multipart(),
            Self::Url(file) => file.is_require_multipart(),
            Self::FS(file) => file.is_require_multipart(),
            Self::Buffered(file) => file.is_require_multipart(),
            Self::Stream(file) => file.is_require_multipart(),
        }
    }

    #[must_use]
    pub fn take(&mut self) -> Self {
        match self {
            Self::Id(file) => file.take().into(),
            Self::Url(file) => file.take().into(),
            Self::FS(file) => file.take().into(),
            Self::Buffered(file) => file.take().into(),
            Self::Stream(file) => file.take().into(),
        }
    }
}

impl Serialize for InputFile {
    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
    where
        S: Serializer,
    {
        self.str_to_file().serialize(serializer)
    }
}

impl From<FileId> for InputFile {
    fn from(file: FileId) -> Self {
        Self::Id(file)
    }
}

impl From<UrlFile> for InputFile {
    fn from(file: UrlFile) -> Self {
        Self::Url(file)
    }
}

impl From<FSFile> for InputFile {
    fn from(file: FSFile) -> Self {
        Self::FS(file)
    }
}

impl From<BufferedFile> for InputFile {
    fn from(file: BufferedFile) -> Self {
        Self::Buffered(file)
    }
}

impl From<StreamFile> for InputFile {
    fn from(file: StreamFile) -> Self {
        Self::Stream(file)
    }
}

#[derive(Debug, Hash, PartialEq, Eq)]
pub struct FileId {
    pub(crate) id: String,
}

impl FileId {
    #[must_use]
    pub fn new(id: impl Into<String>) -> Self {
        Self { id: id.into() }
    }

    #[must_use]
    pub fn str_to_file(&self) -> &str {
        &self.id
    }

    #[must_use]
    pub const fn is_require_multipart(&self) -> bool {
        false
    }

    #[must_use]
    pub fn take(&mut self) -> Self {
        Self {
            id: self.id.clone(),
        }
    }
}

#[derive(Debug, Hash, PartialEq, Eq)]
pub struct UrlFile {
    pub(crate) url: String,
}

impl UrlFile {
    #[must_use]
    pub fn new(url: impl Into<String>) -> Self {
        Self { url: url.into() }
    }

    #[must_use]
    pub fn str_to_file(&self) -> &str {
        &self.url
    }

    #[must_use]
    pub const fn is_require_multipart(&self) -> bool {
        false
    }

    #[must_use]
    pub fn take(&mut self) -> Self {
        Self {
            url: self.url.clone(),
        }
    }
}

#[derive(Debug, PartialEq, Eq)]
pub struct FSFile {
    pub(crate) id: Uuid,
    file_name: Option<String>,
    pub(crate) path: PathBuf,
    pub(crate) str_to_file: String,
}

impl FSFile {
    #[must_use]
    pub fn new(path: impl Into<PathBuf>) -> Self {
        let id = Uuid::new_v4();
        let str_to_file = format!("{ATTACH_PREFIX}{id}");

        Self {
            id,
            file_name: None,
            path: path.into(),
            str_to_file,
        }
    }

    #[must_use]
    pub fn new_with_name(path: impl Into<PathBuf>, name: impl Into<String>) -> Self {
        let id = Uuid::new_v4();
        let str_to_file = format!("{ATTACH_PREFIX}{id}");

        Self {
            id,
            file_name: Some(name.into()),
            path: path.into(),
            str_to_file,
        }
    }

    #[must_use]
    pub const fn is_require_multipart(&self) -> bool {
        true
    }

    #[must_use]
    pub const fn id(&self) -> &Uuid {
        &self.id
    }

    /// Gets passed filename or filename by path
    /// # Returns
    /// If filename is not passed and filename by path is not valid Unicode, returns `None`
    #[must_use]
    pub fn file_name(&self) -> Option<&str> {
        self.file_name
            .as_deref()
            .or(self.path.file_name().and_then(OsStr::to_str))
    }

    #[must_use]
    pub fn str_to_file(&self) -> &str {
        &self.str_to_file
    }

    #[must_use]
    pub fn take(&mut self) -> Self {
        Self {
            id: mem::take(&mut self.id),
            file_name: mem::take(&mut self.file_name),
            path: mem::take(&mut self.path),
            str_to_file: self.str_to_file.clone(),
        }
    }
}

impl FSFile {
    /// Opens a file and returns a stream of its bytes with a specified capacity for the underlying buffer
    /// # Errors
    /// Returns an error if the file cannot be opened or read
    pub fn stream_with_capacity(
        self,
        capacity: usize,
    ) -> impl Stream<Item = Result<Bytes, io::Error>> {
        tokio::fs::File::open(self.path)
            .map_ok(move |file| {
                FramedRead::with_capacity(file, BytesCodec::new(), capacity)
                    .map_ok(BytesMut::freeze)
            })
            .try_flatten_stream()
    }

    /// Opens a file and returns a stream of its bytes with a default capacity for the underlying buffer
    /// # Notes
    /// If you want to specify the capacity, use `stream_with_capacity` method instead.
    ///
    /// The default capacity is [`DEFAULT_CAPACITY`].
    /// # Errors
    /// Returns an error if the file cannot be opened or read
    pub fn stream(self) -> impl Stream<Item = Result<Bytes, io::Error>> {
        self.stream_with_capacity(DEFAULT_CAPACITY)
    }
}

impl Hash for FSFile {
    fn hash<H: Hasher>(&self, state: &mut H) {
        self.id.hash(state);
    }
}

#[derive(PartialEq, Eq)]
pub struct BufferedFile {
    pub(crate) id: Uuid,
    pub(crate) bytes: Bytes,
    pub(crate) file_name: Option<String>,
    pub(crate) str_to_file: String,
}

impl BufferedFile {
    #[must_use]
    pub fn new(bytes: impl Into<Bytes>) -> Self {
        let id = Uuid::new_v4();
        let bytes = bytes.into();

        let str_to_file = format!("{ATTACH_PREFIX}{id}");

        Self {
            id,
            bytes,
            file_name: None,
            str_to_file,
        }
    }

    /// Creates a new [`BufferedFile`] with specified filename
    #[must_use]
    pub fn new_with_name(bytes: impl Into<Bytes>, name: impl Into<String>) -> Self {
        let id = Uuid::new_v4();
        let bytes = bytes.into();

        let str_to_file = format!("{ATTACH_PREFIX}{id}");

        Self {
            id,
            bytes,
            file_name: Some(name.into()),
            str_to_file,
        }
    }

    #[must_use]
    pub const fn is_require_multipart(&self) -> bool {
        true
    }

    #[must_use]
    pub const fn id(&self) -> &Uuid {
        &self.id
    }

    /// Gets string to file as path in format `attach://{id}`
    #[must_use]
    pub fn str_to_file(&self) -> &str {
        &self.str_to_file
    }

    #[must_use]
    pub fn take(&mut self) -> Self {
        Self {
            id: mem::take(&mut self.id),
            bytes: mem::take(&mut self.bytes),
            file_name: mem::take(&mut self.file_name),
            str_to_file: self.str_to_file.clone(),
        }
    }
}

impl Debug for BufferedFile {
    fn fmt(&self, f: &mut Formatter) -> fmt::Result {
        f.debug_struct("BufferedFile")
            .field("id", &self.id)
            .field("file_name", &self.file_name)
            .field("str_to_file", &self.str_to_file)
            .finish()
    }
}

impl Hash for BufferedFile {
    fn hash<H: Hasher>(&self, state: &mut H) {
        self.id.hash(state);
    }
}

pub struct StreamFile {
    pub(crate) id: Uuid,
    pub(crate) file_name: Option<String>,
    pub(crate) stream:
        Option<Box<dyn Stream<Item = Result<Bytes, io::Error>> + Send + Sync + Unpin>>,
    pub(crate) str_to_file: String,
}

impl StreamFile {
    #[must_use]
    pub fn new(
        stream: impl Stream<Item = Result<Bytes, io::Error>> + Send + Sync + Unpin + 'static,
    ) -> Self {
        let id = Uuid::new_v4();

        let str_to_file = format!("{ATTACH_PREFIX}{id}");

        Self {
            id,
            file_name: None,
            stream: Some(Box::new(stream)),
            str_to_file,
        }
    }

    #[must_use]
    pub fn new_with_name(
        stream: impl Stream<Item = Result<Bytes, io::Error>> + Send + Sync + Unpin + 'static,
        name: impl Into<String>,
    ) -> Self {
        let id = Uuid::new_v4();
        let str_to_file = format!("{ATTACH_PREFIX}{id}");

        Self {
            id,
            file_name: Some(name.into()),
            stream: Some(Box::new(stream)),
            str_to_file,
        }
    }

    #[must_use]
    pub const fn is_require_multipart(&self) -> bool {
        true
    }

    #[must_use]
    pub const fn id(&self) -> &Uuid {
        &self.id
    }

    #[must_use]
    pub fn str_to_file(&self) -> &str {
        &self.str_to_file
    }

    #[must_use]
    pub fn take(&mut self) -> Self {
        Self {
            id: mem::take(&mut self.id),
            file_name: mem::take(&mut self.file_name),
            stream: mem::take(&mut self.stream),
            str_to_file: self.str_to_file.clone(),
        }
    }
}

impl Debug for StreamFile {
    fn fmt(&self, f: &mut Formatter) -> fmt::Result {
        f.debug_struct("StreamFile")
            .field("id", &self.id)
            .field("file_name", &self.file_name)
            .field("str_to_file", &self.str_to_file)
            .finish()
    }
}

impl Hash for StreamFile {
    fn hash<H: Hasher>(&self, state: &mut H) {
        self.id.hash(state);
    }
}

impl PartialEq for StreamFile {
    fn eq(&self, other: &Self) -> bool {
        self.id == other.id
    }
}