rhythia-api 89.0.0 → 90.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,101 +1,106 @@
1
- import { NextResponse } from "next/server";
2
- import z from "zod";
3
- import { protectedApi } from "../utils/requestUtils";
4
- import { supabase } from "../utils/supabase";
5
-
6
- export const Schema = {
7
- input: z.strictObject({
8
- session: z.string(),
9
- data: z.strictObject({
10
- token: z.string(),
11
- relayHwid: z.string(),
12
- songId: z.string(),
13
- noteResults: z.record(z.boolean()),
14
- triggers: z.array(z.array(z.number())),
15
- mapHash: z.string(),
16
- mapTitle: z.string(),
17
- mapDifficulty: z.number(),
18
- mapNoteCount: z.number(),
19
- mapLength: z.number(),
20
- }),
21
- }),
22
- output: z.object({
23
- error: z.string().optional(),
24
- }),
25
- };
26
-
27
- export async function POST(request: Request): Promise<NextResponse> {
28
- return protectedApi({
29
- request,
30
- schema: Schema,
31
- authorization: () => {},
32
- activity: handler,
33
- });
34
- }
35
-
36
- export async function handler({
37
- data,
38
- session,
39
- }: (typeof Schema)["input"]["_type"]): Promise<
40
- NextResponse<(typeof Schema)["output"]["_type"]>
41
- > {
42
- const user = (await supabase.auth.getUser(session)).data.user!;
43
-
44
- let { data: userData, error: userError } = await supabase
45
- .from("profiles")
46
- .select("*")
47
- .eq("uid", user.id)
48
- .single();
49
-
50
- if (!userData)
51
- return NextResponse.json(
52
- {
53
- error: "User doesn't exist",
54
- },
55
- { status: 500 }
56
- );
57
-
58
- let { data: beatmaps, error } = await supabase
59
- .from("beatmaps")
60
- .select("playcount")
61
- .eq("beatmapHash", data.mapHash)
62
- .single();
63
-
64
- let newPlaycount = 1;
65
-
66
- if (beatmaps) {
67
- newPlaycount = (beatmaps.playcount || 1) + 1;
68
- }
69
-
70
- const p1 = supabase.from("beatmaps").upsert({
71
- beatmapHash: data.mapHash,
72
- title: data.mapTitle,
73
- playcount: newPlaycount,
74
- difficulty: data.mapDifficulty,
75
- noteCount: data.mapNoteCount,
76
- length: data.mapLength,
77
- });
78
-
79
- const p2 = supabase.from("scores").upsert({
80
- beatmapHash: data.mapHash,
81
- noteResults: data.noteResults,
82
- replayHwid: data.relayHwid,
83
- songId: data.songId,
84
- triggers: data.triggers,
85
- userId: userData[0].id,
86
- passed: data.mapNoteCount == Object.keys(data.noteResults).length,
87
- misses: Object.values(data.noteResults).filter((e) => !e).length,
88
- });
89
-
90
- const p3 = supabase.from("profiles").upsert({
91
- id: userData[0].id,
92
- play_count: (userData[0].play_count || 0) + 1,
93
- squares_hit:
94
- (userData[0].squares_hit || 0) +
95
- Object.values(data.noteResults).filter((e) => e).length,
96
- });
97
-
98
- await Promise.all([p1, p2, p3]);
99
-
100
- return NextResponse.json({});
101
- }
1
+ import { NextResponse } from "next/server";
2
+ import z from "zod";
3
+ import { protectedApi, validUser } from "../utils/requestUtils";
4
+ import { supabase } from "../utils/supabase";
5
+
6
+ export const Schema = {
7
+ input: z.strictObject({
8
+ session: z.string(),
9
+ data: z.strictObject({
10
+ token: z.string(),
11
+ relayHwid: z.string(),
12
+ songId: z.string(),
13
+ noteResults: z.record(z.boolean()),
14
+ triggers: z.array(z.array(z.number())),
15
+ mapHash: z.string(),
16
+ mapTitle: z.string(),
17
+ mapDifficulty: z.number(),
18
+ mapNoteCount: z.number(),
19
+ mapLength: z.number(),
20
+ }),
21
+ }),
22
+ output: z.object({
23
+ error: z.string().optional(),
24
+ }),
25
+ };
26
+
27
+ export async function POST(request: Request): Promise<NextResponse> {
28
+ return protectedApi({
29
+ request,
30
+ schema: Schema,
31
+ authorization: validUser,
32
+ activity: handler,
33
+ });
34
+ }
35
+
36
+ export async function handler({
37
+ data,
38
+ session,
39
+ }: (typeof Schema)["input"]["_type"]): Promise<
40
+ NextResponse<(typeof Schema)["output"]["_type"]>
41
+ > {
42
+ const user = (await supabase.auth.getUser(session)).data.user!;
43
+
44
+ let { data: userData, error: userError } = await supabase
45
+ .from("profiles")
46
+ .select("*")
47
+ .eq("uid", user.id)
48
+ .single();
49
+
50
+ if (!userData)
51
+ return NextResponse.json(
52
+ {
53
+ error: "User doesn't exist",
54
+ },
55
+ { status: 500 }
56
+ );
57
+
58
+ console.log(userData);
59
+ let { data: beatmaps, error } = await supabase
60
+ .from("beatmaps")
61
+ .select("playcount")
62
+ .eq("beatmapHash", data.mapHash)
63
+ .single();
64
+
65
+ let newPlaycount = 1;
66
+
67
+ if (beatmaps) {
68
+ newPlaycount = (beatmaps.playcount || 1) + 1;
69
+ }
70
+
71
+ console.log(newPlaycount);
72
+ const p1 = await supabase.from("beatmaps").upsert({
73
+ beatmapHash: data.mapHash,
74
+ title: data.mapTitle,
75
+ playcount: newPlaycount,
76
+ difficulty: data.mapDifficulty,
77
+ noteCount: data.mapNoteCount,
78
+ length: data.mapLength,
79
+ });
80
+
81
+ console.log("p1");
82
+ const p2 = await supabase.from("scores").upsert({
83
+ beatmapHash: data.mapHash,
84
+ noteResults: data.noteResults,
85
+ replayHwid: data.relayHwid,
86
+ songId: data.songId,
87
+ triggers: data.triggers,
88
+ userId: userData.id,
89
+ passed: data.mapNoteCount == Object.keys(data.noteResults).length,
90
+ misses: Object.values(data.noteResults).filter((e) => !e).length,
91
+ });
92
+ console.log("p2");
93
+
94
+ const p3 = await supabase.from("profiles").upsert({
95
+ id: userData.id,
96
+ play_count: (userData.play_count || 0) + 1,
97
+ squares_hit:
98
+ (userData.squares_hit || 0) +
99
+ Object.values(data.noteResults).filter((e) => e).length,
100
+ });
101
+ console.log("p3");
102
+
103
+ // await Promise.all([p1, p2, p3]);
104
+
105
+ return NextResponse.json({});
106
+ }
package/handleApi.ts CHANGED
@@ -1,19 +1,19 @@
1
- import { z } from "zod";
2
- let env = "development";
3
- export function setEnvironment(
4
- stage: "development" | "testing" | "production"
5
- ) {
6
- env = stage;
7
- }
8
- export function handleApi<
9
- T extends { url: string; input: z.ZodObject<any>; output: z.ZodObject<any> }
10
- >(apiSchema: T) {
11
- return async (input: T["input"]["_type"]): Promise<T["output"]["_type"]> => {
12
- const response = await fetch(`https://${env}.rhythia.com${apiSchema.url}`, {
13
- method: "POST",
14
- body: JSON.stringify(input),
15
- });
16
- const output = await response.json();
17
- return output;
18
- };
19
- }
1
+ import { z } from "zod";
2
+ let env = "development";
3
+ export function setEnvironment(
4
+ stage: "development" | "testing" | "production"
5
+ ) {
6
+ env = stage;
7
+ }
8
+ export function handleApi<
9
+ T extends { url: string; input: z.ZodObject<any>; output: z.ZodObject<any> }
10
+ >(apiSchema: T) {
11
+ return async (input: T["input"]["_type"]): Promise<T["output"]["_type"]> => {
12
+ const response = await fetch(`https://${env}.rhythia.com${apiSchema.url}`, {
13
+ method: "POST",
14
+ body: JSON.stringify(input),
15
+ });
16
+ const output = await response.json();
17
+ return output;
18
+ };
19
+ }
package/index.html CHANGED
@@ -1,3 +1,3 @@
1
- <html>
2
- <div>Rhythia API</div>
1
+ <html>
2
+ <div>Rhythia API</div>
3
3
  </html>
package/index.ts CHANGED
@@ -5,15 +5,20 @@ import { Schema as EditProfile } from "./api/editProfile"
5
5
  export { Schema as SchemaEditProfile } from "./api/editProfile"
6
6
  export const editProfile = handleApi({url:"/api/editProfile",...EditProfile})
7
7
 
8
+ // ./api/getLeaderboard.ts API
9
+ import { Schema as GetLeaderboard } from "./api/getLeaderboard"
10
+ export { Schema as SchemaGetLeaderboard } from "./api/getLeaderboard"
11
+ export const getLeaderboard = handleApi({url:"/api/getLeaderboard",...GetLeaderboard})
12
+
8
13
  // ./api/getProfile.ts API
9
14
  import { Schema as GetProfile } from "./api/getProfile"
10
15
  export { Schema as SchemaGetProfile } from "./api/getProfile"
11
16
  export const getProfile = handleApi({url:"/api/getProfile",...GetProfile})
12
17
 
13
- // ./api/getLeaderboard.ts API
14
- import { Schema as GetLeaderboard } from "./api/getLeaderboard"
15
- export { Schema as SchemaGetLeaderboard } from "./api/getLeaderboard"
16
- export const getLeaderboard = handleApi({url:"/api/getLeaderboard",...GetLeaderboard})
18
+ // ./api/getPublicStats.ts API
19
+ import { Schema as GetPublicStats } from "./api/getPublicStats"
20
+ export { Schema as SchemaGetPublicStats } from "./api/getPublicStats"
21
+ export const getPublicStats = handleApi({url:"/api/getPublicStats",...GetPublicStats})
17
22
 
18
23
  // ./api/searchUsers.ts API
19
24
  import { Schema as SearchUsers } from "./api/searchUsers"
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "rhythia-api",
3
- "version": "89.0.0",
3
+ "version": "90.0.0",
4
4
  "main": "index.ts",
5
5
  "scripts": {
6
6
  "update": "bun ./scripts/update.ts",
@@ -1,76 +1,76 @@
1
- import fs from "fs";
2
- import * as git from "isomorphic-git";
3
- import http from "isomorphic-git/http/node";
4
- import path from "path";
5
-
6
- // Set up the repository URL
7
- const repoUrl = `https://${process.env.GIT_KEY}@github.com/cunev/rhythia-api.git`;
8
-
9
- const sourceBranch = process.env.SOURCE_BRANCH!;
10
- const targetBranch = process.env.TARGET_BRANCH!;
11
-
12
- async function cloneBranch() {
13
- const dir = path.join("/tmp", "repo");
14
-
15
- try {
16
- // Ensure the directory is clean before cloning
17
- if (fs.existsSync(dir)) {
18
- fs.rmdirSync(dir, { recursive: true });
19
- console.log(`Deleted existing directory: ${dir}`);
20
- }
21
-
22
- // Clone the repository into a temporary directory
23
- await git.clone({
24
- fs,
25
- http,
26
- dir,
27
- url: repoUrl,
28
- ref: sourceBranch,
29
- singleBranch: true,
30
- depth: 1,
31
- });
32
- console.log(`Cloned ${sourceBranch} branch from remote repository.`);
33
-
34
- // Check out the source branch
35
- await git.checkout({ fs, dir, ref: sourceBranch });
36
- console.log(`Checked out to branch: ${sourceBranch}`);
37
-
38
- // Pull the latest changes from the source branch
39
- await git.pull({
40
- fs,
41
- http,
42
- dir,
43
- ref: sourceBranch,
44
- singleBranch: true,
45
- author: {
46
- name: process.env.GIT_USER,
47
- email: "you@example.com", // Replace with the actual email
48
- },
49
- });
50
- console.log(`Pulled latest changes from branch: ${sourceBranch}`);
51
-
52
- // Create and checkout the target branch from the source branch
53
- await git.branch({ fs, dir, ref: targetBranch });
54
- await git.checkout({ fs, dir, ref: targetBranch });
55
- console.log(`Created and checked out to branch: ${targetBranch}`);
56
-
57
- // Push the new branch to the remote repository
58
- await git.push({
59
- fs,
60
- http,
61
- dir,
62
- remote: "origin",
63
- ref: targetBranch,
64
- force: true,
65
- onAuth: () => ({
66
- username: process.env.GIT_KEY, // GitHub token or password
67
- password: "",
68
- }),
69
- });
70
- console.log(`Pushed new branch to remote: ${targetBranch}`);
71
- } catch (error) {
72
- console.error("Error performing Git operations:", error.message);
73
- }
74
- }
75
-
76
- cloneBranch();
1
+ import fs from "fs";
2
+ import * as git from "isomorphic-git";
3
+ import http from "isomorphic-git/http/node";
4
+ import path from "path";
5
+
6
+ // Set up the repository URL
7
+ const repoUrl = `https://${process.env.GIT_KEY}@github.com/cunev/rhythia-api.git`;
8
+
9
+ const sourceBranch = process.env.SOURCE_BRANCH!;
10
+ const targetBranch = process.env.TARGET_BRANCH!;
11
+
12
+ async function cloneBranch() {
13
+ const dir = path.join("/tmp", "repo");
14
+
15
+ try {
16
+ // Ensure the directory is clean before cloning
17
+ if (fs.existsSync(dir)) {
18
+ fs.rmdirSync(dir, { recursive: true });
19
+ console.log(`Deleted existing directory: ${dir}`);
20
+ }
21
+
22
+ // Clone the repository into a temporary directory
23
+ await git.clone({
24
+ fs,
25
+ http,
26
+ dir,
27
+ url: repoUrl,
28
+ ref: sourceBranch,
29
+ singleBranch: true,
30
+ depth: 1,
31
+ });
32
+ console.log(`Cloned ${sourceBranch} branch from remote repository.`);
33
+
34
+ // Check out the source branch
35
+ await git.checkout({ fs, dir, ref: sourceBranch });
36
+ console.log(`Checked out to branch: ${sourceBranch}`);
37
+
38
+ // Pull the latest changes from the source branch
39
+ await git.pull({
40
+ fs,
41
+ http,
42
+ dir,
43
+ ref: sourceBranch,
44
+ singleBranch: true,
45
+ author: {
46
+ name: process.env.GIT_USER,
47
+ email: "you@example.com", // Replace with the actual email
48
+ },
49
+ });
50
+ console.log(`Pulled latest changes from branch: ${sourceBranch}`);
51
+
52
+ // Create and checkout the target branch from the source branch
53
+ await git.branch({ fs, dir, ref: targetBranch });
54
+ await git.checkout({ fs, dir, ref: targetBranch });
55
+ console.log(`Created and checked out to branch: ${targetBranch}`);
56
+
57
+ // Push the new branch to the remote repository
58
+ await git.push({
59
+ fs,
60
+ http,
61
+ dir,
62
+ remote: "origin",
63
+ ref: targetBranch,
64
+ force: true,
65
+ onAuth: () => ({
66
+ username: process.env.GIT_KEY, // GitHub token or password
67
+ password: "",
68
+ }),
69
+ });
70
+ console.log(`Pushed new branch to remote: ${targetBranch}`);
71
+ } catch (error) {
72
+ console.error("Error performing Git operations:", error.message);
73
+ }
74
+ }
75
+
76
+ cloneBranch();
package/scripts/update.ts CHANGED
@@ -1,49 +1,49 @@
1
- import { $ } from "bun";
2
- import { readdirSync, readFileSync, writeFileSync } from "fs";
3
- import { lowerFirst, upperFirst } from "lodash";
4
- import path from "path";
5
- const packageJson = JSON.parse(readFileSync("./package.json", "utf-8"));
6
-
7
- const versions = packageJson.version.split(".");
8
- versions[0] = Number(versions[0]) + 1;
9
-
10
- packageJson.version = versions.join(".");
11
-
12
- writeFileSync("./package.json", JSON.stringify(packageJson, null, 2));
13
-
14
- const apis = readdirSync("./api");
15
-
16
- const exports: string[] = [];
17
- exports.push(`import { handleApi } from "./handleApi"`);
18
-
19
- for (const api of apis) {
20
- if (
21
- !readFileSync(path.join("./api", api), "utf-8").includes(
22
- "export const Schema"
23
- )
24
- ) {
25
- continue;
26
- }
27
- exports.push(`\n// ./api/${api} API`);
28
-
29
- const apiName = path.parse(api).name;
30
- exports.push(
31
- `import { Schema as ${upperFirst(apiName)} } from "./api/${apiName}"`
32
- );
33
- exports.push(
34
- `export { Schema as Schema${upperFirst(apiName)} } from "./api/${apiName}"`
35
- );
36
-
37
- exports.push(
38
- `export const ${lowerFirst(
39
- apiName
40
- )} = handleApi({url:"/api/${apiName}",...${upperFirst(apiName)}})`
41
- );
42
- }
43
- exports.push(`export { handleApi } from "./handleApi"`);
44
-
45
- writeFileSync("./index.ts", exports.join("\n"));
46
-
47
- // const conf = readFileSync("./.cred", "utf-8");
48
- // await $`npm logout`.nothrow();
49
- await $`yarn publish`;
1
+ import { $ } from "bun";
2
+ import { readdirSync, readFileSync, writeFileSync } from "fs";
3
+ import { lowerFirst, upperFirst } from "lodash";
4
+ import path from "path";
5
+ const packageJson = JSON.parse(readFileSync("./package.json", "utf-8"));
6
+
7
+ const versions = packageJson.version.split(".");
8
+ versions[0] = Number(versions[0]) + 1;
9
+
10
+ packageJson.version = versions.join(".");
11
+
12
+ writeFileSync("./package.json", JSON.stringify(packageJson, null, 2));
13
+
14
+ const apis = readdirSync("./api");
15
+
16
+ const exports: string[] = [];
17
+ exports.push(`import { handleApi } from "./handleApi"`);
18
+
19
+ for (const api of apis) {
20
+ if (
21
+ !readFileSync(path.join("./api", api), "utf-8").includes(
22
+ "export const Schema"
23
+ )
24
+ ) {
25
+ continue;
26
+ }
27
+ exports.push(`\n// ./api/${api} API`);
28
+
29
+ const apiName = path.parse(api).name;
30
+ exports.push(
31
+ `import { Schema as ${upperFirst(apiName)} } from "./api/${apiName}"`
32
+ );
33
+ exports.push(
34
+ `export { Schema as Schema${upperFirst(apiName)} } from "./api/${apiName}"`
35
+ );
36
+
37
+ exports.push(
38
+ `export const ${lowerFirst(
39
+ apiName
40
+ )} = handleApi({url:"/api/${apiName}",...${upperFirst(apiName)}})`
41
+ );
42
+ }
43
+ exports.push(`export { handleApi } from "./handleApi"`);
44
+
45
+ writeFileSync("./index.ts", exports.join("\n"));
46
+
47
+ // const conf = readFileSync("./.cred", "utf-8");
48
+ // await $`npm logout`.nothrow();
49
+ await $`yarn publish`;
@@ -1,55 +1,55 @@
1
- import { NextResponse } from "next/server";
2
- import { supabase } from "./supabase";
3
- import { ZodObject } from "zod";
4
-
5
- interface Props<
6
- K = (...args: any[]) => Promise<NextResponse<any>>,
7
- T = ZodObject<any>
8
- > {
9
- request: Request;
10
- schema: { input: T; output: T };
11
- authorization?: Function;
12
- activity: K;
13
- }
14
-
15
- export async function protectedApi({
16
- request,
17
- schema,
18
- authorization,
19
- activity,
20
- }: Props) {
21
- try {
22
- const toParse = await request.json();
23
- const data = schema.input.parse(toParse);
24
- if (authorization) {
25
- const authorizationResponse = await authorization(data);
26
- if (authorizationResponse) {
27
- return authorizationResponse;
28
- }
29
- }
30
- return await activity(data, request);
31
- } catch (error) {
32
- return NextResponse.json({ error: error.toString() }, { status: 400 });
33
- }
34
- }
35
-
36
- export async function validUser(data) {
37
- if (!data.session) {
38
- return NextResponse.json(
39
- {
40
- error: "Session is missing",
41
- },
42
- { status: 501 }
43
- );
44
- }
45
-
46
- const user = await supabase.auth.getUser(data.session);
47
- if (user.error || !user.data.user) {
48
- return NextResponse.json(
49
- {
50
- error: "Invalid user session",
51
- },
52
- { status: 400 }
53
- );
54
- }
55
- }
1
+ import { NextResponse } from "next/server";
2
+ import { supabase } from "./supabase";
3
+ import { ZodObject } from "zod";
4
+
5
+ interface Props<
6
+ K = (...args: any[]) => Promise<NextResponse<any>>,
7
+ T = ZodObject<any>
8
+ > {
9
+ request: Request;
10
+ schema: { input: T; output: T };
11
+ authorization?: Function;
12
+ activity: K;
13
+ }
14
+
15
+ export async function protectedApi({
16
+ request,
17
+ schema,
18
+ authorization,
19
+ activity,
20
+ }: Props) {
21
+ try {
22
+ const toParse = await request.json();
23
+ const data = schema.input.parse(toParse);
24
+ if (authorization) {
25
+ const authorizationResponse = await authorization(data);
26
+ if (authorizationResponse) {
27
+ return authorizationResponse;
28
+ }
29
+ }
30
+ return await activity(data, request);
31
+ } catch (error) {
32
+ return NextResponse.json({ error: error.toString() }, { status: 400 });
33
+ }
34
+ }
35
+
36
+ export async function validUser(data) {
37
+ if (!data.session) {
38
+ return NextResponse.json(
39
+ {
40
+ error: "Session is missing",
41
+ },
42
+ { status: 501 }
43
+ );
44
+ }
45
+
46
+ const user = await supabase.auth.getUser(data.session);
47
+ if (user.error || !user.data.user) {
48
+ return NextResponse.json(
49
+ {
50
+ error: "Invalid user session",
51
+ },
52
+ { status: 400 }
53
+ );
54
+ }
55
+ }