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

Feature/click cli flags #278

Open
wants to merge 7 commits into
base: master
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
23 changes: 23 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
google\_cl
==========

[![image](https://img.shields.io/pypi/v/google_cl.svg)](https://pypi.python.org/pypi/google_cl)

[![image](https://img.shields.io/travis/vinitkumar/google_cl.svg)](https://travis-ci.org/vinitkumar/google_cl)

[![Documentation Status](https://readthedocs.org/projects/google-cl/badge/?version=latest)](https://google-cl.readthedocs.io/en/latest/?badge=latest)

[![Updates](https://pyup.io/repos/github/vinitkumar/google_cl/shield.svg)](https://pyup.io/repos/github/vinitkumar/google_cl/)

Pythonic interface to interact with google services

- Free software: Apache Software License 2.0
- Documentation: <https://google-cl.readthedocs.io>.

Features
--------

TODO:

- Implement core Google services

74 changes: 0 additions & 74 deletions README.rst

This file was deleted.

18 changes: 0 additions & 18 deletions google_cl/cli.py

This file was deleted.

11 changes: 5 additions & 6 deletions setup.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,15 +5,14 @@

from setuptools import setup, find_packages

with open('README.rst') as readme_file:
with open('README.md') as readme_file:
readme = readme_file.read()

with open('HISTORY.rst') as history_file:
history = history_file.read()

requirements = ['Click>=6.0', ]

setup_requirements = ['pytest-runner', ]
setup_requirements = ['google-auth==1.6.3', 'pytest-runner', 'requests_oauthlib', 'requests' ]
requirements = ['google-auth==1.6.3', 'pytest-runner', 'requests_oauthlib', 'requests' ]

test_requirements = ['pytest', ]

Expand All @@ -36,7 +35,7 @@
description="Pythonic interface to interact with google services",
entry_points={
'console_scripts': [
'google_cl=google_cl.cli:main',
'google=src.cli:cli',
],
},
install_requires=requirements,
Expand All @@ -45,7 +44,7 @@
include_package_data=True,
keywords='google_cl',
name='google_cl',
packages=find_packages(include=['google_cl']),
packages=find_packages(include=['src']),
setup_requires=setup_requirements,
test_suite='tests',
tests_require=test_requirements,
Expand Down
File renamed without changes.
114 changes: 114 additions & 0 deletions src/authorize.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,114 @@
# Source of this file: https://github.com/gilesknap/gphotos-sync/blob/master/gphotos/authorize.py

import logging
from typing import List, Optional

from requests.adapters import HTTPAdapter
from requests_oauthlib import OAuth2Session

from pathlib import Path
from urllib3.util.retry import Retry



from json import load, dump, JSONDecodeError

logger = logging.getLogger(__name__)

# OAuth endpoints given in the Google API documentation
authorization_base_url = "https://accounts.google.com/o/oauth2/v2/auth"
token_uri = "https://www.googleapis.com/oauth2/v4/token"



class Authorize:
def __init__(
self,
scope: List[str],
token_file: Path,
secrets_file: Path,
max_retries: int = 5,
):
self.max_retries = max_retries
self.scope: List[str] = scope
self.token_file: Path = token_file
self.session = None
self.token = None


try:
with secrets_file.open("r") as stream:
all_json = load(stream)

secrets = all_json["installed"]
sef.client_id = secrets["client_id"]
self.client_secret = secrets["client_secret"]
self.redirect_uri = secrets["redirect_uris"][0]
self.token_uri = secrets["token_uri"]
self.extra = {
"client_id": self.client_id,
"client_secret": self.client_secret,
}
except (JSONDecodeError, IOError):
print(f"missing or bad secrets file: {secrets_file}")
exit(1)

def load_token(self) -> Optional[str]:
try:
with self.token_file.open("r") as stream:
token = load(stream)
except (JSONDecodeError, IOError):
return None
return token

def save_token(self, token: str):
with self.token_file.open("w") as stream:
dump(token, stream)
self.token_file.chmod(0o600)

def authorize(self):
token = self.load_token()

if token:
self.session = OAuth2Session(
self.client_id,
token=token,
auto_refresh_url=self.token_uri,
auto_refresh_kwargs=self.extra,
token_updater=self.save_token,
)
else:
self.session = OAuth2Session(
self.client_id,
scope=self.scope,
redirect_uri=self.redirect_uri,
auto_refresh_url=self.token_uri,
auto_refresh_kwargs=self.extra,
token_updater=self.save_token,
)

authorization_url, _ = self.session.authorization_url(
authorization_base_url, access_type="offline", prompt="select_account"
)
print("Please go here and authorize,", authorization_url)

response_code = input("Paste the response token here:")
self.token = self.session.fetch_token(
self.token_uri, client_secret=self.client_secret, code=response_code)
self.save_token(self.token)

# set up retry behaviour for authorize session

retries = Retry(
total=self.max_retries,
backoff_factor=0.5,
status_forcelist=[500, 502, 503, 504],
method_whitelist=frozenset(["GET", "POST"]),
raise_on_status=False,
respect_retry_after_header=True,
)

self.session.mount("https://", HTTPAdapter(max_retries=retries))



28 changes: 28 additions & 0 deletions src/cli.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
# -*- coding: utf-8 -*-

"""Console script for google_cl."""
import sys
import click
from src.authorize import Authorize

@click.group()
def cli():
click.echo("Sunday Monday")

@cli.group()
def login():
Authorize()

@cli.group()
def picasa():
click.echo("This is a list")


@cli.group()
def contacts():
click.echo("contacts placeholder")


@picasa.command()
def photolist():
click.echo("This is coming from picasa list")
File renamed without changes.