Skip to content

Commit

Permalink
Merge pull request #2 from pibooth/fix-pep8-typo
Browse files Browse the repository at this point in the history
Fix PEP8 warnings, remove useless escape char, rename google gallery with Google Photos
  • Loading branch information
sravel authored May 18, 2020
2 parents 56120c9 + b162f8d commit a298803
Show file tree
Hide file tree
Showing 2 changed files with 54 additions and 42 deletions.
16 changes: 9 additions & 7 deletions README.rst
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ pibooth-google-photo
``pibooth-google-photo`` is a plugin for the `pibooth <https://github.com/pibooth/pibooth>`_
application.

This plugin adds the photo upload to a `google photo gallery <https://photos.google.com/>`_.
This plugin adds the photo upload to a `Google Photos <https://photos.google.com/>`_.
It requires an internet connection to work

Install
Expand Down Expand Up @@ -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``.


Expand Down
80 changes: 45 additions & 35 deletions pibooth_google_photo.py
Original file line number Diff line number Diff line change
@@ -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
Expand All @@ -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):
Expand All @@ -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()
Expand All @@ -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

Expand Down Expand Up @@ -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()
Expand All @@ -161,19 +170,19 @@ 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}})
# print(create_album_body)
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):
Expand All @@ -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():
Expand Down Expand Up @@ -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)

Expand All @@ -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

0 comments on commit a298803

Please sign in to comment.