rhythia-api 92.0.0 → 93.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.
@@ -0,0 +1,84 @@
1
+ import { geolocation } from "@vercel/edge";
2
+ import { NextResponse } from "next/server";
3
+ import z from "zod";
4
+ import { Database } from "../types/database";
5
+ import { protectedApi, validUser } from "../utils/requestUtils";
6
+ import { supabase } from "../utils/supabase";
7
+
8
+ export const Schema = {
9
+ input: z.strictObject({
10
+ id: z.number(),
11
+ }),
12
+ output: z.object({
13
+ error: z.string().optional(),
14
+ lastDay: z
15
+ .array(
16
+ z.object({
17
+ awarded_sp: z.number().nullable(),
18
+ beatmapHash: z.string().nullable(),
19
+ created_at: z.string(),
20
+ id: z.number(),
21
+ misses: z.number().nullable(),
22
+ passed: z.boolean().nullable(),
23
+ rank: z.string().nullable(),
24
+ songId: z.string().nullable(),
25
+ userId: z.number().nullable(),
26
+ })
27
+ )
28
+ .optional(),
29
+ top: z.array(z.object({})).optional(),
30
+ }),
31
+ };
32
+
33
+ export async function POST(request: Request): Promise<NextResponse> {
34
+ return protectedApi({
35
+ request,
36
+ schema: Schema,
37
+ authorization: validUser,
38
+ activity: handler,
39
+ });
40
+ }
41
+
42
+ export async function handler(
43
+ data: (typeof Schema)["input"]["_type"],
44
+ req: Request
45
+ ): Promise<NextResponse<(typeof Schema)["output"]["_type"]>> {
46
+ let { data: scores1, error: errorlast } = await supabase
47
+ .from("scores")
48
+ .select("*")
49
+ .eq("userId", data.id)
50
+ .order("created_at", { ascending: false })
51
+ .limit(10);
52
+
53
+ let { data: scores2, error: errorsp } = await supabase
54
+ .from("scores")
55
+ .select("*")
56
+ .eq("userId", data.id)
57
+ .order("awarded_sp", { ascending: false })
58
+ .limit(10);
59
+
60
+ return NextResponse.json({
61
+ lastDay: scores1?.map((s) => ({
62
+ created_at: s.created_at,
63
+ id: s.id,
64
+ passed: s.passed,
65
+ userId: s.userId,
66
+ awarded_sp: s.awarded_sp,
67
+ beatmapHash: s.beatmapHash,
68
+ misses: s.misses,
69
+ rank: s.rank,
70
+ songId: s.songId,
71
+ })),
72
+ top: scores2?.map((s) => ({
73
+ created_at: s.created_at,
74
+ id: s.id,
75
+ passed: s.passed,
76
+ userId: s.userId,
77
+ awarded_sp: s.awarded_sp,
78
+ beatmapHash: s.beatmapHash,
79
+ misses: s.misses,
80
+ rank: s.rank,
81
+ songId: s.songId,
82
+ })),
83
+ });
84
+ }
@@ -1,41 +1,41 @@
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
- text: z.string(),
9
- }),
10
- output: z.object({
11
- error: z.string().optional(),
12
- results: z
13
- .array(
14
- z.object({
15
- id: z.number(),
16
- username: z.string().nullable(),
17
- })
18
- )
19
- .optional(),
20
- }),
21
- };
22
-
23
- export async function POST(request: Request) {
24
- return protectedApi({
25
- request,
26
- schema: Schema,
27
- authorization: () => {},
28
- activity: handler,
29
- });
30
- }
31
-
32
- export async function handler(data: (typeof Schema)["input"]["_type"]) {
33
- const { data: searchData, error } = await supabase
34
- .from("profiles")
35
- .select("id,username")
36
- .ilike("username", `%${data.text}%`)
37
- .limit(10);
38
- return NextResponse.json({
39
- results: searchData || [],
40
- });
41
- }
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
+ text: z.string(),
9
+ }),
10
+ output: z.object({
11
+ error: z.string().optional(),
12
+ results: z
13
+ .array(
14
+ z.object({
15
+ id: z.number(),
16
+ username: z.string().nullable(),
17
+ })
18
+ )
19
+ .optional(),
20
+ }),
21
+ };
22
+
23
+ export async function POST(request: Request) {
24
+ return protectedApi({
25
+ request,
26
+ schema: Schema,
27
+ authorization: () => {},
28
+ activity: handler,
29
+ });
30
+ }
31
+
32
+ export async function handler(data: (typeof Schema)["input"]["_type"]) {
33
+ const { data: searchData, error } = await supabase
34
+ .from("profiles")
35
+ .select("id,username")
36
+ .ilike("username", `%${data.text}%`)
37
+ .limit(10);
38
+ return NextResponse.json({
39
+ results: searchData || [],
40
+ });
41
+ }
@@ -1,106 +1,108 @@
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
- }
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
+ awarded_sp: 0,
92
+ rank: "A",
93
+ });
94
+ console.log("p2");
95
+
96
+ const p3 = await supabase.from("profiles").upsert({
97
+ id: userData.id,
98
+ play_count: (userData.play_count || 0) + 1,
99
+ squares_hit:
100
+ (userData.squares_hit || 0) +
101
+ Object.values(data.noteResults).filter((e) => e).length,
102
+ });
103
+ console.log("p3");
104
+
105
+ // await Promise.all([p1, p2, p3]);
106
+
107
+ return NextResponse.json({});
108
+ }
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
@@ -1,24 +1,29 @@
1
1
  import { handleApi } from "./handleApi"
2
2
 
3
+ // ./api/getPublicStats.ts API
4
+ import { Schema as GetPublicStats } from "./api/getPublicStats"
5
+ export { Schema as SchemaGetPublicStats } from "./api/getPublicStats"
6
+ export const getPublicStats = handleApi({url:"/api/getPublicStats",...GetPublicStats})
7
+
8
+ // ./api/getUserScores.ts API
9
+ import { Schema as GetUserScores } from "./api/getUserScores"
10
+ export { Schema as SchemaGetUserScores } from "./api/getUserScores"
11
+ export const getUserScores = handleApi({url:"/api/getUserScores",...GetUserScores})
12
+
3
13
  // ./api/editProfile.ts API
4
14
  import { Schema as EditProfile } from "./api/editProfile"
5
15
  export { Schema as SchemaEditProfile } from "./api/editProfile"
6
16
  export const editProfile = handleApi({url:"/api/editProfile",...EditProfile})
7
17
 
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
18
  // ./api/getProfile.ts API
14
19
  import { Schema as GetProfile } from "./api/getProfile"
15
20
  export { Schema as SchemaGetProfile } from "./api/getProfile"
16
21
  export const getProfile = handleApi({url:"/api/getProfile",...GetProfile})
17
22
 
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})
23
+ // ./api/getLeaderboard.ts API
24
+ import { Schema as GetLeaderboard } from "./api/getLeaderboard"
25
+ export { Schema as SchemaGetLeaderboard } from "./api/getLeaderboard"
26
+ export const getLeaderboard = handleApi({url:"/api/getLeaderboard",...GetLeaderboard})
22
27
 
23
28
  // ./api/searchUsers.ts API
24
29
  import { Schema as SearchUsers } from "./api/searchUsers"
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "rhythia-api",
3
- "version": "92.0.0",
3
+ "version": "93.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();