rhythia-api 83.0.0 → 85.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,92 +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
- noteCount: z.number(),
19
- }),
20
- }),
21
- output: z.object({
22
- error: z.string().optional(),
23
- }),
24
- };
25
-
26
- export async function POST(res: Response): Promise<NextResponse> {
27
- return protectedApi({
28
- response: res,
29
- schema: Schema,
30
- authorization: () => {},
31
- activity: handler,
32
- });
33
- }
34
-
35
- export async function handler({
36
- data,
37
- session,
38
- }: (typeof Schema)["input"]["_type"]): Promise<
39
- NextResponse<(typeof Schema)["output"]["_type"]>
40
- > {
41
- const user = (await supabase.auth.getUser(session)).data.user!;
42
-
43
- let { data: userData, error: userError } = await supabase
44
- .from("profiles")
45
- .select("*")
46
- .eq("uid", user.id);
47
-
48
- if (!userData?.length)
49
- return NextResponse.json(
50
- {
51
- error: "User doesn't exist",
52
- },
53
- { status: 500 }
54
- );
55
-
56
- let { data: beatmaps, error } = await supabase
57
- .from("beatmaps")
58
- .select("*")
59
- .eq("beatmapHash", data.mapHash);
60
-
61
- let newPlaycount = 1;
62
-
63
- if (beatmaps?.length) {
64
- newPlaycount = (beatmaps[0].playcount || 1) + 1;
65
- }
66
-
67
- const upsertData = await supabase
68
- .from("beatmaps")
69
- .upsert({
70
- beatmapHash: data.mapHash,
71
- beatmapTitle: data.mapTitle,
72
- playcount: newPlaycount,
73
- difficulty: data.mapDifficulty,
74
- noteCount: data.noteCount,
75
- })
76
- .select();
77
-
78
- const insertData = await supabase
79
- .from("scores")
80
- .upsert({
81
- beatmapHash: data.mapHash,
82
- noteResults: data.noteResults,
83
- replayHwid: data.relayHwid,
84
- songId: data.songId,
85
- triggers: data.triggers,
86
- userId: userData[0].id,
87
- passed: data.noteCount == Object.keys(data.noteResults).length,
88
- })
89
- .select();
90
-
91
- return NextResponse.json({});
92
- }
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
+
49
+ if (!userData?.length)
50
+ return NextResponse.json(
51
+ {
52
+ error: "User doesn't exist",
53
+ },
54
+ { status: 500 }
55
+ );
56
+
57
+ let { data: beatmaps, error } = await supabase
58
+ .from("beatmaps")
59
+ .select("*")
60
+ .eq("beatmapHash", data.mapHash);
61
+
62
+ let newPlaycount = 1;
63
+
64
+ if (beatmaps?.length) {
65
+ newPlaycount = (beatmaps[0].playcount || 1) + 1;
66
+ }
67
+
68
+ const upsertData = await supabase
69
+ .from("beatmaps")
70
+ .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
+ .select();
79
+
80
+ const insertData = await supabase
81
+ .from("scores")
82
+ .upsert({
83
+ beatmapHash: data.mapHash,
84
+ noteResults: data.noteResults,
85
+ replayHwid: data.relayHwid,
86
+ songId: data.songId,
87
+ triggers: data.triggers,
88
+ userId: userData[0].id,
89
+ passed: data.mapNoteCount == Object.keys(data.noteResults).length,
90
+ misses: Object.values(data.noteResults).filter((e) => !e).length,
91
+ })
92
+ .select();
93
+
94
+ const insertUserData = await supabase
95
+ .from("profiles")
96
+ .upsert({
97
+ id: userData[0].id,
98
+ play_count: (userData[0].play_count || 0) + 1,
99
+ squares_hit:
100
+ (userData[0].squares_hit || 0) +
101
+ Object.values(data.noteResults).filter((e) => e).length,
102
+ })
103
+ .select();
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,16 +5,16 @@ 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
-
13
8
  // ./api/getProfile.ts API
14
9
  import { Schema as GetProfile } from "./api/getProfile"
15
10
  export { Schema as SchemaGetProfile } from "./api/getProfile"
16
11
  export const getProfile = handleApi({url:"/api/getProfile",...GetProfile})
17
12
 
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})
17
+
18
18
  // ./api/searchUsers.ts API
19
19
  import { Schema as SearchUsers } from "./api/searchUsers"
20
20
  export { Schema as SchemaSearchUsers } from "./api/searchUsers"
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "rhythia-api",
3
- "version": "83.0.0",
3
+ "version": "85.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`;
package/types/database.ts CHANGED
@@ -12,27 +12,30 @@ export type Database = {
12
12
  beatmaps: {
13
13
  Row: {
14
14
  beatmapHash: string
15
- beatmapTitle: string | null
16
15
  created_at: string
17
16
  difficulty: number | null
17
+ length: number | null
18
18
  noteCount: number | null
19
19
  playcount: number | null
20
+ title: string | null
20
21
  }
21
22
  Insert: {
22
23
  beatmapHash: string
23
- beatmapTitle?: string | null
24
24
  created_at?: string
25
25
  difficulty?: number | null
26
+ length?: number | null
26
27
  noteCount?: number | null
27
28
  playcount?: number | null
29
+ title?: string | null
28
30
  }
29
31
  Update: {
30
32
  beatmapHash?: string
31
- beatmapTitle?: string | null
32
33
  created_at?: string
33
34
  difficulty?: number | null
35
+ length?: number | null
34
36
  noteCount?: number | null
35
37
  playcount?: number | null
38
+ title?: string | null
36
39
  }
37
40
  Relationships: []
38
41
  }
@@ -97,6 +100,7 @@ export type Database = {
97
100
  beatmapHash: string | null
98
101
  created_at: string
99
102
  id: number
103
+ misses: number | null
100
104
  noteResults: Json | null
101
105
  passed: boolean | null
102
106
  playedAt: number | null
@@ -109,6 +113,7 @@ export type Database = {
109
113
  beatmapHash?: string | null
110
114
  created_at?: string
111
115
  id?: number
116
+ misses?: number | null
112
117
  noteResults?: Json | null
113
118
  passed?: boolean | null
114
119
  playedAt?: number | null
@@ -121,6 +126,7 @@ export type Database = {
121
126
  beatmapHash?: string | null
122
127
  created_at?: string
123
128
  id?: number
129
+ misses?: number | null
124
130
  noteResults?: Json | null
125
131
  passed?: boolean | null
126
132
  playedAt?: number | null