forked from devuxd/SeeCodeRun
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathindex.js
More file actions
308 lines (284 loc) · 10.6 KB
/
index.js
File metadata and controls
308 lines (284 loc) · 10.6 KB
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
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
const functions = require('firebase-functions');
const admin = require('firebase-admin');
// Fixes firepad 1.4.0 infamous line with window.firebase in Node.
global.window = {};
const Firepad = require('firepad');
const config = require("./cloud-functions.json");
const uid = config.uid; // matches the uid used in db rules
let sAccount = null, dbUrl = null;
if (process.env.NODE_ENV === 'development') {
sAccount = require("./serviceAccountKey.dev.json");
dbUrl = config.devDbURL;
} else {
sAccount = require("./serviceAccountKey.prod.json");
dbUrl = config.prodDbURL;
}
const serviceAccount = sAccount;
const dataBaseUrl = dbUrl;
const REQUEST_TIMEOUT_MS = 5000;
const SERVER_TIMESTAMP = admin.database.ServerValue.TIMESTAMP;
const dataBaseRoot = '/scr2'; //todo change to scr2/test when testing locally
const defaultPastebinScheme = {
creationTimestamp: SERVER_TIMESTAMP,
firecos: 0, //history on each child handled by Firepad: html, js, css
search: 0,
chat: 0,
shares: {
currentEvent: 0,
parentPastebinId: 0,
children: 0
},
users: 0
};
admin.initializeApp({
credential: admin.credential.cert(serviceAccount),
databaseURL: dataBaseUrl,
// storageBucket: "firebase-seecoderun.appspot.com",
databaseAuthVariableOverride: {
uid: uid
}
});
const databaseRef = admin.database();
// Provide custom logger which prefixes log statements with "[FIREBASE]"
// Disable logging across page refreshes
// databaseRef.enableLogging(function (message) {
// console.log("[FIREBASE]", message);
// },
// false);
let databaseRootRef = databaseRef.ref(dataBaseRoot);
// Data functions
const makeNewPastebin = onComplete => {
return databaseRootRef
.push(defaultPastebinScheme, onComplete);
};
const makeNewPastebinId = () => {
return databaseRootRef.push(0).key;
};
const attemptResponse = (
res,
pastebinResponse, firepadTimeOut, firepadsEditorIds, doneEditorId, text) => {
firepadsEditorIds[doneEditorId].isFulfilled = true;
pastebinResponse.initialEditorsTexts[doneEditorId] = text;
for (const editorId in firepadsEditorIds) {
if (!firepadsEditorIds[editorId].isFulfilled) {
return;
}
}
res.status(200).send(pastebinResponse);
clearTimeout(firepadTimeOut);
};
const sendExistingContent = (res, pastebinResponse, firebasePastebinRef) => {
const firepadsEditorIds = {
'js': {isFulfilled: false},
'html': {isFulfilled: false},
'css': {isFulfilled: false}
};
const firepadTimeOut = setTimeout(() => {
pastebinResponse.error = '[Server Error]:' +
' Timeout getting pastebin data after ' + REQUEST_TIMEOUT_MS + 'ms';
res.status(500).send(pastebinResponse);
console.log(pastebinResponse.error, pastebinResponse);
},
REQUEST_TIMEOUT_MS);
for (const editorId in firepadsEditorIds) {
const headlessFirepad =
new Firepad.Headless(firebasePastebinRef.child(`firecos/${editorId}`));
headlessFirepad.getText(text => {
attemptResponse(
res,
pastebinResponse, firepadTimeOut, firepadsEditorIds, editorId, text);
headlessFirepad.dispose();
});
}
};
const makeFirebaseReferenceCopy = (
source, destination, changeData, onComplete, onError) => {
source.once("value").then(snapshot => {
if (snapshot.exists()) {
destination.set(changeData(snapshot.val()), onComplete);
} else {
onError({
type: '[Client Error]',
details: 'Provided pastebinId does not exist.',
message: null
});
}
}).catch(error =>
onError({
type: "[Server Error]",
details: 'Error copying pastebin.',
message: error
})
);
};
const copyPastebinById = (parentPastebinId, res, pastebinResponse) => {
const childPastebinId = makeNewPastebinId();
let sourceReference =
databaseRootRef.child(`${parentPastebinId}/`);
let destinationReference =
databaseRootRef.child(`${childPastebinId}/`);
const changeData = data => {
data.creationTimestamp = SERVER_TIMESTAMP;
if (!pastebinResponse.copyUsers) {
data.users = {};
}
if (!pastebinResponse.copyChat) {
data.chat = {};
}
data.shares = {
currentEvent: 0,
parentPastebinId: parentPastebinId,
children: 0
};
return data;
};
const onError = error => {
pastebinResponse.error = `${error.type}: ${error.details}`;
if (!pastebinResponse.isSent) {
res.status('[Server Error]' ? 500 : 400).send(pastebinResponse);
pastebinResponse.isSent = true;
}
destinationReference.remove(e => {
console.log(error.type, error.details, error.message, e);
});
};
const onComplete = error => {
if (error) {
onError({
type: '[Server Error]',
details: 'Could not update new copy of ' +
' provided pastebin.',
message: error
});
} else {
sourceReference.child('shares/children')
.push({childPastebinId: childPastebinId, timestamp: SERVER_TIMESTAMP},
error => {
if (error) {
onError({
type: '[Server Error]',
details: 'Could not update parent\'s children data during' +
' pastebin copy.',
message: error
});
} else {
pastebinResponse.pastebinId = childPastebinId;
if (!pastebinResponse.isSent) {
res.status(200).send(pastebinResponse);
pastebinResponse.isSent = true;
}
}
});
}
};
makeFirebaseReferenceCopy(
sourceReference, destinationReference, changeData, onComplete, onError);
};
// Cloud Functions:
exports.getPastebinId = functions.https.onRequest((req, res) => {
const pastebinResponse = {
pastebinId: null,
error: null
};
try {
const pastebinRef = makeNewPastebin(() => {
pastebinResponse.pastebinId = pastebinRef.key;
if (!pastebinResponse.isSent) {
res.status(200).send(pastebinResponse);
pastebinResponse.isSent = true;
}
});
} catch (error) {
pastebinResponse.error = '[Server Error]: Internal error.';
if (!pastebinResponse.isSent) {
res.status(500).send(pastebinResponse);
pastebinResponse.isSent = true;
}
console.log(pastebinResponse.error, error);
}
});
exports.getPastebin = functions.https.onRequest((req, res) => {
const pastebinResponse = {
pastebinId: req.query.pastebinId,
initialEditorsTexts: {},
error: null
};
try {
if (pastebinResponse.pastebinId) {
const firebasePastebinRef =
databaseRootRef.child(`${pastebinResponse.pastebinId}`);
firebasePastebinRef.once('value').then(snapshot => {
if (snapshot.exists()) {
sendExistingContent(res, pastebinResponse, firebasePastebinRef);
} else {
pastebinResponse.error = '[Client Error]: Pastebin does not exist.' +
' Custom pastebinIds are not allowed.';
res.status(400).send(pastebinResponse);
console.log(pastebinResponse.error, pastebinResponse);
}
}).catch(error => {
pastebinResponse.error = '[Server Error]: Internal error.';
res.status(500).send(pastebinResponse);
console.log(pastebinResponse.error, error);
});
} else {
pastebinResponse.error = '[Client Error]: PastebinId was not provided.';
res.status(400).send(pastebinResponse);
console.log(pastebinResponse.error, pastebinResponse);
}
} catch (error) {
pastebinResponse.error = '[Server Error]: Internal error.';
res.status(400).send(pastebinResponse);
console.log(pastebinResponse.error, pastebinResponse, error);
}
});
exports.copyPastebin = functions.https.onRequest((req, res) => {
const pastebinResponse = {
sourcePastebinId: req.query.sourcePastebinId,
copyUsers: req.query.copyUsers,
copyChat: req.query.copyChat,
pastebinId: null,
error: null
};
try {
if (pastebinResponse.sourcePastebinId) {
copyPastebinById(pastebinResponse.sourcePastebinId, res, pastebinResponse);
} else {
pastebinResponse.error = '[Client Error]: No Pastebin ID was provided.' +
' Please add pastebinId="a_value" to the URL.';
res.status(400).send(pastebinResponse);
console.log(pastebinResponse.error, pastebinResponse);
}
} catch (error) {
pastebinResponse.error = '[Server Error]: Internal Error.';
res.status(500).send(pastebinResponse);
console.log(pastebinResponse.error, pastebinResponse);
}
});
exports.getPastebinToken = functions.https.onRequest((req, res) => {
const pastebinResponse = {
pastebinToken: null,
error: null
};
const uid = req.query.pastebinId;
if (uid) {
admin.auth().createCustomToken(uid)
.then(customToken => {
pastebinResponse.pastebinToken = customToken;
res.status(200).send(pastebinResponse);
})
.catch(error => {
pastebinResponse.error = '[Server Error]: Authentication failed ' +
'while accessing pastebin. Please inform admin to get renew ' +
'Firebase service account.';
res.status(500).send(pastebinResponse);
console.log(pastebinResponse.error, error);
});
} else {
pastebinResponse.error = '[Client Error]: No Pastebin ID was provided. ' +
'Please add pastebinId="a_value" to the URL';
res.status(400).send(pastebinResponse);
console.log(pastebinResponse.error, error);
}
});
process.env.NODE_ENV === 'development' && console.log('USING DEVELOPMENT FIREBASE DB FOR FUNCTIONS: ', Object.keys(exports || {}));