misskey-util 0.1.0

High-level API for the misskey-rs library
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
use std::path::{Path, PathBuf};

use crate::pager::{BackwardPager, BoxPager, PagerStream};
use crate::Error;

#[cfg(feature = "12-48-0")]
use futures::stream::TryStreamExt;
use mime::Mime;
use misskey_api::model::drive::{DriveFile, DriveFolder};
#[cfg(feature = "12-48-0")]
use misskey_api::streaming::channel;
use misskey_api::{endpoint, EntityRef};
#[cfg(feature = "12-48-0")]
use misskey_core::streaming::StreamingClient;
use misskey_core::{Client, UploadFileClient};
#[cfg(feature = "12-48-0")]
use ulid_crate::Ulid;
use url::Url;

/// Builder for the [`build_file_from_url`][`crate::ClientExt::build_file_from_url`] method.
pub struct DriveFileUrlBuilder<C> {
    client: C,
    #[cfg(feature = "12-48-0")]
    marker: String,
    request: endpoint::drive::files::upload_from_url::Request,
}

impl<C> DriveFileUrlBuilder<C> {
    /// Creates a builder with the client and URL of the upload source.
    pub fn with_url(client: C, url: Url) -> Self {
        #[cfg(feature = "12-48-0")]
        let marker = Ulid::new().to_string();
        let request = endpoint::drive::files::upload_from_url::Request {
            url,
            folder_id: None,
            is_sensitive: Some(false),
            force: Some(false),
            #[cfg(feature = "12-48-0")]
            comment: None,
            #[cfg(feature = "12-48-0")]
            marker: Some(marker.clone()),
        };
        DriveFileUrlBuilder {
            client,
            request,
            #[cfg(feature = "12-48-0")]
            marker,
        }
    }

    /// Gets the request object for reuse.
    pub fn as_request(&self) -> &endpoint::drive::files::upload_from_url::Request {
        &self.request
    }

    /// Sets the parent folder of the file.
    pub fn folder(&mut self, folder: impl EntityRef<DriveFolder>) -> &mut Self {
        self.request.folder_id.replace(folder.entity_ref());
        self
    }

    /// Sets the comment for the file.
    #[cfg(feature = "12-48-0")]
    #[cfg_attr(docsrs, doc(cfg(feature = "12-48-0")))]
    pub fn comment(&mut self, comment: impl Into<String>) -> &mut Self {
        self.request.comment.replace(comment.into());
        self
    }

    /// Sets whether the file contains NSFW content.
    pub fn sensitive(&mut self, sensitive: bool) -> &mut Self {
        self.request.is_sensitive = Some(sensitive);
        self
    }

    /// Sets whether or not to upload the file again even if the same content has already been
    /// uploaded.
    pub fn use_existing_if_uploaded(&mut self, use_existing_if_uploaded: bool) -> &mut Self {
        self.request.force = Some(!use_existing_if_uploaded);
        self
    }
}

impl<C: Client> DriveFileUrlBuilder<C> {
    /// Uploads the file.
    ///
    /// The difference between [`upload_`][alt] and this method is that the former
    /// can get the [`DriveFile`][drive_file] of the uploaded file, while the latter cannot.
    /// If you want to obtain the [`DriveFile`] of an uploaded file in v12.48.0 or later, you can
    /// use [`upload_and_wait`][wait] or download the file once on the client side
    /// and the use [`UploadFileClientExt::upload_file`][upload_file] to upload it.
    ///
    /// [alt]: DriveFileUrlBuilder::upload_
    /// [drive_file]: misskey_api::model::drive::DriveFile
    /// [wait]: DriveFileUrlBuilder::upload_and_wait
    /// [upload_file]: crate::UploadFileClientExt::upload_file
    #[cfg(feature = "12-48-0")]
    #[cfg_attr(docsrs, doc(cfg(feature = "12-48-0")))]
    pub async fn upload(&self) -> Result<(), Error<C::Error>> {
        self.client
            .request(&self.request)
            .await
            .map_err(Error::Client)?
            .into_result()?;
        Ok(())
    }

    /// Uploads the file.
    ///
    /// See [`upload`][alt] for the difference between them.
    ///
    /// [alt]: DriveFileUrlBuilder::upload
    #[cfg(any(docsrs, not(feature = "12-48-0")))]
    #[cfg_attr(docsrs, doc(cfg(not(feature = "12-48-0"))))]
    pub async fn upload_(&self) -> Result<DriveFile, Error<C::Error>> {
        let file = self
            .client
            .request(&self.request)
            .await
            .map_err(Error::Client)?
            .into_result()?;
        Ok(file)
    }
}

#[cfg(feature = "12-48-0")]
#[cfg_attr(docsrs, doc(cfg(feature = "12-48-0")))]
impl<C: Client> DriveFileUrlBuilder<C>
where
    C: StreamingClient<Error = <C as Client>::Error>,
{
    /// Uploads the file and wait for a message of completion from the server.
    ///
    /// Unlike [`upload`][upload], this method returns [`DriveFile`][drive_file].
    ///
    /// [upload]: DriveFileUrlBuilder::upload
    /// [drive_file]: misskey_api::model::drive::DriveFile
    ///
    /// # Note on the use of main stream
    ///
    /// This method is implemented by waiting for the upload completion event in the main stream.
    /// However, it is currently not possible to have multiple connections to the main stream from
    /// the same client. Therefore, when you use this method, you must not not be connected to the
    /// main stream elsewhere. Likewise, you will not be able to connect to the main stream until
    /// this method is completed.
    pub async fn upload_and_wait(&self) -> Result<DriveFile, Error<<C as Client>::Error>> {
        let expected_marker = self.marker.clone();
        self.client
            .request(&self.request)
            .await
            .map_err(Error::Client)?
            .into_result()?;

        use channel::main::{self, MainStreamEvent};
        let stream = self
            .client
            .channel(main::Request::default())
            .await
            .map_err(Error::Client)?
            .map_err(Error::Client)
            .try_filter_map(|event| async {
                match event {
                    MainStreamEvent::UrlUploadFinished {
                        marker: Some(marker),
                        file,
                    } if marker == expected_marker => Ok(Some(file)),
                    _ => Ok(None),
                }
            });
        futures::pin_mut!(stream);
        let file = stream.try_next().await?.unwrap();
        Ok(file)
    }
}

/// Builder for the [`build_file`][`crate::UploadFileClientExt::build_file`] method.
pub struct DriveFileBuilder<C> {
    client: C,
    path: PathBuf,
    type_: Mime,
    request: endpoint::drive::files::create::Request,
}

impl<C> DriveFileBuilder<C> {
    /// Creates a builder with the client and path to the file.
    pub fn with_path(client: C, path: impl AsRef<Path>) -> Self {
        let path = path.as_ref().to_owned();
        let request = endpoint::drive::files::create::Request {
            name: path.file_name().map(|s| s.to_string_lossy().into_owned()),
            folder_id: None,
            is_sensitive: Some(false),
            force: Some(false),
        };
        let type_ = mime_guess::from_path(&path).first_or_octet_stream();
        DriveFileBuilder {
            client,
            type_,
            path,
            request,
        }
    }

    /// Gets the request object for reuse.
    pub fn as_request(&self) -> &endpoint::drive::files::create::Request {
        &self.request
    }

    /// Sets the parent folder of the file.
    pub fn folder(&mut self, folder: impl EntityRef<DriveFolder>) -> &mut Self {
        self.request.folder_id.replace(folder.entity_ref());
        self
    }

    /// Sets the mime type of the file.
    pub fn type_(&mut self, type_: Mime) -> &mut Self {
        self.type_ = type_;
        self
    }

    /// Sets the name of the file.
    pub fn name(&mut self, name: impl Into<String>) -> &mut Self {
        self.request.name.replace(name.into());
        self
    }

    /// Sets whether the file contains NSFW content.
    pub fn sensitive(&mut self, sensitive: bool) -> &mut Self {
        self.request.is_sensitive = Some(sensitive);
        self
    }

    /// Sets whether or not to upload the file again even if the same content has already been
    /// uploaded.
    pub fn use_existing_if_uploaded(&mut self, use_existing_if_uploaded: bool) -> &mut Self {
        self.request.force = Some(!use_existing_if_uploaded);
        self
    }
}

impl<C: UploadFileClient> DriveFileBuilder<C> {
    /// Uploads the file.
    pub async fn upload(&self) -> Result<DriveFile, Error<C::Error>> {
        let fs_file = std::fs::File::open(&self.path)?;
        let file = self
            .client
            .request_with_file(
                &self.request,
                self.type_.clone(),
                self.request.name.clone().unwrap_or_default(),
                fs_file,
            )
            .await
            .map_err(Error::Client)?
            .into_result()?;
        Ok(file)
    }
}

/// Builder for the [`update_file`][`crate::ClientExt::update_file`] method.
pub struct DriveFileUpdateBuilder<C> {
    client: C,
    request: endpoint::drive::files::update::Request,
}

impl<C> DriveFileUpdateBuilder<C> {
    /// Creates a builder with the client and the file you are going to update.
    pub fn new(client: C, file: impl EntityRef<DriveFile>) -> Self {
        let request = endpoint::drive::files::update::Request {
            file_id: file.entity_ref(),
            folder_id: None,
            name: None,
            is_sensitive: None,
        };
        DriveFileUpdateBuilder { client, request }
    }

    /// Gets the request object for reuse.
    pub fn as_request(&self) -> &endpoint::drive::files::update::Request {
        &self.request
    }

    /// Sets the parent folder of the file.
    pub fn set_folder(&mut self, folder: impl EntityRef<DriveFolder>) -> &mut Self {
        self.request.folder_id.replace(Some(folder.entity_ref()));
        self
    }

    /// Deletes the parent folder of the file.
    pub fn delete_folder(&mut self) -> &mut Self {
        self.request.folder_id.replace(None);
        self
    }

    /// Sets the name of the file.
    pub fn name(&mut self, name: impl Into<String>) -> &mut Self {
        self.request.name.replace(name.into());
        self
    }

    /// Sets whether the file contains NSFW content.
    pub fn sensitive(&mut self, sensitive: bool) -> &mut Self {
        self.request.is_sensitive = Some(sensitive);
        self
    }
}

impl<C: Client> DriveFileUpdateBuilder<C> {
    /// Updates the file.
    pub async fn update(&self) -> Result<DriveFile, Error<C::Error>> {
        let file = self
            .client
            .request(&self.request)
            .await
            .map_err(Error::Client)?
            .into_result()?;
        Ok(file)
    }
}

/// Builder for the [`update_folder`][`crate::ClientExt::update_folder`] method.
pub struct DriveFolderUpdateBuilder<C> {
    client: C,
    request: endpoint::drive::folders::update::Request,
}

impl<C> DriveFolderUpdateBuilder<C> {
    /// Creates a builder with the client and the folder you are going to update.
    pub fn new(client: C, folder: impl EntityRef<DriveFolder>) -> Self {
        let request = endpoint::drive::folders::update::Request {
            folder_id: folder.entity_ref(),
            parent_id: None,
            name: None,
        };
        DriveFolderUpdateBuilder { client, request }
    }

    /// Gets the request object for reuse.
    pub fn as_request(&self) -> &endpoint::drive::folders::update::Request {
        &self.request
    }

    update_builder_option_field! {
        #[doc_name = "parent folder of the folder"]
        pub parent: impl EntityRef<DriveFolder> { parent_id = parent.entity_ref() };
    }

    /// Sets the name of the folder.
    pub fn name(&mut self, name: impl Into<String>) -> &mut Self {
        self.request.name.replace(name.into());
        self
    }
}

impl<C: Client> DriveFolderUpdateBuilder<C> {
    /// Updates the folder.
    pub async fn update(&self) -> Result<DriveFolder, Error<C::Error>> {
        let folder = self
            .client
            .request(&self.request)
            .await
            .map_err(Error::Client)?
            .into_result()?;
        Ok(folder)
    }
}

/// Builder for the [`files`][`crate::ClientExt::files`] method.
pub struct DriveFileListBuilder<C> {
    client: C,
    request: endpoint::drive::files::Request,
}

impl<C> DriveFileListBuilder<C> {
    /// Creates a builder with the client.
    pub fn new(client: C) -> Self {
        let request = endpoint::drive::files::Request::default();
        DriveFileListBuilder { client, request }
    }

    /// Gets the request object for reuse.
    pub fn as_request(&self) -> &endpoint::drive::files::Request {
        &self.request
    }

    /// Limits the listed files to those of the specified MIME type.
    pub fn type_(&mut self, type_: Mime) -> &mut Self {
        self.request.type_.replace(type_);
        self
    }

    /// Specifies the folder to list the files.
    pub fn folder(&mut self, folder: impl EntityRef<DriveFolder>) -> &mut Self {
        self.request.folder_id.replace(folder.entity_ref());
        self
    }
}

impl<C: Client + Sync> DriveFileListBuilder<C> {
    /// Lists the files.
    pub fn list(&self) -> PagerStream<BoxPager<C, DriveFile>> {
        let pager = BackwardPager::new(&self.client, self.request.clone());
        PagerStream::new(Box::pin(pager))
    }
}