hurricane/security_camera/resources/cloud_server/public/src/boot/firebase/Firestore.js

import 'firebase/firestore'
import { store } from 'store'
import { FIREBASE_CONFIG } from 'firebaseConfig/firebase-config'
export default class Firestore {
/*********************************************************************************************************/
constructor (app) {
this.app = app
this.db = app.firestore()
this.db.enablePersistence().then(() => {
logger.debug('firestore persistence enabled')
}).catch((err) => {
logger.error(`Failed to enable firestore persistence, err:${err.description || err.message || err}`)
})
this.auth = app.auth()
this.deviceRef = null
this.deviceWatchCancel = null
this.imagesWatchCancel = null
}
/*********************************************************************************************************/
getDeviceDocument () {
const self = this
let deviceId = store.getters['firebase/deviceId']
if (!deviceId) {
throw new Error('No deviceId')
}
this.deviceRef = this.db.collection('devices').doc(deviceId)
store.commit('firebase/error', null)
return this.deviceRef.get().catch((err) => {
logger.error(`Failed to get device database reference, err:${err.message || err.toString()}`)
if (err.code === 'permission-denied') {
logger.debug('forcefully logging out')
self.app.backend.auth.unregister()
} else if(err.message && err.message.toLowerCase().includes('quota exceeded')) {
store.commit('firebase/error', 'quota-exceeded')
}
throw err
})
}
/*********************************************************************************************************/
watchDevice () {
const self = this
if (this.deviceWatchCancel) {
return Promise.resolve()
}
this.deviceWatchCancel = () => {}
logger.debug(`Watching device ...`)
return this.getDeviceDocument().then((snapshot) => {
self.deviceRef = snapshot.ref
self.deviceWatchCancel = self.deviceRef.onSnapshot((doc) => {
logger.debug('Device details updated')
store.commit('firebase/device', doc.data())
})
}).catch((err) => {
self.deviceWatchCancel = null
throw err
})
}
/*********************************************************************************************************/
syncDevice () {
if (this.deviceRef) {
let details = store.getters['firebase/device']
return this.deviceRef.update(details)
} else {
return new Promise().resolve()
}
}
/*********************************************************************************************************/
stopWatching() {
this.deviceRef = null
if(this.deviceWatchCancel) {
this.deviceWatchCancel()
this.deviceWatchCancel = null
}
if(this.imagesWatchCancel) {
this.imagesWatchCancel()
this.imagesWatchCancel = null
}
}
/*********************************************************************************************************/
retrieveImages(maxCount) {
if(!this.deviceRef) {
return []
}
const self = this
store.commit('firebase/error', null)
let query = this.deviceRef.collection('images').orderBy('timestamp', 'desc').limit(maxCount)
return query.get().then((snapshot) => {
let results = []
for(let i = 0; i < snapshot.docs.length; i++) {
let doc = snapshot.docs[i].data()
let result = {
timestamp: doc.timestamp,
meta: doc.meta,
url: self._getImageUrl(doc.path, doc.token)
}
results.push(result)
}
if(results.length > 0) {
store.commit('firebase/newestImage', results[0])
}
return results
}).catch((err) => {
if(err.message && err.message.toLowerCase().includes('quota exceeded')) {
store.commit('firebase/error', 'quota-exceeded')
}
throw err
})
}
/*********************************************************************************************************/
watchImages(callback) {
if(!this.deviceRef) {
throw new Error('Cant watch images, no deviceRef!')
}
let query = this.deviceRef.collection('images')
if(this.imagesWatchCancel) {
this.imagesWatchCancel()
}
this.imagesWatchCancel = query.onSnapshot(callback)
}
/*********************************************************************************************************/
_getImageUrl(path, token) {
// https://firebasestorage.googleapis.com/v0/b/[BUCKET_NAME]/o/[FILE_PATH]?alt=media&token=[THE_TOKEN_YOU_CREATED]
return `https://firebasestorage.googleapis.com/v0/b/${FIREBASE_CONFIG.storageBucket}/o/${encodeURIComponent(path)}?alt=media&token=${token}`
}
}