Skip to content

Commit

Permalink
Merge branch 'main'
Browse files Browse the repository at this point in the history
  • Loading branch information
TheGamerzs committed Mar 20, 2021
2 parents 67cfc66 + 2a7e3aa commit 9de8fa5
Show file tree
Hide file tree
Showing 39 changed files with 1,866 additions and 572 deletions.
4 changes: 3 additions & 1 deletion .env.example
Original file line number Diff line number Diff line change
Expand Up @@ -6,4 +6,6 @@ DISCORD_WEBHOOK_ID=ID
DISCORD_WEBHOOK_TOKEN=TOKEN

CROWDINBASE=
CROWDINWEBHOOK=
CROWDINWEBHOOK=

SENTRY_DSN=
11 changes: 6 additions & 5 deletions .github/workflows/deploy.yml
Original file line number Diff line number Diff line change
Expand Up @@ -10,19 +10,20 @@ on:
jobs:
DePloY:
strategy:
max-parallel: 2
matrix:
host: [1.premid.app]
host: [94.130.110.12,94.130.228.224,88.198.92.64,88.198.144.181,78.47.55.214]
runs-on: "ubuntu-latest"
steps:
- name: Deploying...
uses: appleboy/ssh-action@master
with:
host: ${{ matrix.host }}
username: ${{ secrets.SSHUSERNAME }}
password: ${{ secrets.SSHPASSWORD }}
username: ${{ secrets.SSH_USERNAME }}
key: ${{ secrets.SSH_KEY }}
script: |
cd /home/PreMiD/API
cd /home/API
git reset --hard
git pull
yarn run init
pm2 reload /home/PreMiD/ecosystem.config.js --only API
pm2 reload API
2 changes: 2 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -2,3 +2,5 @@ node_modules
dist
.env
caches
*.crt
*.key
33 changes: 15 additions & 18 deletions package.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "pmd-api",
"version": "3.0.0",
"version": "3.0.4",
"main": "index.js",
"repository": "https://github.com/PreMiD/API",
"author": "Timeraa",
Expand All @@ -11,28 +11,25 @@
"dev": "devScript"
},
"dependencies": {
"axios": "0.20.0",
"braintree": "3.0.0",
"discord.js": "12.3.1",
"@sentry/node": "^6.2.2",
"axios": "0.21.1",
"discord.js": "12.5.1",
"fast-node-cache": "1.2.1",
"fastify": "3.4.1",
"fastify-gql": "5.6.0",
"fastify-helmet": "5.0.1",
"fs-extra": "9.0.1",
"graphql": "15.3.0",
"middie": "5.1.0",
"mongodb": "3.6.1",
"nodemailer": "^6.4.13",
"fastify": "3.14.0",
"graphql": "15.5.0",
"mercurius": "^7.2.0",
"middie": "5.2.0",
"mongodb": "^3.6.3",
"source-map-support": "^0.5.19"
},
"devDependencies": {
"@types/fs-extra": "^9.0.1",
"@types/mongodb": "^3.5.26",
"@types/node": "^14.6.3",
"@types/connect": "^3.4.34",
"@types/mongodb": "^3.6.10",
"@types/node": "^14.14.35",
"dotenv": "^8.2.0",
"rimraf": "^3.0.2",
"ts-devscript": "^1.0.8",
"typescript": "^4.0.2",
"yarn": "^1.22.5"
"ts-devscript": "^3.0.3",
"typescript": "^4.2.3",
"yarn": "^1.22.10"
}
}
4 changes: 4 additions & 0 deletions src/endpoints.json
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,10 @@
"path": "/ping",
"handler": "ping"
},
{
"path": "/crowdin",
"handler": "crowdin"
},
{
"path": ["/app/update", "/app/update/:bit", "/app/update/*"],
"handler": "appUpdate"
Expand Down
94 changes: 94 additions & 0 deletions src/endpoints/default/crowdin.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,94 @@
import axios from "axios";
import { RouteHandlerMethod } from "fastify";
import { RouteGenericInterface } from "fastify/types/route";
import { IncomingMessage, Server, ServerResponse } from "http";

import { pmdDB } from "../../db/client";

const base = axios.create({
baseURL: "https://accounts.crowdin.com/"
});

const handler: RouteHandlerMethod<
Server,
IncomingMessage,
ServerResponse,
RouteGenericInterface,
unknown
> = async (req, res) => {
const hostname =
process.env.NODE_ENV === "production" ? "premid.app" : "localhost:3000",
query = req.query as any;

if (query?.error === "access_denied") {
await pmdDB.collection("crowdin").findOneAndDelete({ code: query.state });
return res.redirect(
encodeURI(
`//${hostname}/crowdin?success=false&error=Authorization canceled.`
)
);
}

if (!query?.code || !query?.state)
return res.redirect(
encodeURI(
`//${
process.env.NODE_ENV === "production"
? "premid.app"
: "localhost:3000"
}/crowdin?success=false&error=No code or state supplied.`
)
);

const codeValid = await pmdDB
.collection("crowdin")
.findOne({ code: query.state });

if (!codeValid)
return res.redirect(
encodeURI(`//${hostname}/crowdin?success=false&error=Invalid code.`)
);

try {
const { token_type, access_token } = (
await base("oauth/token", {
method: "POST",
data: {
grant_type: "authorization_code",
client_id: process.env.CROWDIN_CLIENT_ID,
client_secret: process.env.CROWDIN_CLIENT_SECRET,
redirect_uri: `http${
process.env.NODE_ENV === "production"
? "s://api.premid.app"
: "://localhost:3001"
}/crowdin`,
code: query.code
}
})
).data,
user = (
await axios("https://api.crowdin.com/api/v2/user", {
headers: { Authorization: `${token_type} ${access_token}` }
})
).data.data;

await pmdDB
.collection("crowdin")
.findOneAndUpdate(
{ code: query.state },
{ $set: { user }, $unset: { code: true } }
);
res.redirect(encodeURI(`//${hostname}/crowdin?success=true`));
} catch (err) {
console.log(err);
await pmdDB.collection("crowdin").findOneAndDelete({ code: query.state });

return res.redirect(
encodeURI(
`//${hostname}/crowdin?success=false&error=Crowdin token invalid.`
)
);
}
};

export { handler };
2 changes: 1 addition & 1 deletion src/endpoints/default/ping.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,6 @@ const handler: RouteHandlerMethod<
ServerResponse,
RouteGenericInterface,
unknown
> = async (_req, res) => res.send("OK");
> = async (_req, res) => res.send();

export { handler };
9 changes: 7 additions & 2 deletions src/endpoints/v2/betaUsers.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ import { IncomingMessage, Server, ServerResponse } from "http";
import { pmdDB } from "../../db/client";

//* Define credits collection
const betaUsers = pmdDB.collection("betaUsers");
let betaUsers = pmdDB.collection("betaUsers").countDocuments();

const handler: RouteHandlerMethod<
Server,
Expand All @@ -13,8 +13,13 @@ const handler: RouteHandlerMethod<
RouteGenericInterface,
unknown
> = async (req, res) => {
res.send({ betaUsers: await betaUsers.countDocuments() });
res.send({ betaUsers: await betaUsers });
};

setInterval(
() => (betaUsers = pmdDB.collection("betaUsers").countDocuments()),
5 * 60 * 1000
);

//* Export handler
export { handler };
3 changes: 1 addition & 2 deletions src/endpoints/v2/credits.ts
Original file line number Diff line number Diff line change
Expand Up @@ -14,8 +14,7 @@ const handler: RouteHandlerMethod<
if (!req.params["userId"]) {
//* Send all users
//* return
res.send(cache.get("credits"));
return;
return res.send(cache.get("credits"));
}

//* find user
Expand Down
8 changes: 6 additions & 2 deletions src/endpoints/v2/downloads.ts
Original file line number Diff line number Diff line change
Expand Up @@ -24,8 +24,12 @@ const handler: RouteHandlerMethod<

getDiscordUser(req.params["token"])
.then(async dUser => {
let alphaUser = await alphaUsers.findOne({ userId: dUser.id });
let betaUser = await betaUsers.findOne({ userId: dUser.id });
const results = Promise.all([
await alphaUsers.findOne({ userId: dUser.id }),
await betaUsers.findOne({ userId: dUser.id })
]);
let alphaUser = results[0];
let betaUser = results[1];

let d = await downloads.findOne(
{ item: req.params["item"] },
Expand Down
23 changes: 14 additions & 9 deletions src/endpoints/v2/presenceUsage.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import { RouteGenericInterface, RouteHandlerMethod } from "fastify/types/route";
import { IncomingMessage, Server, ServerResponse } from "http";
import { RouteGenericInterface, RouteHandlerMethod } from "fastify/types/route";

import { cache } from "../../index";

Expand All @@ -18,17 +18,22 @@ const handler: RouteHandlerMethod<
> = async (_req, res) => res.send(science);

export function prepareUsage(science) {
let ranking = {};
let ranking = {},
ranks = [];
const times = science.map(s => s.presences).length / 65536;

[].concat
.apply(
for (let i = 1; i < times + 1; i++) {
const rankss = [].concat.apply(
[],
science.map(s => s.presences).slice((i - 1) * 65536, i * 65536)
);

ranks = ranks.concat(rankss);
}

science.map(s => s.presences)
)
.map(function (x: string) {
ranking[x] = (ranking[x] || 0) + 1;
});
for (let i = 0; i < ranks.length; i++) {
ranking[ranks[i]] = (ranking[ranks[i]] || 0) + 1;
}

return ranking;
}
Expand Down
35 changes: 22 additions & 13 deletions src/endpoints/v2/presences.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,8 @@ import { IncomingMessage, Server, ServerResponse } from "http";

import { cache } from "../../index";

let prs = preparePresences(cache.get("presences"));
let presenceInfos = [],
prs = preparePresences(cache.get("presences"));

cache.on("update", (_, data) => (prs = preparePresences(data)), {
only: "presences"
Expand All @@ -22,15 +23,7 @@ const handler: RouteHandlerMethod<
if (!req.params["presence"])
//* send all presences
//* return
return await res.send(
presences.map(p => {
return {
name: p.name,
url: p.url,
metadata: p.metadata
};
})
);
return await res.send(presenceInfos);

//* If presence "name" === versions
if (req.params["presence"] === "versions")
Expand Down Expand Up @@ -105,14 +98,30 @@ const handler: RouteHandlerMethod<
};

function preparePresences(presences) {
return presences.map(presence => {
if (presence.metadata.logo.includes("imgur.com"))
const prs = presences.map(presence => {
if (
presence.metadata.logo.includes("imgur.com") &&
!presence.metadata.logo.includes("duckduckgo.com")
)
presence.metadata.logo = `https://proxy.duckduckgo.com/iu/?u=${presence.metadata.logo}`;
if (presence.metadata.thumbnail.includes("imgur.com"))
if (
presence.metadata.thumbnail.includes("imgur.com") &&
!presence.metadata.thumbnail.includes("duckduckgo.com")
)
presence.metadata.thumbnail = `https://proxy.duckduckgo.com/iu/?u=${presence.metadata.thumbnail}`;

return presence;
});

presenceInfos = prs.map(p => {
return {
name: p.name,
url: p.url,
metadata: p.metadata
};
});

return prs;
}

//* Export handler
Expand Down
2 changes: 0 additions & 2 deletions src/endpoints/v2/science.ts
Original file line number Diff line number Diff line change
Expand Up @@ -18,8 +18,6 @@ setInterval(() => {

if (scienceToUpdate.length === 0) return;

console.log(scienceToUpdate.length, scienceUpdateQueue.length);

science.bulkWrite(
scienceToUpdate.map(s => {
return {
Expand Down

0 comments on commit 9de8fa5

Please sign in to comment.