File size: 2,189 Bytes
428a607
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
import os
import pyrebase
import tempfile
import uuid

from dotenv import load_dotenv
from firebase_admin import credentials, initialize_app, firestore, storage


load_dotenv(override=True)

firebase_config = {
    'apiKey': os.getenv('FIREBASE_API_KEY'),
    'authDomain': os.getenv('FIREBASE_AUTH_DOMAIN'),
    'projectId': os.getenv('FIREBASE_PROJECT_ID'),
    'storageBucket': os.getenv('FIREBASE_STORAGE_BUCKET'),
    'messagingSenderId': os.getenv('FIREBASE_MESSAGING_SENDER_ID'),
    'appId': os.getenv('FIREBASE_APP_ID'),
    'databaseURL': ''
}

firebase_admin_config = {
    'type': os.getenv('FIREBASE_ADMIN_TYPE'),
    'project_id': os.getenv('FIREBASE_ADMIN_PROJECT_ID'),
    'private_key_id': os.getenv('FIREBASE_ADMIN_PRIVATE_KEY_ID'),
    'private_key': os.getenv('FIREBASE_ADMIN_PRIVATE_KEY').replace('\\n', '\n'),
    'client_email': os.getenv('FIREBASE_ADMIN_CLIENT_EMAIL'),
    'client_id': os.getenv('FIREBASE_ADMIN_CLIENT_ID'),
    'auth_uri': os.getenv('FIREBASE_ADMIN_AUTH_URI'),
    'token_uri': os.getenv('FIREBASE_ADMIN_TOKEN_URI'),
    'auth_provider_x509_cert_url': os.getenv('FIREBASE_ADMIN_AUTH_PROVIDER_X509_CERT_URL'),
    'client_x509_cert_url': os.getenv('FIREBASE_ADMIN_CLIENT_X509_CERT_URL'),
    'universe_domain': os.getenv('FIREBASE_ADMIN_UNIVERSE_DOMAIN')
}

firebase = pyrebase.initialize_app(firebase_config)
firebase_admin = initialize_app(credentials.Certificate(firebase_admin_config), {
    'storageBucket': os.getenv('FIREBASE_STORAGE_BUCKET')
})

firebase_auth = firebase.auth()
firebase_db = firestore.client()
firebase_storage = storage.bucket()


def storage_upload_file(file, destination_folder):
    temp = tempfile.NamedTemporaryFile(delete=False)
    file.save(temp.name)
    temp.close()

    unique_filename = str(uuid.uuid4()) + '.' + file.filename.split('.')[-1]

    blob = firebase_storage.blob(f'{destination_folder}/{unique_filename}')
    blob.upload_from_filename(temp.name)
    blob.make_public()
    os.remove(temp.name)

    return blob.public_url


def storage_delete_file(public_url):
    firebase_storage.blob(public_url.replace(f'https://storage.googleapis.com/{os.getenv('FIREBASE_STORAGE_BUCKET')}/', '')).delete()