-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathProject.ts
More file actions
382 lines (301 loc) · 13.3 KB
/
Project.ts
File metadata and controls
382 lines (301 loc) · 13.3 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
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
import { Column, CreatedAt, Model, Table, UpdatedAt, PrimaryKey, AutoIncrement, DataType, BelongsToMany, HasMany } from 'sequelize-typescript';
import User, { getUserByDiscordId } from './User';
import UserProject, { DbToStdModal_UserProject, GetProjectCollaborators } from './UserProject';
import { IProject, IProjectCollaborator } from './types';
import { isUrl, levenshteinDistance, match } from '../common/helpers/generic';
import Tag, { DbToStdModal_Tag } from './Tag';
import ProjectTag from './ProjectTag';
import fs from 'fs';
import { BuildResponse, HttpStatus, ResponsePromiseReject } from '../common/helpers/responseHelper';
import { Response } from 'express';
import { GetGuildUser } from '../common/helpers/discord';
import ProjectImage from './ProjectImage';
import fetch from 'node-fetch';
@Table
export default class Project extends Model<Project> {
@PrimaryKey
@AutoIncrement
@Column(DataType.INTEGER)
declare id: number;
@Column
appName!: string;
@Column
description!: string;
@Column
isPrivate!: boolean;
@Column
downloadLink!: string;
@Column
githubLink!: string;
@Column
externalLink!: string;
@Column
awaitingLaunchApproval!: boolean;
@Column
needsManualReview!: boolean;
@Column
lookingForRoles!: string;
@Column
heroImage!: string;
@Column
appIcon!: string;
@Column
accentColor!: string;
@BelongsToMany(() => User, () => UserProject)
users?: User[];
@BelongsToMany(() => Tag, () => ProjectTag)
tags?: Tag[];
@HasMany(() => UserProject)
userProjects!: UserProject[];
@Column
category!: string;
@CreatedAt
@Column
declare createdAt: Date;
@UpdatedAt
@Column
declare updatedAt: Date;
}
export function isExistingProject(appName: string): Promise<boolean> {
return new Promise<boolean>((resolve, reject) => {
Project.findAll({
where: { appName: appName }
}).then(projects => {
resolve(projects.length > 0);
}).catch(reject)
});
}
export async function getProjectsByDiscordId(discordId: string): Promise<Project[]> {
let projects = await getAllDbProjects().catch(x => Promise.reject(x));
projects = projects.filter(x => x.users?.filter(x => x.discordId == discordId).length ?? 0 > 0);
if (!projects)
Promise.reject("User not found");
return projects;
}
export function getOwnedProjectsByDiscordId(discordId: string): Promise<Project[]> {
return new Promise(async (resolve, reject) => {
// Get user by id
const user = await getUserByDiscordId(discordId).catch(reject);
if (!user)
return;
// Get user projects with this id
const userProjects = await UserProject.findAll({ where: { userId: user.id, isOwner: true } }).catch(reject);
if (!userProjects)
return;
const results: Project[] = [];
// Get projects
for (let userProject of userProjects) {
const project = await Project.findOne({ where: { id: userProject.projectId } }).catch(reject);
if (project) {
results.push(project);
}
}
resolve(results);
});
}
export interface ISimilarProjectMatch {
distance: number;
appName: string;
}
export let IsRefreshingCache = false;
export let IsCacheInitialized = false;
export async function RefreshProjectCache() {
IsCacheInitialized = false;
IsRefreshingCache = true;
await getAllProjects();
IsRefreshingCache = false;
IsCacheInitialized = true;
}
export async function ProjectFieldsAreValid(project: IProject, res: Response): Promise<boolean> {
// Make sure download link is a valid URL
if (project.downloadLink && !isUrl(project.downloadLink)) {
BuildResponse(res, HttpStatus.MalformedRequest, "Invalid downloadLink");
return false;
}
// Make sure github link is a valid URL
if (project.githubLink && !isUrl(project.githubLink)) {
BuildResponse(res, HttpStatus.MalformedRequest, "Invalid githubLink");
return false;
}
// Make sure external link is a valid URL
if (project.externalLink && !isUrl(project.externalLink)) {
BuildResponse(res, HttpStatus.MalformedRequest, "Invalid externalLink");
return false;
}
// Make sure hero image is an image URL or a microsoft store image
if (project.heroImage && await isInvalidImage(project.heroImage)) {
if (!project.heroImage.includes("https")) {
BuildResponse(res, HttpStatus.MalformedRequest, "heroImage must be hosted on https");
return false;
}
BuildResponse(res, HttpStatus.MalformedRequest, "Invalid heroImage");
return false;
}
// Make sure images given are an image URL or a microsoft store image
if (project.images) {
for (let image of project.images) {
if (await isInvalidImage(image)) {
if (!image.includes("https")) {
BuildResponse(res, HttpStatus.MalformedRequest, "Images must be hosted on https");
return false;
}
BuildResponse(res, HttpStatus.MalformedRequest, "Invalid image");
return false;
}
}
}
// Make sure app icon is an image URL or a microsoft store image
if (project.appIcon && await isInvalidImage(project.appIcon)) {
if (!project.appIcon.includes("https")) {
BuildResponse(res, HttpStatus.MalformedRequest, "appIcon must be hosted on https");
return false;
}
BuildResponse(res, HttpStatus.MalformedRequest, "Invalid appIcon");
return false;
}
return true;
}
async function isInvalidImage(image: string): Promise<boolean> {
if (!image.includes("https"))
return true;
if (!isUrl(image))
return true;
var res = await fetch(image);
var contentType = res.headers.get("content-type");
if (!contentType)
return true;
return !contentType.includes("image/");
}
export function nukeProject(appName: string, discordId: string): Promise<void> {
return new Promise<void>((resolve, reject) => {
getAllDbProjects()
.then(async (allProjects) => {
const projects = allProjects.filter(x => x.appName == appName);
if (projects.length === 0) { ResponsePromiseReject(`Project with name "${appName}" could not be found.}`, HttpStatus.NotFound, reject); return; }
if (projects.length > 1) { ResponsePromiseReject("More than one project with that name found. Contact a system administrator to fix the data duplication", HttpStatus.InternalServerError, reject); return; }
const guildMember = await GetGuildUser(discordId);
const isMod = guildMember && [...guildMember.roles.cache.filter(role => role.name.toLowerCase() === "mod" || role.name.toLowerCase() === "admin").values()].length > 0;
const collaborators = await GetProjectCollaborators(projects[0].id);
const userCanModify = collaborators.filter(x => x.isOwner && x.discordId == discordId).length > 0 || isMod;
if (!userCanModify) {
ResponsePromiseReject("Unauthorized user", HttpStatus.Unauthorized, reject);
return;
}
const projectTags = await ProjectTag.findAll({ where: { projectId: projects[0].id } }).catch(err => ResponsePromiseReject(err, HttpStatus.InternalServerError, reject)) as ProjectTag[] | null;
for (var tag of projectTags ?? []) {
await tag.destroy();
}
const projectImages = await ProjectImage.findAll({ where: { projectId: projects[0].id } }).catch(err => ResponsePromiseReject(err, HttpStatus.InternalServerError, reject)) as ProjectImage[] | null;
for (let image of projectImages ?? []) {
await image.destroy();
}
const userProjects = await UserProject.findAll({ where: { projectId: projects[0].id } }).catch(err => ResponsePromiseReject(err, HttpStatus.InternalServerError, reject)) as UserProject[] | null;
for (const userProject of userProjects ?? []) {
await userProject.destroy();
}
projects[0].destroy({ force: true })
.then(resolve)
.catch(err => ResponsePromiseReject(err, HttpStatus.InternalServerError, reject));
}).catch(err => ResponsePromiseReject(err, HttpStatus.InternalServerError, reject));
});
}
export async function getAllDbProjects(customWhere: any = undefined): Promise<Project[]> {
const dbProjects = await Project.findAll({
include: [{
all: true
}],
where: customWhere,
}).catch(Promise.reject);
return (dbProjects);
}
export function getAllProjects(customWhere: any = undefined, cached: boolean = false): Promise<IProject[]> {
return new Promise(async (resolve, reject) => {
if (cached && IsCacheInitialized) {
var file = fs.readFileSync("./projects.json", {}).toString();
var cachedProjects = JSON.parse(file) as IProject[];
resolve(cachedProjects);
} else {
const DbProjects = await getAllDbProjects(customWhere).catch(reject);
let projects: IProject[] = [];
if (DbProjects) {
for (let project of DbProjects) {
let proj = DbToStdModal_Project(project);
if (proj) {
projects.push(proj);
}
}
}
fs.writeFileSync("./projects.json", JSON.stringify(projects), {});
IsCacheInitialized = true;
resolve(projects);
}
});
}
/**
* @summary Looks through a list of projects to find the closest matching app name
* @param projects Array of projects to look through
* @param appName App name to match against
* @returns Closest suitable match if found, otherwise undefined
*/
export function findSimilarProjectName(projects: Project[], appName: string, maxDistance: number = 7): string | undefined {
let matches: ISimilarProjectMatch[] = [];
// Calculate and store the distances of each possible match
for (let project of projects) {
matches.push({ distance: levenshteinDistance(project.appName, appName), appName: project.appName });
}
const returnData = matches[0].appName + (matches.length > 1 ? " or " + matches[1].appName : "");
// Sort by closest match
matches = matches.sort((first, second) => first.distance - second.distance);
// If the difference is less than X characters, return a possible match.
if (matches[0].distance <= maxDistance) return returnData; // 7 characters is just enough for a " (Beta)" label
// If the difference is greater than 1/3 of the entire string, don't return as a similar app name
if ((appName.length / 3) < matches[0].distance) return;
return returnData;
}
//#region Converters
/** @summary This converts the data model ONLY, and does not represent the actual data in the database */
export async function StdToDbModal_Project(project: Partial<IProject>): Promise<Partial<Project>> {
const dbProject: Partial<Project> = {
category: project.category,
appName: project.appName,
description: project.description,
isPrivate: project.isPrivate,
downloadLink: project.downloadLink,
githubLink: project.githubLink,
externalLink: project.externalLink,
awaitingLaunchApproval: project.awaitingLaunchApproval,
needsManualReview: project.needsManualReview,
heroImage: project.heroImage,
appIcon: project.appIcon,
accentColor: project.accentColor,
lookingForRoles: JSON.stringify(project.lookingForRoles)
};
return (dbProject);
}
export function DbToStdModal_Project(project: Project): IProject {
const collaborators: (IProjectCollaborator | undefined)[] = project.userProjects?.map(DbToStdModal_UserProject);
const stdProject: IProject = {
id: project.id,
appName: project.appName,
description: project.description,
isPrivate: project.isPrivate,
downloadLink: project.downloadLink,
githubLink: project.githubLink,
externalLink: project.externalLink,
collaborators: collaborators.filter(x => x != undefined) as IProjectCollaborator[],
category: project.category,
createdAt: project.createdAt,
updatedAt: project.updatedAt,
awaitingLaunchApproval: project.awaitingLaunchApproval,
needsManualReview: project.needsManualReview,
images: [],
features: [],
tags: project.tags?.map(DbToStdModal_Tag) ?? [],
heroImage: project.heroImage,
appIcon: project.appIcon,
accentColor: project.accentColor,
lookingForRoles: JSON.parse(project.lookingForRoles)
};
return (stdProject);
}
//#endregion