Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Google Slides & Google Drive #1031

Open
wants to merge 14 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -125,4 +125,4 @@ bill_com_credentials.*

docs/html
docs/dirhtml
*.sw*
*.sw*
112 changes: 109 additions & 3 deletions docs/google.rst
Original file line number Diff line number Diff line change
Expand Up @@ -51,7 +51,6 @@ API
.. autoclass:: parsons.google.google_admin.GoogleAdmin
:inherited-members:


********
BigQuery
********
Expand Down Expand Up @@ -255,7 +254,60 @@ You can also retrieve represntative information such as offices, officals, etc.
API
===

.. autoclass :: parsons.google.google_civic.GoogleCivic
.. autoclass:: parsons.google.google_civic.GoogleCivic
:inherited-members:

*************
Google Drive
*************

========
Overview
========

The GoogleDrive class allows you to interact with Google Drive. You can update permissions with this connector.

In order to instantiate the class, you must pass Google service account credentials as a dictionary, or store the credentials as a JSON file locally and pass the path to the file as a string in the ``GOOGLE_DRIVE_CREDENTIALS`` environment variable. You can follow these steps:

- Go to the `Google Developer Console <https://console.cloud.google.com/apis/dashboard>`_ and make sure the "Google Drive API" is enabled.
- Go to the credentials page via the lefthand sidebar. On the credentials page, click "create credentials".
- Choose the "Service Account" option and fill out the form provided. This should generate your credentials.
- Select your newly created Service Account on the credentials main page.
- select "keys", then "add key", then "create new key". Pick the key type JSON. The credentials should start to automatically download.

You can now copy and paste the data from the key into your script or (recommended) save it locally as a JSON file.

==========
Quickstart
==========

To instantiate the GoogleSheets class, you can either pass the constructor a dict containing your Google service account credentials or define the environment variable ``GOOGLE_DRIVE_CREDENTIALS`` to contain a path to the JSON file containing the dict.

.. code-block:: python

from parsons import GoogleDrive

# First approach: Use API credentials via environmental variables
drive = GoogleDrive()

# Second approach: Pass API credentials as argument
credential_filename = 'google_drive_service_credentials.json'
credentials = json.load(open(credential_filename))
drive = GoogleDrive(google_keyfile_dict=credentials)

You can then retreive and edit the permissions for Google Drive objects.

.. code-block:: python

email_addresses = ["[email protected]"]
shared = drive.share_object(file_id, email_addresses)


===
API
===

.. autoclass:: parsons.google.google_drive.GoogleDrive
:inherited-members:


Expand All @@ -267,7 +319,7 @@ Google Sheets
Overview
========

The GoogleSheets class allows you to interact with Google service account spreadsheets, called "Google Sheets." You can create, modify, read, format, share and delete sheets with this connector.
The GoogleSlides class allows you to interact with Google Slides. You can create and modify Google Slides with this connector.

In order to instantiate the class, you must pass Google service account credentials as a dictionary, or store the credentials as a JSON file locally and pass the path to the file as a string in the ``GOOGLE_DRIVE_CREDENTIALS`` environment variable. You can follow these steps:

Expand Down Expand Up @@ -314,3 +366,57 @@ API
.. autoclass:: parsons.google.google_sheets.GoogleSheets
:inherited-members:

*************
Google Slides
*************

========
Overview
========

The GoogleSheets class allows you to interact with Google service account spreadsheets, called "Google Sheets." You can create, modify, read, format, share and delete sheets with this connector.

In order to instantiate the class, you must pass Google service account credentials as a dictionary, or store the credentials as a JSON file locally and pass the path to the file as a string in the ``GOOGLE_DRIVE_CREDENTIALS`` environment variable. You can follow these steps:

- Go to the `Google Developer Console <https://console.cloud.google.com/apis/dashboard>`_ and make sure the "Google Drive API" and the "Google Sheets API" are both enabled.
- Go to the credentials page via the lefthand sidebar. On the credentials page, click "create credentials".
- Choose the "Service Account" option and fill out the form provided. This should generate your credentials.
- Select your newly created Service Account on the credentials main page.
- select "keys", then "add key", then "create new key". Pick the key type JSON. The credentials should start to automatically download.

You can now copy and paste the data from the key into your script or (recommended) save it locally as a JSON file.

==========
Quickstart
==========

To instantiate the GoogleSheets class, you can either pass the constructor a dict containing your Google service account credentials or define the environment variable ``GOOGLE_DRIVE_CREDENTIALS`` to contain a path to the JSON file containing the dict.

.. code-block:: python

from parsons import GoogleSlides

# First approach: Use API credentials via environmental variables
slides = GoogleSlides()

# Second approach: Pass API credentials as argument
credential_filename = 'google_drive_service_credentials.json'
credentials = json.load(open(credential_filename))
slides = GoogleSlides(google_keyfile_dict=credentials)

You can then create/modify/retrieve slides using instance methods:

.. code-block:: python

slides.create_presentation("Parsons is Fun")


You can use the GoogleDrive() connector to share the slide deck.

===
API
===

.. autoclass:: parsons.google.google_slides.GoogleSlides
:inherited-members:

2 changes: 2 additions & 0 deletions parsons/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -64,7 +64,9 @@
("parsons.google.google_bigquery", "GoogleBigQuery"),
("parsons.google.google_civic", "GoogleCivic"),
("parsons.google.google_cloud_storage", "GoogleCloudStorage"),
("parsons.google.google_drive", "GoogleDrive"),
("parsons.google.google_sheets", "GoogleSheets"),
("parsons.google.google_slides", "GoogleSlides"),
("parsons.hustle.hustle", "Hustle"),
("parsons.mailchimp.mailchimp", "Mailchimp"),
("parsons.mobilecommons.mobilecommons", "MobileCommons"),
Expand Down
153 changes: 153 additions & 0 deletions parsons/google/google_drive.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,153 @@
import os
import json
import logging

from parsons.google.utitities import setup_google_application_credentials
elyse-weiss marked this conversation as resolved.
Show resolved Hide resolved
from googleapiclient.discovery import build
from google.oauth2.service_account import Credentials

logger = logging.getLogger(__name__)


class GoogleDrive:
"""
A connector for Google Drive, largely handling permissions.

`Args:`
google_keyfile_dict: dict
A dictionary of Google Drive API credentials, parsed from JSON provided
by the Google Developer Console. Required if env variable
``GOOGLE_DRIVE_CREDENTIALS`` is not populated.
subject: string
In order to use account impersonation, pass in the email address of the account to be
impersonated as a string.
"""

def __init__(self, google_keyfile_dict=None, subject=None):

scope = ["https://www.googleapis.com/auth/drive"]

setup_google_application_credentials(
google_keyfile_dict, "GOOGLE_DRIVE_CREDENTIALS"
)
google_credential_file = open(os.environ["GOOGLE_DRIVE_CREDENTIALS"])
credentials_dict = json.load(google_credential_file)

credentials = Credentials.from_service_account_info(
credentials_dict, scopes=scope, subject=subject
)
Comment on lines +30 to +38
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Would you consider using the new pattern adopted by other google connectors as of #1040 to avoid reimplementing the issue #1039?

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@austinweisgrau I previously had:

self.client = build("drive", "v3", credentials=credentials)

If I follow your code from the other PR, will the following work too:

self.client = AuthorizedSession(credentials)


self.client = build("drive", "v3", credentials=credentials)

def get_permissions(self, file_id):
"""
`Args:`
file_id: str
this is the ID of the object you are hoping to share
`Returns:`
permission dict
"""

p = self.client.permissions().list(fileId=file_id).execute()

return p

def _share_object(self, file_id, permission_dict):

# Send the request to share the file
p = (
self.client.permissions()
.create(fileId=file_id, body=permission_dict)
.execute()
)

return p

def share_object(self, file_id, email_addresses=None, role="reader", type="user"):
"""
`Args:`
file_id: str
this is the ID of the object you are hoping to share
email_addresses: list
this is the list of the email addresses you want to share;
set to a list of domains like `['domain']` if you choose `type='domain'`;
set to `None` if you choose `type='anyone'`
role: str
Options are -- owner, organizer, fileOrganizer, writer, commenter, reader
https://developers.google.com/drive/api/guides/ref-roles
type: str
Options are -- user, group, domain, anyone
`Returns:`
List of permission objects
"""
if role not in [
"owner",
"organizer",
"fileOrganizer",
"writer",
"commenter",
"reader",
]:
raise Exception(
f"{role} not from the allowed list of: \
owner, organizer, fileOrganizer, writer, commenter, reader"
)

if type not in ["user", "group", "domain", "anyone"]:
raise Exception(
f"{type} not from the allowed list of: \
user, group, domain, anyone"
)

if type == "domain":
permissions = [
{"type": type, "role": role, "domain": email}
for email in email_addresses
]
else:
permissions = [
{"type": type, "role": role, "emailAddress": email}
for email in email_addresses
]

new_permissions = []
for permission in permissions:
p = self._share_object(file_id, permission)
new_permissions.append(p)

return new_permissions

def transfer_ownership(self, file_id, new_owner_email):
"""
`Args:`
file_id: str
this is the ID of the object you are hoping to share
new_owner_email: str
the email address of the intended new owner
`Returns:`
None
"""
permissions = self.client.permissions().list(fileId=file_id).execute()

# Find the current owner
current_owner_permission = next(
(p for p in permissions.get("permissions", []) if "owner" in p), None
)

if current_owner_permission:
# Update the permission to transfer ownership
new_owner_permission = {
"type": "user",
"role": "owner",
"emailAddress": new_owner_email,
}
self.client.permissions().update(
fileId=file_id,
permissionId=current_owner_permission["id"],
body=new_owner_permission,
).execute()
logger.info(f"Ownership transferred successfully to {new_owner_email}.")
else:
logger.info("File does not have a current owner.")

return None
Loading
Loading