1+ import argparse
2+ import requests
3+ import io
4+
5+ from oauth2client .service_account import ServiceAccountCredentials
6+
7+
8+ PROJECT_ID = '<PROJECT_ID>'
9+ BASE_URL = 'https://firebaseremoteconfig.googleapis.com'
10+ REMOTE_CONFIG_ENDPOINT = 'v1/projects/' + PROJECT_ID + '/remoteConfig'
11+ REMOTE_CONFIG_URL = BASE_URL + '/' + REMOTE_CONFIG_ENDPOINT
12+ SCOPES = ['https://www.googleapis.com/auth/firebase.remoteconfig' ]
13+
14+ # [START retrieve_access_token]
15+ def _get_access_token ():
16+ """Retrieve a valid access token that can be used to authorize requests.
17+
18+ :return: Access token.
19+ """
20+ credentials = ServiceAccountCredentials .from_json_keyfile_name (
21+ 'service-account.json' , SCOPES )
22+ access_token_info = credentials .get_access_token ()
23+ return access_token_info .access_token
24+ # [END retrieve_access_token]
25+
26+ def _get ():
27+ """Retrieve the current Firebase Remote Config template from server.
28+
29+ Retrieve the current Firebase Remote Config template from server and store it
30+ locally.
31+ """
32+ headers = {
33+ 'Authorization' : 'Bearer ' + _get_access_token ()
34+ }
35+ resp = requests .get (REMOTE_CONFIG_URL , headers = headers )
36+
37+ if resp .status_code == 200 :
38+ with io .open ('config.json' , 'wb' ) as f :
39+ f .write (resp .text .encode ('utf-8' ))
40+
41+ print ('Retrieved template has been written to config.json' )
42+ print ('ETag from server: {}' .format (resp .headers ['ETag' ]))
43+ else :
44+ print ('Unable to get template' )
45+ print (resp .text )
46+
47+
48+ def _publish (etag ):
49+ """Publish local template to Firebase server.
50+
51+ Args:
52+ etag: ETag for safe (avoid race conditions) template updates.
53+ * can be used to force template replacement.
54+ """
55+ with open ('config.json' , 'r' , encoding = 'utf-8' ) as f :
56+ content = f .read ()
57+ headers = {
58+ 'Authorization' : 'Bearer ' + _get_access_token (),
59+ 'Content-Type' : 'application/json; UTF-8' ,
60+ 'If-Match' : etag
61+ }
62+ resp = requests .put (REMOTE_CONFIG_URL , data = content .encode ('utf-8' ), headers = headers )
63+ if resp .status_code == 200 :
64+ print ('Template has been published.' )
65+ print ('ETag from server: {}' .format (resp .headers ['ETag' ]))
66+ else :
67+ print ('Unable to publish template.' )
68+ print (resp .text )
69+
70+
71+ def main ():
72+ parser = argparse .ArgumentParser ()
73+ parser .add_argument ('--action' )
74+ parser .add_argument ('--etag' )
75+ args = parser .parse_args ()
76+
77+ if args .action and args .action == 'get' :
78+ _get ()
79+ elif args .action and args .action == 'publish' and args .etag :
80+ _publish (args .etag )
81+ else :
82+ print ('''Invalid command. Please use one of the following commands:
83+ python configure.py --action=get
84+ python configure.py --action=publish --etag=<LATEST_ETAG>''' )
85+
86+
87+
88+ if __name__ == '__main__' :
89+ main ()
0 commit comments