-
Notifications
You must be signed in to change notification settings - Fork 126
/
Copy pathFire.js
executable file
·109 lines (93 loc) · 2.69 KB
/
Fire.js
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
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
import uuid from 'uuid';
import getUserInfo from './utils/getUserInfo';
import shrinkImageAsync from './utils/shrinkImageAsync';
import uploadPhoto from './utils/uploadPhoto';
const firebase = require('firebase');
// Required for side-effects
require('firebase/firestore');
const collectionName = 'snack-SJucFknGX';
class Fire {
constructor() {
firebase.initializeApp({
apiKey: 'AIzaSyAQan8_IJ6fY6F8E06FMDKVbWlrdI75mvA',
authDomain: 'instahamm-b09ce.firebaseapp.com',
databaseURL: 'https://instahamm-b09ce.firebaseio.com',
projectId: 'instahamm-b09ce',
storageBucket: 'instahamm-b09ce.appspot.com',
messagingSenderId: '716190466061',
});
// Some nonsense...
firebase.firestore().settings({ timestampsInSnapshots: true });
// Listen for auth
firebase.auth().onAuthStateChanged(async user => {
if (!user) {
await firebase.auth().signInAnonymously();
}
});
}
// Download Data
getPaged = async ({ size, start }) => {
let ref = this.collection.orderBy('timestamp', 'desc').limit(size);
try {
if (start) {
ref = ref.startAfter(start);
}
const querySnapshot = await ref.get();
const data = [];
querySnapshot.forEach(function(doc) {
if (doc.exists) {
const post = doc.data() || {};
// Reduce the name
const user = post.user || {};
const name = user.deviceName;
const reduced = {
key: doc.id,
name: (name || 'Secret Duck').trim(),
...post,
};
data.push(reduced);
}
});
const lastVisible = querySnapshot.docs[querySnapshot.docs.length - 1];
return { data, cursor: lastVisible };
} catch ({ message }) {
alert(message);
}
};
// Upload Data
uploadPhotoAsync = async uri => {
const path = `${collectionName}/${this.uid}/${uuid.v4()}.jpg`;
return uploadPhoto(uri, path);
};
post = async ({ text, image: localUri }) => {
try {
const { uri: reducedImage, width, height } = await shrinkImageAsync(
localUri,
);
const remoteUri = await this.uploadPhotoAsync(reducedImage);
this.collection.add({
text,
uid: this.uid,
timestamp: this.timestamp,
imageWidth: width,
imageHeight: height,
image: remoteUri,
user: getUserInfo(),
});
} catch ({ message }) {
alert(message);
}
};
// Helpers
get collection() {
return firebase.firestore().collection(collectionName);
}
get uid() {
return (firebase.auth().currentUser || {}).uid;
}
get timestamp() {
return Date.now();
}
}
Fire.shared = new Fire();
export default Fire;