· 4 years ago · May 28, 2021, 01:04 AM
1import express from "express";
2import fs from "fs"
3import { join } from "path"
4import https from "https";
5import http from "http"
6import cors from "cors"
7//import redis from "redis"
8
9//import { promisify } from "util"
10const app = express();
11import { PrismaClient } from '@prisma/client'
12import { fetchBans, fetchChats, fetchIP, findPlayer, resolveAliases } from "./functions/playerFuntions";
13import { fetchMembers } from "./functions/clanmemberFunctions";
14//import { chatlogFetch } from "./functions/chatlogFunctions";
15import { LoginUser } from "./functions/authFunctions";
16import { decrypt } from "./functions/stringFunctions";
17
18import MessageCollection from "./structs/MessageCache"
19import { addRule, SettingUpdateResult, updateSetting } from "./functions/settingFunctions";
20import { postNewRecruitment, RecruitmentPostRequest, RecruitmentResolveRequest, recruitmentsFetch, resolveRecruitment } from "./functions/recruitmentShit";
21//import { updateSetting } from "./functions/settingFunctions";
22
23const corsOptions = {
24 //origin: 'http://localhost:3000',
25 optionsSuccessStatus: 200 // some legacy browsers (IE11, various SmartTVs) choke on 204
26}
27
28/*const client = redis.createClient({
29 host: "127.0.0.1",
30 port: 6379
31})*/
32
33
34//export const redis_get = promisify(client.get).bind(client)
35//export const redis_set = promisify(client.set).bind(client)
36
37app.use(cors(corsOptions))
38app.use(express.json())
39app.use(express.urlencoded({
40 extended: true
41 }))
42//@ts-ignore
43app.use(function (req, res, next) {
44 // Website you wish to allow to connect
45 res.setHeader('Access-Control-Allow-Origin', '*');
46 // Request methods you wish to allow
47 res.setHeader('Access-Control-Allow-Methods', 'GET, POST, OPTIONS, PUT, PATCH, DELETE');
48 // Request headers you wish to allow
49 res.setHeader('Access-Control-Allow-Headers', 'X-Requested-With,content-type');
50 // Set to true if you need the website to include cookies in the requests sent
51 // to the API (e.g. in case you use sessions)
52 res.setHeader('Access-Control-Allow-Credentials', "true");
53 // Pass to next layer of middleware
54 next();
55});
56
57app.use(function(req, res, next) {
58 if (!req.headers.authorization || req.headers.authorization !== "56365298923549946646") {
59 return res.status(403).json({ error: 'No credentials sent!' });
60 }
61 return next();
62 });
63
64export const prisma = new PrismaClient();
65
66const cache = new MessageCollection()
67
68app.get("/users/:uid", async (req, res) => {
69 const id = req.params.uid
70
71 const player = await prisma.cod2_players.findFirst({where: {id: Number(id)}})
72
73 if(!player) {
74 return res.json({error: "Not Found!"})
75 }
76
77 const location = await fetchIP(player)
78 const aliases = await resolveAliases(player.id)
79 const messages = await fetchChats(player.id)
80 const bans = await fetchBans(player.id)
81
82
83 return res.json({messages, aliases, banList: bans, player, location})
84})
85
86//@ts-ignore
87app.get("/settings", async(req, res) => {
88 const settings = await prisma.cod2_serverinfo.findMany()
89
90 return res.json(settings)
91})
92
93app.post("/settings/update", async(req, res) => {
94 console.log(req.body.data)
95 const data = req.body.data as SettingPost[]
96
97 const results: SettingUpdateResult[] = []
98 for await (const setting of data) {
99 const res = await updateSetting(setting.key, setting.value , parseInt(setting.forced) === 1)
100 results.push(res)
101 }
102
103 let str = "Results: "
104 for(let i = 0; i < results.length; i++) {
105 str += `key: ${results[i].key } => result: ${results[i].result ? "Success" : "Failed"}\n`
106 }
107
108 return res.json({message: str})
109})
110
111app.post("/rules/update", async (req, res) => {
112 const data = req.body.data as Rule[]
113
114 for(const rule of data) {
115 await addRule(rule.type, rule.rule)
116 }
117
118 res.json({message: "Rules have been added!"})
119})
120
121//@ts-ignore
122app.get("/rules", async(req, res) => {
123 const rules = await prisma.cod2_rules.findMany({where: {type: 0}}) as Rule[]
124 const info = await prisma.cod2_rules.findMany({where: {type: 1}}) as Rule[]
125
126 return res.json({rules, info})
127})
128
129app.get("/users/bans/:uid", async (req, res) => {
130 const playerid = req.params.uid;
131 if(!playerid) return res.json({error: "Invalid Request!"})
132
133 const bans = await fetchBans(parseInt(playerid))
134
135 return res.json(bans)
136
137})
138
139//@ts-ignore
140app.get('/members', async( req, res) => {
141 const memberList = await fetchMembers()
142
143 return res.json(memberList)
144})
145
146
147app.get("/chats/:limit", async(req, res) => {
148
149 const limit = req.params.limit ? Number(req.params.limit) : 500
150
151 const array = cache.getMany(limit)
152
153 res.json(array)
154})
155
156app.get("/findplayer/:name", async (req, res) => {
157 const name = req.params.name;
158
159 if(!name) return res.json({error: "not found!"});
160
161 const list = await findPlayer(name)
162
163 return res.json(list)
164})
165
166app.get("/login", async (req, res) => {
167 const username = req.query.username as string
168 const pass = req.query.pass as string
169 const data = await LoginUser(decrypt(username), decrypt(pass));
170 if(!data) return res.json({error: "Invalid Request!"});
171
172 return res.json(data)
173})
174
175//@ts-ignore
176app.get("/recruitments", async (req, res) => {
177 const recs = await recruitmentsFetch();
178 return res.json(recs)
179})
180
181app.get("/recruitments/:id", async (req, res) => {
182 const id = req.params.id
183
184 const recs = await recruitmentsFetch();
185 return res.json(recs.filter(x => x.uid === Number(id)))
186})
187
188app.post("/recruitments/post", async(req, res) => {
189
190 const body = req.body.data as RecruitmentPostRequest
191
192 body.uid = Number(body.uid)
193 const success = await postNewRecruitment(body)
194 if(!success.recruitmentID) {
195 return res.status(500).json({success: false, message: "Something went wrong!"})
196 }
197 return res.json({success: true, message: "Succesfully posted your recruitment!"})
198})
199
200app.post("/recruitments/resolve", async(req, res) => {
201 const body = req.body.data as RecruitmentResolveRequest
202
203 body.recruitmentID = Number(body.recruitmentID)
204 body.reason = body.reason ? body.reason : "No reason provided!"
205
206 const resolve = await resolveRecruitment(body)
207 if(!resolve) {
208 return res.json({success: false, message: "Something went wrong resolving this application!"})
209 } else {
210 return res.json({success: true, message: `Succesfully ${body.accepted === true ? "accepted" : "denied"} the recruitment!`})
211 }
212})
213
214cache.loadFirst().then(() => {
215 setInterval(() => {
216
217 cache.loadMore()
218
219 }, 1000)
220})
221
222
223const httpServer = http.createServer(app)
224
225const server = https.createServer({
226key: fs.readFileSync(join(__dirname, ".." , "certs", "key.pem")),
227cert: fs.readFileSync(join(__dirname, "..", "certs", "cert.pem"))
228}, app)
229
230httpServer.listen(4001, () => console.log(`HTTP on 4001`))
231server.listen(4000, () => console.log(`Online on port 4000!`));
232
233interface SettingPost {
234 key: string
235 value: string
236 forced: string
237}
238
239export interface Rule {
240 type: number
241 rule: string
242}
243