-
Notifications
You must be signed in to change notification settings - Fork 0
/
server.js
291 lines (283 loc) · 7.58 KB
/
server.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
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
var express = require("express");
var cors = require("cors");
const path = require("path");
const { format } = require("util");
var bodyparser = require("body-parser");
var admin = require("firebase-admin");
const { Storage } = require("@google-cloud/storage");
const multer = require("multer");
const fetch = require("node-fetch");
const cheerio = require("cheerio");
var app = express();
("use strict");
app.use(bodyparser.json());
app.use(bodyparser.urlencoded({ extended: true }));
app.use(cors());
const storage = new Storage({
projectId: "ratethenews-20e78",
keyFilename: path.join(__dirname, "./ratethenews-20e78-aa1bc0399669.json"),
});
const bucketref = storage.bucket("ratethenews-20e78.appspot.com");
var serviceAccount = require("./ratethenews-20e78-firebase-adminsdk-fe5k4-741d5391f5.json");
admin.initializeApp({
credential: admin.credential.cert(serviceAccount),
databaseURL: "https://ratethenews-20e78.firebaseio.com",
});
// database initialize
const db = admin.firestore();
var ref = db.collection("news-shows");
const userRef = db.collection("users");
var articleRef = db.collection("articles");
var upload = multer({
storage: multer.memoryStorage(),
limits: {
fileSize: 5 * 1024 * 1024, // no larger than 5mb, you can change as needed.
},
});
app.put("/submitshow", (req, res) => {
console.log(req.body);
var data = {
title: req.body.title,
tv_channel: req.body.tv_channel,
anchor: req.body.anchor,
timings: req.body.timings,
length: req.body.length,
};
ref.doc(req.body.title).set(data);
});
app.put("/fetchreviews", (req, res) => {
data = [];
db.collection("show-ratings")
.where("showid", "==", req.body.showid)
.get()
.then(function (querySnapshot) {
querySnapshot.forEach(function (doc) {
console.log(doc.id, " => ", doc.data());
data.push({
title: doc.data().title,
content: doc.data().content,
user: doc.data().user,
rating: doc.data().rating,
helpful: doc.data().helpful,
totalvotes: doc.data().totalvotes,
reviewid: doc.id,
uservote: null,
voteid: null
});
console.log(data);
});
res.send(data);
})
.catch(function (error) {
console.log("Error getting documents: ", error);
});
});
// fetch show
app.get("/fetchshows", (req, res) => {
let data = [];
db.collection("news-shows")
.get()
.then(function (querySnapshot) {
querySnapshot.forEach(function (doc) {
console.log(doc.id, " => ", doc.data());
data.push({
title: doc.data().title,
rating: doc.data().rating,
poster: doc.data().poster,
avgrating: doc.data().avgrating,
id: doc.id,
image: "",
});
console.log(data);
});
res.send(data);
})
.catch(function (error) {
console.log("Error getting documents: ", error);
});
});
/** fetch articles
* @return (articles: JSON)
*/
app.get("/fetchArticles", (req, res) => {
let data = [];
db.collection("articles")
.orderBy('votes', "desc")
.orderBy('time','desc')
.get()
.then((snapshot) => {
snapshot.forEach((doc) => {
console.log("Doc Id:", doc.id);
data.push({
docId: doc.id,
title: doc.data().title,
time: doc.data().time,
votes: doc.data().votes,
uid: doc.data().uid,
});
console.log(data);
});
res.send(data);
})
.catch((e) => console.error("Errow While Fetching Articles", e));
});
app.get("/fetchArticlesbynew", (req, res) => {
let data = [];
db.collection("articles")
.orderBy('time','desc')
.get()
.then((snapshot) => {
snapshot.forEach((doc) => {
console.log("Doc Id:", doc.id);
data.push({
docId: doc.id,
title: doc.data().title,
time: doc.data().time,
votes: doc.data().votes,
uid: doc.data().uid,
});
console.log(data);
});
res.send(data);
})
.catch((e) => console.error("Errow While Fetching Articles", e));
});
// editorjs image uploader
app.post("/image-upload", upload.single("image"), (req, res) => {
const file = req.file;
if (file) {
uploadImageToStorage(file)
.then((data) => {
res.send({
success: 1,
file: {
url: data,
},
});
})
.catch((e) => console.log(e));
}
});
async function uploadImageToStorage(imageFile) {
console.log(imageFile);
return new Promise((resolve, reject) => {
if (!imageFile) {
reject("No image file");
return;
}
let newFileName = Date.now() + "-" + imageFile.originalname;
let fileUpload = bucketref.file(newFileName);
const blobStream = fileUpload.createWriteStream({
resumable: false,
gzip: true,
});
blobStream.on("error", (error) => {
console.error(error);
});
blobStream.on("finish", () => {
const url = format(
`http://storage.googleapis.com/${bucketref.name}/${fileUpload.name}`
);
resolve(url);
console.log("Uploaded Successfully");
});
blobStream.end(imageFile.buffer);
});
}
// editorjs link previewer
app.get("/fetchUrl", async (req, res) => {
let url = req.query.url;
let resHTML = await fetch(new URL(url)).catch((e) => console.log(e));
const html = await resHTML.text();
const $ = cheerio.load(html);
// custom meta-tag function
const getMetaTag = (value) => {
return (
$(`meta[name=${value}]`).attr("content") ||
$(`meta[property="og:${value}"]`).attr("content") ||
$(`meta[property="twitter:${value}"]`).attr("content")
);
};
const resi = {
success: 1,
meta: {
title: $("title").first().text(),
description: getMetaTag("description"),
image: {
url: getMetaTag("image"),
},
},
};
res.send(resi);
return;
});
// get user data by UID
app.get("/getUserByUid", (req, res) => {
userRef
.doc(req.query.uid)
.get()
.then((val) => res.send(val.data()))
.catch((e) => {
console.log(e);
});
});
app.get("/getArticleHeadings", (req, res) => {
articleRef
.doc(req.query.article)
.get()
.then((val) => res.send(val.data()))
.catch((e) => console.log(e));
});
/**
* @params (uid, showId)
* @return (show rating of showId of the requested user uid)
**/
app.get("/getMyRating", (req, res) => {
id = "";
data = [];
const query = req.query.query;
const i = query.indexOf("-");
const showId = query.substring(0, i);
const uid = query.substring(i + 1);
db.collection("show-ratings")
.where("showid", "==", showId)
.where("user", "==", uid)
.get()
.then((snapShot) => {
snapShot.forEach((doc) => {
data.push(doc.data());
id = doc.id;
});
})
.then(() => data.push(id))
.then(() => res.send(data))
.catch((e) => console.error(e));
});
app.get("/getRatedTvShowsByUid", (req, res) => {
const data = [];
const uid = req.query.id;
db.collection("show-ratings")
.where("user", "==", uid)
.get()
.then((snapShot) => {
snapShot.forEach((doc) => {
data.push(doc.data());
});
})
.then(() => res.send(data))
.catch((e) => console.log(e));
});
app.get("/getShowById", (req, res) => {
const id = req.query.id;
db.collection("news-shows")
.doc(id)
.get()
.then((doc) => {
const data = doc.data();
data["showID"] = doc.id;
res.send(data);
})
.catch((e) => console.error(e));
});
const PORT = process.env.port || 3000;
app.listen(PORT, () => console.log(`Node.js server is running on ${PORT}`));