How to get file information in google drive using google drive url in google drive api - google-drive-api

Does anyone know if this is possible?
i think i can do it by extracting id from url.
then execute code like below.
service = build('drive', 'v3', credentials=creds)
# Call the Drive v3 API
results = service.files().list(
pageSize=10, fields="nextPageToken, files(id, name,parents,owners)",q="'drive id' in parents"
).execute()
https://developers.google.com/drive/api/guides/search-files
however parsing url might fail sometime.
so i would like to know how to get file information in drive by specify url.

To ensure the parsing URL will not fail, you can use the findall function in regex in extracting the folder ID from the folder URL. Since the structure of the folder URL is static except for the id part, this pattern will guarantee the extraction of folder Id
Regex Pattern
"/folders\/(.*)\?resourcekey"
Please see sample code below for getting the files in a specific folder in my google drive
Code:
from googleapiclient.discovery import build
from google.colab import auth
from google.auth import default
import re
auth.authenticate_user()
creds, _ = default()
# Build the service
service = build('drive', 'v3', credentials=creds)
# Google drive folder's URL
folder_url = 'https://drive.google.com/corp/drive/folders/1bBWIXbinmb-DQ1z_fspsvxlw3vt8v6Wa?resourcekey=0-3Q_nXWmlLp_eG79NzcRe5w'
# Get the folder's ID from the URL using regex
folder_id = re.findall("/folders\/(.*)\?resourcekey", folder_url)
#query
query = f"'{folder_id[0]}' in parents"
# List the files in the folder
results = service.files().list(pageSize=10, fields="nextPageToken, files(id, name,parents,owners)",q=query).execute()
items = results.get('files', [])
if not items:
print('No files found.')
else:
print('Files:')
for item in items:
print(u'{0} ({1})'.format(item['name'], item['id']))
Output:
Resources:
Search for files and folders
Regular Expression
https://regex101.com/

Related

Change Google Drive file from public to private

I created a public File on my Google Drive, I used the v3 API from Google Drive on Python to get a list of all my files.
Now I want to change a file permissions so it would be private and can only be seen by me (owner)
from __future__ import print_function
from apiclient.discovery import build
from httplib2 import Http
from oauth2client import file, client, tools
# Setup the Drive v3 API
SCOPES = 'https://www.googleapis.com/auth/drive.metadata.readonly'
store = file.Storage('credentials.json')
creds = store.get()
if not creds or creds.invalid:
flow = client.flow_from_clientsecrets('client_id.json', SCOPES)
creds = tools.run_flow(flow, store)
service = build('drive', 'v3', http=creds.authorize(Http()))
# Call the Drive v3 API
results = service.files().list(
pageSize=10, fields="nextPageToken, files(id, name, modifiedTime, owners, permissions)").execute()
items = results.get('files', [])
if not items:
print('No files found.')
else:
print('Files:')
for item in items:
print('{0} ({1}) ({2})'.format(item['name'], item['id'], item["modifiedTime"])
Cosa = items[2]
print("--- Archivo Publico ---")
print(Cosa["permissions"])
print("---- Modifico los Permisos ----")
service.permissions().delete(fileId="ExampleID",permissionId="anyone").execute()
Now, when I execute the code I get:
googleapiclient.errors.HttpError: <HttpError 403 when requesting https://www.googleapis.com/drive/v3/files/1KHjbcJkN79cccgwywrwsBHlOuLUgtOqXZk4gvZKR1eE/permissions/anyone? returned "Insufficient Permission">
Why? I´m the owner of the File.
edit: The file has 2 permissions. The first is "anyone" which let´s everyone see and edit the file. The second is my permission which makes me the owner. I'm trying to delete the first to make the file private
I had to change de SCOPE from:
SCOPES = 'https://www.googleapis.com/auth/drive.metadata.readonly'
to
SCOPES = 'https://www.googleapis.com/auth/drive'
I also deleted my credentials.json and made the web authentication. It works as spected now

Get Google Drive file owner email address using Google Drive API V3 via python

I'm having trouble getting the owner of a file on Google Drive via the Google Drive API v3.
I could do this under v2, but things have changed.
According to the documentation I need to:
List the permissions on a file (no problem)
Find Id of the permission with the 'owner' role from that list of permissions (no problem)
Get that permission ... which should return a permissions resource which should include the email address (problem!)
Unfortunately, what I'm getting back includes some of the information, but not the email address.
I suspect that I need to change my "get" call to tell the API which fields I'm after, but I can't see how to do this.
This is what I've got (v3):
from oauth2client.service_account import ServiceAccountCredentials
from httplib2 import Http
from apiclient.discovery import build
def build_service(user):
keyfile = 'C:\Python27\Scripts\Certificates for Transfer owner script\Transfer Ownership on Drive-f240cff252af.json'
SCOPE = 'https://www.googleapis.com/auth/drive'
credentials = ServiceAccountCredentials.from_json_keyfile_name(keyfile, scopes=SCOPE).create_delegated(user)
http_auth = credentials.authorize(Http())
return build('drive', 'v2', http=http_auth)
service = build_service('lpglobaldrive#lonelyplanet.com.au')
f = service.files().get(fileId='1lASRBuAHRxEC-T0X5SdlF3w7X_168Q2QV9L0V6QaXUk').execute()
p = service.permissions().get(fileId='1lASRBuAHRxEC-T0X5SdlF3w7X_168Q2QV9L0V6QaXUk',permissionId='18137907375963748644').execute()
currentOwner = p['emailAddress']
Unfortunately I get a "KeyError: 'emailAddress'" (and if I look at the contents of "p", there's role, kind, type and id, but no email Address).
This works for me (using v2):
from oauth2client.service_account import ServiceAccountCredentials
from httplib2 import Http
from apiclient.discovery import build
def build_service(user):
keyfile = 'C:\Python27\Scripts\Certificates for Transfer owner script\Transfer Ownership on Drive-f240cff252af.json'
SCOPE = 'https://www.googleapis.com/auth/drive'
credentials = ServiceAccountCredentials.from_json_keyfile_name(keyfile, scopes=SCOPE).create_delegated(user)
http_auth = credentials.authorize(Http())
return build('drive', 'v2', http=http_auth)
service = build_service('lpglobaldrive#lonelyplanet.com.au')
f = service.files().get(fileId='1lASRBuAHRxEC-T0X5SdlF3w7X_168Q2QV9L0V6QaXUk').execute()
currentOwner = f['owners'][0]['emailAddress']
Too simple ... just needed to add the following to the get call:
,fields='emailAddress'
i.e.
currentOwner = service.permissions().get(fileId='1lASRBuAHRxEC-T0X5SdlF3w7X_168Q2QV9L0V6QaXUk',permissionId='18137907375963748644',fields='emailAddress').execute()['emailAddress']

Automatically verifying gdrive app login in python program

I want to automatically verify my credentials without going to the link and pasting the verification code every time I run this program.
might storing credentials will work but I don't know how to store it and reuse it..
my code is given below
#!/usr/bin/python
import httplib2
import pprint
from apiclient.discovery import build
from apiclient.http import MediaFileUpload
from oauth2client.client import OAuth2WebServerFlow
from oauth2client.file import Storage
# Copy your credentials from the console
CLIENT_ID = 'my_id' #i have client id but dont wanna share
CLIENT_SECRET = 'my_secret' #i have client secret but dont wanna share
# Check https://developers.google.com/drive/scopes for all available scopes
OAUTH_SCOPE = 'https://www.googleapis.com/auth/drive'
# Redirect URI for installed apps
REDIRECT_URI = 'urn:ietf:wg:oauth:2.0:oob'
# Path to the file to upload
FILENAME = 'hello.txt'
# Run through the OAuth flow and retrieve credentials
flow = OAuth2WebServerFlow(CLIENT_ID, CLIENT_SECRET, OAUTH_SCOPE,
redirect_uri=REDIRECT_URI)
authorize_url = flow.step1_get_authorize_url()
print 'Go to the following link in your browser: ' + authorize_url
code = raw_input('Enter verification code: ').strip()
credentials = flow.step2_exchange(code)
# Create an httplib2.Http object and authorize it with our credentials
http = httplib2.Http()
http = credentials.authorize(http)
drive_service = build('drive', 'v2', http=http)
# Insert a file
media_body = MediaFileUpload(FILENAME, mimetype='text/plain', resumable=True)
body = {
'title': 'My document',
'description': 'A test document',
'mimeType': 'text/plain'
}
file = drive_service.files().insert(body=body, media_body=media_body).execute()
pprint.pprint(file)
any help is appreciated !
Here you can find the documentation on OAuth with python: https://developers.google.com/api-client-library/python/guide/aaa_oauth (edited url)
basically you will have to use self.redirect(authorize_url) to make that step automatically and then in the second step you will use flow.step2_exchange(self.request.params)
In the documentation will find a better explanation of the process.

Get shared link through Google Drive API

I am working on an app using Google Drive. I want the user to be able to share files by link, setting the permissions to anyone and withLink as described in the Google Developers documentation.
However, I cannot figure out what link to share. When I share a file in the Google Drive browser interface, I see the Link to share in the format:
https://docs.google.com/presentation/d/[...]/edit?usp=sharing
A link in this format is not part of the file resource object, nor it is returned from the http call setting the permissions. I hope someone can explain to me how to get this link through the REST api?
You can use the alternateLink property in the File resource to get a link that can be shared for opening the file in the relevant Google editor or viewer:
https://developers.google.com/drive/v2/reference/files
Update
[With API V3](https://developers.google.com/drive/api/v3/reference/files it is suggested to use the webViewLink property.
To actually enable link sharing using Google Drive API:
drive.permissions.create({
fileId: '......',
requestBody: {
role: 'reader',
type: 'anyone',
}
});
Get the webLinkView value using:
const webViewLink = await drive.files.get({
fileId: file.id,
fields: 'webViewLink'
}).then(response =>
response.data.webViewLink
);
In my case using the PHP Api v3, for the link to be non-empty you must define that you request this field... and if you have the right permissions:
so something like this:
$file =self::$service->files->get("1ogXyGxcJdMXt7nJddTpVqwd6_G8Hd5sUfq4b4cxvotest",array("fields"=>"webViewLink"));
Here's a practical example on how to get the WebViewLink file property (A.K.A. File edit link):
$file = $service->files->get($file_id, array('fields' => 'webViewLink'));
$web_link_view = $file->getWebViewLink();
OR
$sheetsList = $drive_service->files->listFiles([
'fields' => 'files(id, name, webViewLink, webContentLink)',
]);
$web_link_view = $sheetsList->current()->getWebViewLink();
Pay attention that you should load the file specifying which fields you wanna bring with it (In this case, webViewLink). If you don't do that, only id and name will be available.
In case you need to adjust the file sharing settings, this is how you do it:
$permissions = new \Google_Service_Drive_Permission();
$permissions->setRole('writer');
$permissions->setType('anyone');
$drive_service->permissions->create($file_id, $permissions);
Possible values for setRole() and setType() can be found here: https://developers.google.com/drive/api/v3/reference/permissions/create
For python, I only needed to get the file "id".
Then "created" the link like this:
def create_folder(folder_name, folder_id):
"""Create a folder and prints the folder ID and Folder link
Returns : Folder Id
"""
try:
# create drive api client
service = build("drive", "v3", credentials=creds)
file_metadata = {
"name": folder_name,
"mimeType": "application/vnd.google-apps.folder",
"parents": [folder_id],
}
file = (
service.files().create(body=file_metadata, fields="id").execute()
)
id = file.get("id")
print(
f'Folder ID: "{id}".',
f'https://drive.google.com/drive/u/0/folders/{id}',
)
return id
except HttpError as error:
print(f"An error occurred: {error}")
return None

Upload CSV to Google Drive Spreadsheet using Drive v2 API

How can I upload a local CSV file to Google Drive using the Drive API v2 so that the uploaded file is in the native Google Spreadsheet format. Preferably in Python, but a raw HTTP request will suffice.
What I tried:
request body content-type: 'application/vnd.google-apps.spreadsheet', media_body content-type: 'text/csv'. --> 401 Bad Request
request body content-type: 'application/vnd.google-apps.spreadsheet', media_body content-type: 'application/vnd.google-apps.spreadsheet'. --> 400 Bad Request
... (a couple of others such as leaving a property out and similar, usually got 400 or Drive didn't recognise it as a native spreadsheet)
Your insert request should specify text/csv as the content-type.
The trick to get the file converted is to add the ?convert=true query parameter to the request url:
https://developers.google.com/drive/v2/reference/files/insert
(Mar 2017) Note, while the question specifically asks about Drive API v2, developers should know that the Google Drive API team released v3 at the end of 2015, and in that release, insert() changed names to create() so as to better reflect the file operation. There's also no more convert flag -- you just specify MIMEtypes... imagine that!
The documentation has also been improved: there's now a special guide devoted to uploads (simple, multipart, and resumable) that comes with sample code in Java, Python, PHP, C#/.NET, Ruby, JavaScript/Node.js, and iOS/Obj-C to upload a file and another that imports a CSV file as a Google Sheet.
Just to show how straightforward it is, below is one alternate Python solution (to the sample in the docs) for short files ("simple upload") where you don't need the apiclient.http.MediaFileUpload class. This snippet assumes your auth code works where your service endpoint is DRIVE with a minimum auth scope of https://www.googleapis.com/auth/drive.file.
# filenames & MIMEtypes
DST_FILENAME = 'inventory'
SRC_FILENAME = DST_FILENAME + '.csv'
SHT_MIMETYPE = 'application/vnd.google-apps.spreadsheet'
CSV_MIMETYPE = 'text/csv'
# Import CSV file to Google Drive as a Google Sheets file
METADATA = {'name': DST_FILENAME, 'mimeType': SHT_MIMETYPE}
rsp = DRIVE.files().create(body=METADATA, media_body=SRC_FILENAME).execute()
if rsp:
print('Imported %r to %r (as %s)' % (SRC_FILENAME, DST_FILENAME, rsp['mimeType']))
Claudio Cherubino's answer is correct -- you have to add the parameter manually. Since you asked in Python though, here's a concrete example:
body = {
'mimeType':'text/csv',
'title': 'title'
}
# service: your authenticated service
# media: your apiclient.http.MediaFileUpload object, with 'text/csv' mimeType
req = service.files().insert(media_body=media, body=body)
# patch the uri to ensure conversion, as the documented kwarg seems to be borked.
# you may need to use '?convert=true' depending on the uri, not taking that into
# account here for sake of simplicity.
req.uri = req.uri + '&convert=true'
# now we can execute the response.
resp = req.execute()
# should be OK
assert resp['mimeType'] == u'application/vnd.google-apps.spreadsheet'
Java :
//Insert a file
File body = new File();
body.setTitle("CSV");
body.setDescription("A test document");
body.setMimeType("text/csv");
java.io.File fileContent = new java.io.File("document.csv");
FileContent mediaContent = new FileContent("text/csv", fileContent);
Insert insert = service.files().insert(body, mediaContent);
insert.setConvert(true);
File file = insert.execute();
System.out.println("File ID: " + file.getId());
The best way to get started is using the web form at
https://developers.google.com/drive/v2/reference/files/insert#try-it