Rietveld Code Review Tool
Help | Bug tracker | Discussion group | Source code

Side by Side Diff: sitescripts/oauth2dl/bin/oauth2dl.py

Issue 29833582: Issue 4954 - Implement a downloader script supporting OAuth2 authentication/authorization (Closed)
Patch Set: Created July 18, 2018, 1:41 p.m.
Left:
Right:
Use n/p to move between diff chunks; N/P to move between comments.
Jump to:
View unified diff | Download patch
OLDNEW
(Empty)
1 # This file is part of the Adblock Plus web scripts,
2 # Copyright (C) 2006-present eyeo GmbH
3 #
4 # Adblock Plus is free software: you can redistribute it and/or modify
5 # it under the terms of the GNU General Public License version 3 as
6 # published by the Free Software Foundation.
7 #
8 # Adblock Plus is distributed in the hope that it will be useful,
9 # but WITHOUT ANY WARRANTY; without even the implied warranty of
10 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
11 # GNU General Public License for more details.
12 #
13 # You should have received a copy of the GNU General Public License
14 # along with Adblock Plus. If not, see <http://www.gnu.org/licenses/>.
15
16
17 import argparse
Vasily Kuznetsov 2018/07/20 21:00:01 PEP8 recommends breaking the imports into three gr
Tudor Avram 2018/07/23 19:29:03 Acknowledged.
Tudor Avram 2018/07/31 09:20:16 Done.
18 import codecs
19 import os
20 import sys
21 from httplib2 import Http
22 from oauth2client.service_account import ServiceAccountCredentials
23 import json
24
25 try:
Vasily Kuznetsov 2018/07/20 21:00:00 I think we can assume that the root of sitescripts
Tudor Avram 2018/07/23 19:29:03 That was to allow it to run both as `python -m ...
Tudor Avram 2018/07/31 09:20:17 Done.
26 from sitescripts.oauth2dl.bin import constants as cnts
27 except ImportError:
28 import constants as cnts
29
30
31 def write_to_file(content, path):
Vasily Kuznetsov 2018/07/20 21:00:00 I'm not sure if it really makes sense to have this
Tudor Avram 2018/07/23 19:29:03 Acknowledged.
Tudor Avram 2018/07/31 09:20:16 Done.
32 """Write data to file.
33
34 Parameters
35 ----------
36 content: str
37 The data to write.
38 path: str
39 Path to the file we write to.
40 """
41 with codecs.open(path, encoding='utf-8', mode='wb') as f:
42 f.write(content)
43
44
45 def download_file(url, key_file, scope):
46 """Download a file using Oauth2.
47
48 Parameters
49 ----------
50 url: str
51 The url of the file we want to download
52 key_file: str
53 Path/ url to key file used in Oauth2
54 scope: str
55 The scope used in Oauth2
56
57 Returns
58 -------
59 dict
60 Headers resulted from the HTTP request.
61 str
62 The content of the file we want to download/
63 error message if it was unsuccessful.
64 """
65 credentials = ServiceAccountCredentials.from_json_keyfile_name(key_file, sco pes=[scope])
Vasily Kuznetsov 2018/07/20 21:00:00 PEP8 recommends keeping the lines under 80 charact
Tudor Avram 2018/07/23 19:29:03 Yeah, I know. that's why I added the flake8 except
Tudor Avram 2018/07/31 09:20:16 Done.
66
67 http_auth = credentials.authorize(Http())
68
69 headers, content = http_auth.request(url)
70 try:
71 content = content.decode('utf-8')
72 finally:
73 return headers, content
74
75
76 def parse_args():
77 """Set up the required arguments and returns them."""
78 parser = argparse.ArgumentParser(description='Download using Oauth2')
79
80 parser.add_argument('url', help='URL to download from')
81 parser.add_argument('-k', '--key', help='Oauth2 key file path',
82 default=os.environ.get('OAUTH2DL_KEY'))
83 parser.add_argument('-s', '--scope', help='Oauth2 scope',
84 default=os.environ.get('OAUTH2DL_SCOPE'))
85 parser.add_argument('-o', help='Path where to save the file.')
86
87 return parser.parse_args()
88
89
90 def main():
91 args = parse_args()
92
93 if args.key is None:
94 sys.exit(cnts.KEYFILE_NOT_FOUND_ERROR)
95
96 if args.scope is None:
97 sys.exit(cnts.SCOPE_NOT_FOUND_ERROR)
98
99 try:
100 headers, content = download_file(args.url, args.key, args.scope)
101 except KeyError as err:
102 sys.exit(cnts.INVALID_KEY_FILE.format(str(err), str(args.key)))
103 except Exception as err:
104 sys.exit(err)
105
106 if headers['status'] != '200':
107 try:
108 error_json = json.loads(content, encoding='utf-8')
109 sys.exit(cnts.GOOGLE_OAUTH_ERROR.format(
110 str(error_json['error']['code']),
111 str(error_json['error']['message']),
112 ))
113 except ValueError:
114 sys.exit(content)
115
116 if args.o is None:
117 sys.stdout.write(content)
118 else:
119 write_to_file(content, args.o)
120
121
122 if __name__ == '__main__':
123 main()
OLDNEW

Powered by Google App Engine
This is Rietveld