-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
239 lines (198 loc) · 6.77 KB
/
index.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
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
const express = require('express');
var router = require('./apiManager')
var admin = require("firebase-admin");
var cors = require('cors')
var os = require("os");
// deploy to vercel for testing
// Vercel platform is event-driven, therefore not maintaining a running server,
// we recommend using a third-party service to schedule these tasks.
// Simply means no automation, no scheduler, no cron job of any sort.
var serviceAccount = require("./fbCert/vietnamagron-be-fb-firebase-adminsdk-63suj-361b8f9b86.json");
admin.initializeApp({
credential: admin.credential.cert(serviceAccount)
});
const db = admin.firestore();
const usersDb = db.collection('users');
const liam = usersDb.doc('lragozzine');
const PORT = process.env.PORT || 3000
var app = module.exports = express();
/* JSON body parse*/
const bodyParser = require('body-parser');
app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());
const server = app.listen(PORT, () => {
console.info('Server is running on PORT:', PORT);
// Automatically start connection to DB right after the server goes live. Does not work on event-driven server like Vercel.
startDBConnection();
console.log(os.hostname())
});
app.use(router)
// var whitelist = ['*']
// var corsOptions = {
// origin: function (origin, callback) {
// if (whitelist.indexOf(origin) !== -1) {
// callback(null, true)
// } else {
// callback(new Error('Not allowed by CORS'))
// }
// callback(null, true)
// },
// optionsSuccessStatus:200
// }
var corsOptions = {
"origin": "*",
"methods": ["GET", "HEAD", "PUT", "PATCH", "POST", "DELETE"],
"preflightContinue": false,
"optionsSuccessStatus": 204
}
app.use(cors(corsOptions))
app.get('/', (req, res, next) => {
res.sendFile('index.html', {
root: '.'
});
})
app.get('/hello', (req, res, next) => {
console.info('/hello call success ');
liam.update({
'name': 'abc',
'age': 41
})
.then(
result => console.log(result)
)
liam.get()
.then(result => {
console.log(result.data())
res.send(result.data());
})
.catch(err => {
console.log(err)
res.send(err);
})
// res.send('Welcome to Firebase Cloud Functions');
});
/////////////////////////////////////////////////////////socket.io ////////////////////////////////////////
// const io = require("socket.io")(server, {
// cors: {
// origin: "*",
// methods: ["GET", "POST"]
// }
// });
// const activeUsers = new Set();
// io.on("connection", function (socket) {
// console.log("Made socket connection");
// socket.on("newUser", function (data) {
// socket.userId = data;
// activeUsers.add(data);
// io.emit("new user", [...activeUsers]);
// });
// socket.on("disconnect", () => {
// activeUsers.delete(socket.userId);
// io.emit("user disconnected", socket.userId);
// });
// socket.on("priceAlertSubscribe", function (data) {
// // Data Model Expectation
// // data = {
// // targetCoin: '',
// // alertAtPrice: ''
// // }
// // io.emit("chat message", data);
// console.log(data)
// });
// socket.on("cancelPriceAlert", function (data) {
// // Data Model Expectation
// // data = {
// // alertID: ''
// // }
// // io.emit("chat message", data);
// console.log(data)
// });
// // socket.on("typing", function (data) {
// // socket.broadcast.emit("typing", data);
// // });
// });
///////////////////////////////////////////// Worker Thread /////////////////////////////////////
// const { Worker } = require('worker_threads')
// const runService = (param) => {
// return new Promise((resolve, reject) => {
// // import workerExample.js script, option is the data passing from main thread to the worker thread
// const worker = new Worker('./workerThreadSample.js', { workerData: param });
// console.log(`ID của thread vừa tạo: ${worker.threadId}`)
// worker.postMessage('this is the message coming from main thread')
// //These events work when worker send messages to main thread
// worker.on('message', resolve);
// worker.on('error', reject);
// worker.on('exit', (code) => {
// if (code !== 0)
// reject(new Error(`stopped with ${code} exit code`));
// })
// })
// }
// const run = async () => {
// const result = await runService('hello John Doe')
// console.log(result);
// }
// // for(let i=0; i<10; ++i)
// run().catch(err => console.error(err))
///////////////////////////////////////////////////APNs push notification/////////////////////////////////////
// var apns= require('./apnsPushManager')
// apns.createNewNotification()
///////////////////////////////HLS streaming ///////////////////////////////
var fs = require('fs');
app.get('/videos/hls/*', (req, res, next) => {
console.log(req.url)
var filePath = '.' + req.url;
console.log(filePath)
fs.readFile(filePath, function (error, content) {
if (error) {
console.log(error)
res.status(500).send('Failed to read file')
}
else {
console.log(content)
res.status(200).send(content);
}
});
});
app.get('/videos/dash/*', (req, res, next) => {
console.log(req.url)
var filePath = '.' + req.url;
console.log(filePath)
fs.readFile(filePath, function (error, content) {
if (error) {
console.log(error)
res.status(500).send('Failed to read file')
}
else {
console.log(content)
res.status(200).send(content);
}
});
});
/////////////////////////////////////FFMPEG//////////////////////////////////////////////////
// var ffmpeg = require('./ffmpegStreaming')
// app.get('/stream/abc.flv', (req, res, next) => {
// ffmpeg()
// .input('http://14.225.23.40:80/streams/60f8fa790655a40011d55419/stream/60f8fa790655a40011d55419.m3u8')
// .outputOptions([
// '-vcodec libx265',
// '-f flv'
// ])
// .on('start', function(commandLine) {
// console.log('Running ffmpeg with command: ' + commandLine);
// })
// .on('codecData', function(data) {
// console.log('Input is ' + data.audio + ' audio ' + 'with ' + data.video + ' video');
// })
// .on('progress', function(progress) {
// console.log('Processing: ' + progress.percent + '% done');
// })
// .on('error', function(err, stdout, stderr) {
// console.log('Error while Processing video: ' + err.message);
// })
// .on('end', function() {
// console.log('Transcoding succeeded!');
// })
// // .save('http://localhost:3000/stream/abc.flv').run();
// .pipe(res, {end: true});
// });