Files

Struct Files 

Source
pub struct Files { /* private fields */ }
Expand description

Information related to a user’s files.

§Examples:

List the files in a drive

use drive_v3::{Credentials, Drive};

let credentials_path = "my_credentials.json";
let scopes = ["https://www.googleapis.com/auth/drive.metadata.readonly"];

let credentials = Credentials::from_file(&credentials_path, &scopes)?;
let drive = Drive::new(&credentials);

let file_list = drive.files.list()
    .fields("files(name, id, mimeType)") // Set what fields will be returned
    .q("name = 'file_im_looking_for' and not trashed") // search for specific files
    .execute()?;

if let Some(files) = file_list.files {
    for file in &files {
        println!("{}", file);
    }
}

Implementations§

Source§

impl Files

Source

pub fn new(credentials: &Credentials) -> Self

Creates a new Files resource with the given Credentials.

Source

pub fn copy<T: AsRef<str>>(&self, file_id: T) -> CopyRequest

Creates a copy of a file and applies any requested updates with patch semantics.

See Google’s documentation for more information.

§Requires one of the following OAuth scopes:
  • https://www.googleapis.com/auth/drive
  • https://www.googleapis.com/auth/drive.appdata
  • https://www.googleapis.com/auth/drive.file
  • https://www.googleapis.com/auth/drive.photos.readonly
§Examples:
use drive_v3::objects::File;

// Set the metadata that the copied file will have
let metadata = File {
    name: Some( "my-copy.txt".to_string() ),
    description: Some( "I copied this using drive_v3!".to_string() ),
    ..Default::default()
};

// Set the ID of the file you want to copy,
// you can get this using files.list()
let source_file_id = "some-file-id";

let copied_file = drive.files.copy(&source_file_id)
    .metadata(&metadata)
    .execute()?;

assert_eq!(copied_file.name, metadata.name);
assert_eq!(copied_file.description, metadata.description);
Source

pub fn create(&self) -> CreateRequest

Creates a new file.

See Google’s documentation for more information.

§Note:

You can use any of the UploadTypes, but for most uploads I recommend using the Resumable type, which will allow you to set a callback to monitor the upload progress.

§Requires one of the following OAuth scopes:
  • https://www.googleapis.com/auth/drive
  • https://www.googleapis.com/auth/drive.appdata
  • https://www.googleapis.com/auth/drive.file
§Examples:

Perform a simple upload to create a small media file (5 MB or less) without supplying metadata:

use drive_v3::objects::{File, UploadType};

// A simple upload does not support metadata, however you can use it in
// this request to set the MIME type of your new file, any other fields
// you set will be ignored.
let metadata = File {
    mime_type: Some( "text/plain".to_string() ),
    ..Default::default()
};

let my_new_file = drive.files.create()
    .upload_type(UploadType::Media)
    .metadata(&metadata)
    .content_string("This is the content of my new file!")
    // .content_source("path/to/file.txt") // You can also load a file from the system
    .execute()?;

assert_eq!(my_new_file.mime_type, metadata.mime_type);

Perform a multipart upload to create a small media file (5 MB or less) along with metadata that describes the file, in a single request:

use drive_v3::objects::{File, UploadType};

// Set what information the uploaded file wil have
let metadata = File {
    name: Some( "my-new-file.txt".to_string() ),
    mime_type: Some( "text/plain".to_string() ),
    ..Default::default()
};

let my_new_file = drive.files.create()
    .upload_type(UploadType::Multipart)
    .metadata(&metadata)
    .content_source("path/to/file.txt")
    // .content_string("This is the content of my new file!")  // You can use a string
    .execute()?;

assert_eq!(my_new_file.name, metadata.name);
assert_eq!(my_new_file.mime_type, metadata.mime_type);

Perform a resumable upload to create a large file (greater than 5 MB):

use drive_v3::objects::{File, UploadType};

// Set what information the uploaded file wil have
let metadata = File {
    name: Some( "my-new-file.txt".to_string() ),
    mime_type: Some( "text/plain".to_string() ),
    ..Default::default()
};

// You can set a callback that will be called when a resumable upload
// progresses
fn progress_callback( total_bytes: usize, uploaded_bytes: usize ) {
    println!("Uploaded {} bytes, out of a total of {}.", uploaded_bytes, total_bytes);
}

let my_new_file = drive.files.create()
    .upload_type(UploadType::Resumable)
    .callback(progress_callback)
    .metadata(&metadata)
    .content_source("path/to/file.txt")
    .execute()?;

assert_eq!(my_new_file.name, metadata.name);
assert_eq!(my_new_file.mime_type, metadata.mime_type);
Source

pub fn delete<T: AsRef<str>>(&self, file_id: T) -> DeleteRequest

Permanently deletes a file owned by the user without moving it to the trash.

If the file belongs to a shared drive, the user must be an organizer on the parent folder. If the target is a folder, all descendants owned by the user are also deleted.

§Requires one of the following OAuth scopes:
  • https://www.googleapis.com/auth/drive
  • https://www.googleapis.com/auth/drive.appdata
  • https://www.googleapis.com/auth/drive.file
§Examples:
let my_file_id = "example-id";

drive.files.delete(&my_file_id).execute()?;
Source

pub fn empty_trash(&self) -> EmptyTrashRequest

Permanently deletes all of the user’s trashed files.

§Note:

The emptying of the trash may take some time to be reflected in a user’s Drive.

§Requires the following OAuth scope:
  • https://www.googleapis.com/auth/drive
§Examples:
drive.files.empty_trash()
    // .drive_id("my-drive-id") // You can specify which drive to empty the trash from
    .execute()?;
Source

pub fn export<T: AsRef<str>>(&self, file_id: T) -> ExportRequest

Exports a Google Workspace document to the requested MIME type and returns exported byte content (limited to 10MB).

For more information on the supported export MIME types, check Google’s documentation.

§Note:

This request requires you to set the mime_type of the file to export.

§Requires one of the following OAuth scopes:
  • https://www.googleapis.com/auth/drive
  • https://www.googleapis.com/auth/drive.file
  • https://www.googleapis.com/auth/drive.readonly
§Examples:
use std::fs;
use std::io::Write;
let my_file_id = "file-id";
let my_exported_mime_type = "application/pdf";

let exported_bytes = drive.files.export(&my_file_id)
    .mime_type(my_exported_mime_type)
    .execute()?;

// Write the bytes to a file
let mut file = fs::File::create("exported-file.pdf")?;
file.write_all(&exported_bytes)?;
Source

pub fn generate_ids(&self) -> GenerateIDsRequest

Generates a set of file IDs which can be provided in create or copy requests.

§Requires one of the following OAuth scopes:
  • https://www.googleapis.com/auth/drive
  • https://www.googleapis.com/auth/drive.appdata
  • https://www.googleapis.com/auth/drive.file
§Examples:
use drive_v3::objects::{Space, IDKind};

let my_generated_ids = drive.files.generate_ids()
    .count(5) // How many IDs to generate
    .space(Space::Drive) // Set the space in which the IDs can be used
    .kind(IDKind::Files) // Set the type of the IDs
    .execute()?;

for id in &my_generated_ids.ids {
    println!("Generated this ID: {}", id);
}
Source

pub fn get<T: AsRef<str>>(&self, file_id: T) -> GetRequest

Gets a file’s metadata by ID.

§Note:

To get the content of a file you can use get_media (only works if the file is stored in Drive).

To download Google Docs, Sheets, and Slides use export instead.

§Requires one of the following OAuth scopes:
  • https://www.googleapis.com/auth/drive
  • https://www.googleapis.com/auth/drive.appdata
  • https://www.googleapis.com/auth/drive.file
  • https://www.googleapis.com/auth/drive.metadata
  • https://www.googleapis.com/auth/drive.metadata.readonly
  • https://www.googleapis.com/auth/drive.photos.readonly
  • https://www.googleapis.com/auth/drive.readonly
§Examples:
let my_file_id = "file-id";

let file_metadata = drive.files.get(&my_file_id).execute()?;

println!("Look at this metadata:\n{}", file_metadata);
Source

pub fn get_media<T: AsRef<str>>(&self, file_id: T) -> GetMediaRequest

Gets a file’s content by ID.

§Requires one of the following OAuth scopes:
  • https://www.googleapis.com/auth/drive
  • https://www.googleapis.com/auth/drive.appdata
  • https://www.googleapis.com/auth/drive.file
  • https://www.googleapis.com/auth/drive.metadata
  • https://www.googleapis.com/auth/drive.metadata.readonly
  • https://www.googleapis.com/auth/drive.photos.readonly
  • https://www.googleapis.com/auth/drive.readonly
§Examples:
let my_text_file_id = "file-id";

let file_bytes = drive.files.get_media(&my_text_file_id)
    // .save_to("my_downloaded_file.txt") // Save the contents to a path
    .execute()?;

let content = String::from_utf8_lossy(&file_bytes);

println!("content: {}", content);
Source

pub fn list(&self) -> ListRequest

Lists the user’s files.

This method accepts the q parameter, which is a search query combining one or more search terms.

For more information, see Google’s Search for files & folders guide.

§Note

This method returns all files by default, including trashed files. If you don’t want trashed files to appear in the list, use the trashed=false or not trashed in the q parameter to remove trashed files from the results.

§Requires one of the following OAuth scopes:
  • https://www.googleapis.com/auth/drive
  • https://www.googleapis.com/auth/drive.appdata
  • https://www.googleapis.com/auth/drive.file
  • https://www.googleapis.com/auth/drive.metadata
  • https://www.googleapis.com/auth/drive.metadata.readonly
  • https://www.googleapis.com/auth/drive.photos.readonly
  • https://www.googleapis.com/auth/drive.readonly
§Examples:
let file_list = drive.files.list()
    .fields("files(name, id, mimeType)") // Set what fields will be returned
    .q("name = 'file_im_looking_for' and not trashed") // search for specific files
    .execute()?;

if let Some(files) = file_list.files {
    for file in &files {
        println!("{}", file);
    }
}
Source

pub fn list_labels<T: AsRef<str>>(&self, file_id: T) -> ListLabelsRequest

Lists the labels on a file.

§Requires one of the following OAuth scopes:
  • https://www.googleapis.com/auth/drive
  • https://www.googleapis.com/auth/drive.file
  • https://www.googleapis.com/auth/drive.metadata
  • https://www.googleapis.com/auth/drive.metadata.readonly
  • https://www.googleapis.com/auth/drive.readonly
§Examples:
let my_file_id = "file-id";

let label_list = drive.files.list_labels(&my_file_id)
    .max_results(10)
    .execute()?;

if let Some(labels) = label_list.labels {
    for label in &labels {
        println!("{}", label);
    }
}
Source

pub fn modify_labels<T: AsRef<str>>(&self, file_id: T) -> ModifyLabelsRequest

Modifies the set of labels applied to a file.

Returns a list of the labels that were added or modified.

§Note

As of now, labels on files are not supported on personal (free) Google Drive accounts.

§Requires one of the following OAuth scopes:
  • https://www.googleapis.com/auth/drive
  • https://www.googleapis.com/auth/drive.file
  • https://www.googleapis.com/auth/drive.metadata
§Examples:
use drive_v3::objects::{LabelModification, FieldModification};

let label_modifications = vec![
    LabelModification::from(
        "label-id",
        &vec![
            FieldModification {
                set_text_values: Some( vec!["text".into(), "other_text".into()] ),
                ..Default::default()
            }
        ]
    )
];

let my_file_id = "file-id";

let modified_labels = drive.files.modify_labels(&my_file_id)
    .modifications(label_modifications)
    .execute()?;

for label in &modified_labels {
    println!("this label was modified:\n{}", label);
}
Source

pub fn update<T: AsRef<str>>(&self, file_id: T) -> UpdateRequest

Updates a file’s metadata and/or content.

When calling this method, only populate fields in the request that you want to modify. When updating fields, some fields might be changed automatically, such as modified_time.

This method supports patch semantics.

§Requires one of the following OAuth scopes:
  • https://www.googleapis.com/auth/drive
  • https://www.googleapis.com/auth/drive.appdata
  • https://www.googleapis.com/auth/drive.file
§Examples:

Perform a simple upload to create a small media file (5 MB or less) without supplying metadata:

use drive_v3::objects::{File, UploadType};
// A simple upload does not support metadata, however you can use it in
// this request to set the MIME type of your new file, any other fields
// you set will be ignored.
let metadata = File {
    mime_type: Some( "text/plain".to_string() ),
    ..Default::default()
};

let my_file_id = "file-id";

let my_new_file = drive.files.update(&my_file_id)
    .upload_type(UploadType::Media)
    .metadata(&metadata)
    .content_string("This is the content of my new file!")
    // .content_source("path/to/file.txt") // You can also load a file from the system
    .execute()?;

Perform a multipart upload to create a small media file (5 MB or less) along with metadata that describes the file, in a single request:

use drive_v3::objects::{File, UploadType};
// Set what information the uploaded file wil have
let metadata = File {
    name: Some( "my-new-file.txt".to_string() ),
    mime_type: Some( "text/plain".to_string() ),
    ..Default::default()
};

let my_file_id = "file-id";

let my_new_file = drive.files.update(&my_file_id)
    .upload_type(UploadType::Multipart)
    .metadata(&metadata)
    .content_source("path/to/file.txt")
    // .content_string("This is the content of my new file!")  // You can use a string
    .execute()?;

Perform a resumable upload to create a large file (greater than 5 MB):

use drive_v3::objects::{File, UploadType};
// Set what information the uploaded file wil have
let metadata = File {
    name: Some( "my-new-file.txt".to_string() ),
    mime_type: Some( "text/plain".to_string() ),
    ..Default::default()
};

// You can set a callback that will be called when a resumable upload
// progress, that way you can monitor and display how far along your
// file upload is
fn progress_callback( total_bytes: usize, uploaded_bytes: usize ) {
    println!("Uploaded {} bytes, out of a total of {}.", uploaded_bytes, total_bytes);
}

let my_file_id = "file-id";

let my_new_file = drive.files.update(&my_file_id)
    .upload_type(UploadType::Resumable)
    .callback(progress_callback)
    .metadata(&metadata)
    .content_source("path/to/file.txt")
    .execute()?;
Source

pub fn watch<T: AsRef<str>>(&self, file_id: T) -> WatchRequest

Subscribes to changes to a file.

§Note

In order to subscribe to a file’s changes, you must provide a Channel with an id and an address which is the one that will receive the notifications. This can be done by creating a channel using from.

For more information on channels, see Google’s documentation.

§Requires one of the following OAuth scopes:
  • https://www.googleapis.com/auth/drive
  • https://www.googleapis.com/auth/drive.appdata
  • https://www.googleapis.com/auth/drive.file
  • https://www.googleapis.com/auth/drive.metadata
  • https://www.googleapis.com/auth/drive.metadata.readonly
  • https://www.googleapis.com/auth/drive.photos.readonly
  • https://www.googleapis.com/auth/drive.readonly
§Examples:
use drive_v3::objects::Channel;

let channel_id = "my-channel-id";
let channel_address = "https://mydomain.com/channel-notifications";
let channel = Channel::from(&channel_id, &channel_address);

let my_file_id = "file-id";

let created_channel = drive.files.watch(&my_file_id)
    .channel(&channel)
    .execute()?;

println!("this is the created channel:\n{}", created_channel);

Trait Implementations§

Source§

impl Clone for Files

Source§

fn clone(&self) -> Files

Returns a duplicate of the value. Read more
1.0.0 · Source§

fn clone_from(&mut self, source: &Self)

Performs copy-assignment from source. Read more
Source§

impl Debug for Files

Source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more
Source§

impl PartialEq for Files

Source§

fn eq(&self, other: &Files) -> bool

Tests for self and other values to be equal, and is used by ==.
1.0.0 · Source§

fn ne(&self, other: &Rhs) -> bool

Tests for !=. The default implementation is almost always sufficient, and should not be overridden without very good reason.
Source§

impl Eq for Files

Source§

impl StructuralPartialEq for Files

Auto Trait Implementations§

§

impl Freeze for Files

§

impl RefUnwindSafe for Files

§

impl Send for Files

§

impl Sync for Files

§

impl Unpin for Files

§

impl UnwindSafe for Files

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<T> CloneToUninit for T
where T: Clone,

Source§

unsafe fn clone_to_uninit(&self, dest: *mut u8)

🔬This is a nightly-only experimental API. (clone_to_uninit)
Performs copy-assignment from self to dest. Read more
Source§

impl<Q, K> Equivalent<K> for Q
where Q: Eq + ?Sized, K: Borrow<Q> + ?Sized,

Source§

fn equivalent(&self, key: &K) -> bool

Checks if this value is equivalent to the given key. Read more
Source§

impl<Q, K> Equivalent<K> for Q
where Q: Eq + ?Sized, K: Borrow<Q> + ?Sized,

Source§

fn equivalent(&self, key: &K) -> bool

Compare self to key and return true if they are equal.
Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T> Instrument for T

Source§

fn instrument(self, span: Span) -> Instrumented<Self>

Instruments this type with the provided Span, returning an Instrumented wrapper. Read more
Source§

fn in_current_span(self) -> Instrumented<Self>

Instruments this type with the current Span, returning an Instrumented wrapper. Read more
Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<T> Same for T

Source§

type Output = T

Should always be Self
Source§

impl<T> ToOwned for T
where T: Clone,

Source§

type Owned = T

The resulting type after obtaining ownership.
Source§

fn to_owned(&self) -> T

Creates owned data from borrowed data, usually by cloning. Read more
Source§

fn clone_into(&self, target: &mut T)

Uses borrowed data to replace owned data, usually by cloning. Read more
Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = Infallible

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.
Source§

impl<V, T> VZip<V> for T
where V: MultiLane<T>,

Source§

fn vzip(self) -> V

Source§

impl<T> WithSubscriber for T

Source§

fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self>
where S: Into<Dispatch>,

Attaches the provided Subscriber to this type, returning a WithDispatch wrapper. Read more
Source§

fn with_current_subscriber(self) -> WithDispatch<Self>

Attaches the current default Subscriber to this type, returning a WithDispatch wrapper. Read more