<reponame>danielassis-dev/firestore_backup
# -*- coding: UTF-8 -*-

import firebase_admin
from firebase_admin import credentials
from firebase_admin import firestore
import json
from bson import json_util

'''
The serviceAccountKey.json file must be generated by firebase 
in the dashboard, settings, service account.
 '''
cred = credentials.Certificate(
    'serviceAccountKey.json')  # from firebase project settings
firebase_admin.initialize_app(cred)
firestore_client = firestore.client()


def import_collections(reference) -> dict:
    dict4json = dict()
    collections = reference.collections()

    for collectionRef in collections:
        dict4json[collectionRef.id] = {}
        for documentRef in collectionRef.list_documents():
            dict4json[collectionRef.id][documentRef.id] = {}

            dict4json[collectionRef.id][documentRef.id]['documentData'] = documentRef.get(
            ).to_dict()
            dict4json[collectionRef.id][documentRef.id]['documentSubcollections'] = import_collections(
                documentRef)
    return dict4json


dict4json = import_collections(firestore_client)
print(dict4json)

jsonfromdict = json.dumps(dict4json, indent=4, default=json_util.default)

with open('firestore_backup.json', 'w') as the_file:
    the_file.write(jsonfromdict)

input('Press [enter] to exit...')

# -*- coding: UTF-8 -*-

import firebase_admin
from firebase_admin import credentials
from firebase_admin import firestore
import json
from bson import json_util

'''
The serviceAccountKey.json file must be generated by firebase 
in the dashboard, settings, service account.
 '''
cred = credentials.Certificate(
    'serviceAccountKey.json')  # from firebase project settings
firebase_admin.initialize_app(cred)
firestore_client = firestore.client()


def import_collections(reference) -> dict:
    dict4json = dict()
    collections = reference.collections()

    for collectionRef in collections:
        dict4json[collectionRef.id] = {}
        for documentRef in collectionRef.list_documents():
            dict4json[collectionRef.id][documentRef.id] = {}

            dict4json[collectionRef.id][documentRef.id]['documentData'] = documentRef.get(
            ).to_dict()
            dict4json[collectionRef.id][documentRef.id]['documentSubcollections'] = import_collections(
                documentRef)
    return dict4json


dict4json = import_collections(firestore_client)
print(dict4json)

jsonfromdict = json.dumps(dict4json, indent=4, default=json_util.default)

with open('firestore_backup.json', 'w') as the_file:
    the_file.write(jsonfromdict)

input('Press [enter] to exit...')
# -*- coding: UTF-8 -*- The serviceAccountKey.json file must be generated by firebase  in the dashboard, settings, service account. # from firebase project settings