From b162f8d499af26c0782e04c9f6ff8d62d65662cc Mon Sep 17 00:00:00 2001 From: anxuae Date: Sat, 16 May 2020 23:57:20 +0200 Subject: [PATCH] Fix PEP8 warnings, remove useless escape char, rename google gallery with Google Photos --- README.rst | 16 +++++---- pibooth_google_photo.py | 80 +++++++++++++++++++++++------------------ 2 files changed, 54 insertions(+), 42 deletions(-) diff --git a/README.rst b/README.rst index 3eb9d61..2e7e44a 100644 --- a/README.rst +++ b/README.rst @@ -8,7 +8,7 @@ pibooth-google-photo ``pibooth-google-photo`` is a plugin for the `pibooth `_ application. -This plugin adds the photo upload to a `google photo gallery `_. +This plugin adds the photo upload to a `Google Photos `_. It requires an internet connection to work Install @@ -36,13 +36,15 @@ configuration): .. code-block:: ini [GOOGLE] - # The name of album on gallery - album_name = Pibooth - # The client_id.json file download from google API - client_id_file = path/to/client_id.json - # Option to allow disable plugin + # Enable upload on Google Photos activate = True - + + # Album where pictures are uploaded + album_name = Pibooth + + # Credentials file downloaded from Google API + client_id_file = + .. note:: Edit the configuration by running the command ``pibooth --config``. diff --git a/pibooth_google_photo.py b/pibooth_google_photo.py index 422a64b..9221b84 100644 --- a/pibooth_google_photo.py +++ b/pibooth_google_photo.py @@ -1,39 +1,45 @@ # -*- coding: utf-8 -*- -"""Pibooth plugin for google gallery upload.""" +"""Pibooth plugin for Google Photos upload.""" -from google_auth_oauthlib.flow import InstalledAppFlow -from google.auth.transport.requests import AuthorizedSession -from google.oauth2.credentials import Credentials import json import os.path + import requests +from google_auth_oauthlib.flow import InstalledAppFlow +from google.auth.transport.requests import AuthorizedSession +from google.oauth2.credentials import Credentials + import pibooth from pibooth.utils import LOGGER + __version__ = "1.0.2" ########################################################################### -## HOOK pibooth +# HOOK pibooth ########################################################################### + @pibooth.hookimpl def pibooth_configure(cfg): """Declare the new configuration options""" + cfg.add_option('GOOGLE', 'activate', True, + "Enable upload on Google Photos", + "Enable upload", ['True', 'False']) cfg.add_option('GOOGLE', 'album_name', "Pibooth", - "The name of album on gallery") + "Album where pictures are uploaded", + "Album name", "Pibooth") cfg.add_option('GOOGLE', 'client_id_file', '', - "The client_id.json file download from google API") - cfg.add_option('GOOGLE', 'activate', True, "Option to allow disable plugin", - "activate upload", ['True', 'False']) + "Credentials file downloaded from Google API") + @pibooth.hookimpl def pibooth_startup(app, cfg): - """Create the GoogleUpload instances.""" + """Create the GoogleUpload instance.""" activate_state = cfg.getboolean('GOOGLE', 'activate') app.google_photo = GoogleUpload(client_id=cfg.getpath('GOOGLE', 'client_id_file'), - credentials=None, activate=activate_state) - + credentials=None, activate=activate_state) @pibooth.hookimpl @@ -46,8 +52,10 @@ def state_processing_exit(app, cfg): ########################################################################### -## Class -################0########################################################### +# Class +########################################################################### + + class GoogleUpload(object): def __init__(self, client_id=None, credentials=None, activate=True): @@ -73,7 +81,8 @@ def __init__(self, client_id=None, credentials=None, activate=True): self.album_name = None self.activate = activate if not os.path.exists(self.client_id_file) or os.path.getsize(self.client_id_file) == 0: - LOGGER.error("Can't load json file \'%s\' please check GOOGLE:client_id_file on pibooth config file (DISABLE PLUGIN)", self.client_id_file) + LOGGER.error( + "Can't load json file '%s' please check GOOGLE:client_id_file on pibooth config file (DISABLE PLUGIN)", self.client_id_file) self.activate = False if self.activate and self._is_internet(): self._get_authorized_session() @@ -83,7 +92,7 @@ def _is_internet(self): try: requests.get('https://www.google.com/').status_code return True - except: + except requests.ConnectionError: LOGGER.warning("No internet connection!!!!") return False @@ -134,13 +143,13 @@ def _save_cred(self): 'client_secret': self.credentials.client_secret } - with open(self.google_credentials, 'w') as f: - print(json.dumps(cred_dict), file=f) + with open(self.google_credentials, 'w') as fp: + json.dump(cred_dict, fp) - def get_albums(self, appCreatedOnly=False): - """#Generator to loop through all albums""" + def get_albums(self, app_created_only=False): + """Generator to loop through all albums""" params = { - 'excludeNonAppCreatedData': appCreatedOnly + 'excludeNonAppCreatedData': app_created_only } while True: albums = self.session.get('https://photoslibrary.googleapis.com/v1/albums', params=params).json() @@ -161,7 +170,7 @@ def _create_or_retrieve_album(self): for a in self.get_albums(True): if a["title"].lower() == self.album_name.lower(): self.album_id = a["id"] - LOGGER.info("Uploading into EXISTING photo album -- \'%s\'", self.album_name) + LOGGER.info("Uploading into EXISTING photo album -- '%s'", self.album_name) if self.album_id is None: # No matches, create new album create_album_body = json.dumps({"album": {"title": self.album_name}}) @@ -169,11 +178,11 @@ def _create_or_retrieve_album(self): resp = self.session.post('https://photoslibrary.googleapis.com/v1/albums', create_album_body).json() LOGGER.debug("Server response: %s", resp) if "id" in resp: - LOGGER.info("Uploading into NEW photo album -- \'%s\'", self.album_name) + LOGGER.info("Uploading into NEW photo album -- '%s'", self.album_name) self.album_id = resp['id'] else: - LOGGER.error("Could not find or create photo album \'{0}\'.\ - Server Response: %s", self.album_name, resp) + LOGGER.error("Could not find or create photo album '%s'.\ + Server Response: %s", self.album_name, resp) self.album_id = None def upload_photos(self, photo_file_list, album_name, activate): @@ -184,7 +193,8 @@ def upload_photos(self, photo_file_list, album_name, activate): :param album_name: name of albums to upload :type album_name: str :param activate: use to disable the upload - :type activate: bool""" + :type activate: bool + """ self.activate = activate # interrupt upload no internet if not self._is_internet(): @@ -214,12 +224,12 @@ def upload_photos(self, photo_file_list, album_name, activate): photo_file = open(photo_file_name, mode='rb') photo_bytes = photo_file.read() except OSError as err: - LOGGER.error("Could not read file \'%s\' -- %s", photo_file_name, err) + LOGGER.error("Could not read file '%s' -- %s", photo_file_name, err) continue self.session.headers["X-Goog-Upload-File-Name"] = os.path.basename(photo_file_name) - LOGGER.info("Uploading photo -- \'%s\'", photo_file_name) + LOGGER.info("Uploading photo -- '%s'", photo_file_name) upload_token = self.session.post('https://photoslibrary.googleapis.com/v1/uploads', photo_bytes) @@ -236,24 +246,24 @@ def upload_photos(self, photo_file_list, album_name, activate): if "newMediaItemResults" in resp: status = resp["newMediaItemResults"][0]["status"] if status.get("code") and (status.get("code") > 0): - LOGGER.error("Could not add \'%s\' to library -- %s", os.path.basename(photo_file_name), + LOGGER.error("Could not add '%s' to library -- %s", os.path.basename(photo_file_name), status["message"]) else: LOGGER.info( - "Added \'%s\' to library and album \'%s\' ", os.path.basename(photo_file_name), + "Added '%s' to library and album '%s' ", os.path.basename(photo_file_name), album_name) else: LOGGER.error( - "Could not add \'%s\' to library. Server Response -- %s", os.path.basename(photo_file_name), + "Could not add '%s' to library. Server Response -- %s", os.path.basename(photo_file_name), resp) else: - LOGGER.error("Could not upload \'%s\'. Server Response - %s", os.path.basename(photo_file_name), + LOGGER.error("Could not upload '%s'. Server Response -- %s", os.path.basename(photo_file_name), upload_token) try: - del (self.session.headers["Content-type"]) - del (self.session.headers["X-Goog-Upload-Protocol"]) - del (self.session.headers["X-Goog-Upload-File-Name"]) + del self.session.headers["Content-type"] + del self.session.headers["X-Goog-Upload-Protocol"] + del self.session.headers["X-Goog-Upload-File-Name"] except KeyError: pass