|
12 | 12 | https://firebase.google.com/docs/reference/rest/storage/rest
|
13 | 13 | """
|
14 | 14 |
|
| 15 | +import datetime |
15 | 16 | import requests
|
16 | 17 | from gcloud import storage
|
17 | 18 | from urllib.parse import quote
|
@@ -224,26 +225,46 @@ def download(self, filename, token=None):
|
224 | 225 | for chunk in r:
|
225 | 226 | f.write(chunk)
|
226 | 227 |
|
227 |
| - def get_url(self, token): |
| 228 | + def get_url(self, token=None, expiration_hour=24): |
228 | 229 | """ Fetches URL for file.
|
229 | 230 |
|
230 | 231 |
|
231 | 232 | :type token: str
|
232 |
| - :param token: Firebase Auth User ID Token. |
| 233 | + :param token: (Optional) Firebase Auth User ID Token, defaults |
| 234 | + to :data:`None`. |
233 | 235 |
|
| 236 | + :type expiration_hour: int |
| 237 | + :param expiration_hour: (Optional) time in ``hour`` for URL to |
| 238 | + expire after, defaults to 24 hours. Works only for links |
| 239 | + generated with admin credentials. |
234 | 240 |
|
235 | 241 | :return: URL for the file.
|
236 | 242 | :rtype: str
|
237 | 243 | """
|
238 | 244 |
|
| 245 | + # reset path |
239 | 246 | path = self.path
|
240 | 247 | self.path = None
|
241 | 248 |
|
| 249 | + # remove leading backlash |
242 | 250 | if path.startswith('/'):
|
243 | 251 | path = path[1:]
|
244 | 252 |
|
245 |
| - if token: |
246 |
| - return "{0}/o/{1}?alt=media&token={2}".format(self.storage_bucket, quote(path, safe=''), token) |
| 253 | + if self.credentials: |
| 254 | + blob = self.bucket.get_blob(path) |
| 255 | + if blob: |
| 256 | + return blob.generate_signed_url(datetime.timedelta(hours=expiration_hour), method='GET') |
| 257 | + |
| 258 | + elif token: |
| 259 | + |
| 260 | + # retrieve download tokens first |
| 261 | + headers = {"Authorization": "Bearer " + token} |
| 262 | + request_ref = "{0}/o/{1}".format(self.storage_bucket, quote(path, safe='')) |
| 263 | + request_object = self.requests.get(request_ref, headers=headers) |
| 264 | + |
| 265 | + raise_detailed_error(request_object) |
| 266 | + |
| 267 | + return "{0}/o/{1}?alt=media&token={2}".format(self.storage_bucket, quote(path, safe=''), request_object.json()['downloadTokens']) |
247 | 268 |
|
248 | 269 | return "{0}/o/{1}?alt=media".format(self.storage_bucket, quote(path, safe=''))
|
249 | 270 |
|
|
0 commit comments