Last active
May 5, 2021 15:59
-
-
Save thespacedoctor/652b845e19314aa78ce685dc8fdf6b89 to your computer and use it in GitHub Desktop.
[Tidy Gmail Labels] Homogenise the visibility and naming of my Gmail labels (later converterd to macos finder tags) #gmail #label #tag
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from __future__ import print_function | |
import httplib2 | |
import os | |
from apiclient import discovery | |
from oauth2client import client | |
from oauth2client import tools | |
from oauth2client.file import Storage | |
from apiclient import errors | |
try: | |
import argparse | |
flags = argparse.ArgumentParser(parents=[tools.argparser]).parse_args() | |
except ImportError: | |
flags = None | |
import re | |
# If modifying these scopes, delete your previously saved credentials | |
# at CLIENT_SECRET_FILE and the CLIENT_SECRET_FILE will be regenerated | |
SCOPES = 'https://mail.google.com/' | |
CLIENT_SECRET_FILE = '/Users/Dave/.credentials/client_secret.json' | |
# I HAVE ADDED THE PROJECTOR PROJECT UNDER THE GMAIL API | |
# https://console.developers.google.com/apis/dashboard | |
APPLICATION_NAME = 'Projector' | |
def get_credentials(filename): | |
"""Gets valid user credentials from storage. | |
If nothing has been stored, or if the stored credentials are invalid, | |
the OAuth2 flow is completed to obtain the new credentials. | |
**Key Arguments:** | |
- ``filename`` -- differentiate between home and work emails. | |
**Returns:** | |
Credentials, the obtained credential. | |
""" | |
home_dir = os.path.expanduser('~') | |
credential_dir = os.path.join(home_dir, '.credentials') | |
if not os.path.exists(credential_dir): | |
os.makedirs(credential_dir) | |
credential_path = os.path.join(credential_dir, | |
filename) | |
store = Storage(credential_path) | |
credentials = store.get() | |
if not credentials or credentials.invalid: | |
flow = client.flow_from_clientsecrets(CLIENT_SECRET_FILE, SCOPES) | |
flow.user_agent = APPLICATION_NAME | |
if flags: | |
credentials = tools.run_flow(flow, store, flags) | |
else: # Needed only for compatibility with Python 2.6 | |
credentials = tools.run(flow, store) | |
print('Storing credentials to ' + credential_path) | |
return credentials | |
def UpdateLabel(service, user_id, label_id, updated_label_object): | |
"""Update an existing Label. | |
Args: | |
service: Authorized Gmail API service instance. | |
user_id: User's email address. The special value "me" | |
can be used to indicate the authenticated user. | |
label_id: ID of the Label to update. | |
updated_label_object: Updated Label. | |
Returns: | |
Updated Label. | |
""" | |
try: | |
updated_label_object['id'] = label_id | |
updated_label = (service.users().labels() | |
.update(userId=user_id, id=label_id, | |
body=updated_label_object).execute()) | |
try: | |
print('label id: %s - label name: %s' % (updated_label['id'], | |
updated_label['name'].encode("utf-8"))) | |
except: | |
pass | |
return updated_label | |
except errors.HttpError, error: | |
print('An error occurred: %s' % error) | |
def main(): | |
"""Shows basic usage of the Gmail API. | |
Creates a Gmail API service object and outputs a list of label names | |
of the user's Gmail account. | |
""" | |
for filename in ["home-gmail.json", "work-gmail.json"]: | |
credentials = get_credentials(filename) | |
http = credentials.authorize(httplib2.Http()) | |
service = discovery.build('gmail', 'v1', http=http) | |
results = service.users().labels().list( | |
userId='me').execute() | |
labels = results.get('labels', []) | |
if not labels: | |
print('No labels found.') | |
else: | |
print('Labels:') | |
for label in labels: | |
name = label['name'] | |
skip = False | |
for i in ["CATEGORY_", "["]: | |
if i in name: | |
skip = True | |
if skip: | |
continue | |
skip = False | |
for i in ["TRASH", "DRAFT", "SPAM", "STARRED", "UNREAD", "INBOX", "SENT", "IMPORTANT", "CHAT"]: | |
if i == name: | |
skip = True | |
if skip: | |
continue | |
r = re.findall('([A-Z])', name) | |
if len(r) or "-" in name or " " in name or ":" in name or "," in name: | |
name = name.encode("utf-8") | |
print("Renaming %(name)s" % locals()) | |
label['name'] = label['name'].lower().replace( | |
"-", "_").replace(" ", "_").replace(":", "_").replace("__", "_").replace("__", "_").replace(",", "") | |
UpdateLabel(service, user_id="me", label_id=label[ | |
'id'], updated_label_object=label) | |
if labels: | |
for label in labels: | |
name = label['name'] | |
skip = False | |
for i in ["@", "CATEGORY_"]: | |
if i in name: | |
skip = True | |
if skip: | |
continue | |
skip = False | |
for i in ["TRASH", "DRAFT", "SPAM", "STARRED", "UNREAD", "INBOX", "SENT", "IMPORTANT", "CHAT"]: | |
if i == name: | |
skip = True | |
if skip: | |
continue | |
if "labelListVisibility" not in label or label["labelListVisibility"] != "labelShowIfUnread": | |
label["labelListVisibility"] = "labelShowIfUnread" | |
UpdateLabel(service, user_id="me", label_id=label[ | |
'id'], updated_label_object=label) | |
if __name__ == '__main__': | |
main() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment