rhythia-api 139.0.0 → 142.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.
@@ -18,6 +18,7 @@ export const Schema = {
18
18
  input: z.strictObject({
19
19
  url: z.string(),
20
20
  session: z.string(),
21
+ updateFlag: z.boolean().optional(),
21
22
  }),
22
23
  output: z.strictObject({
23
24
  hash: z.string().optional(),
@@ -36,6 +37,8 @@ export async function POST(request: Request): Promise<NextResponse> {
36
37
 
37
38
  export async function handler({
38
39
  url,
40
+ session,
41
+ updateFlag,
39
42
  }: (typeof Schema)["input"]["_type"]): Promise<
40
43
  NextResponse<(typeof Schema)["output"]["_type"]>
41
44
  > {
@@ -49,6 +52,17 @@ export async function handler({
49
52
  const parsedData = parser.parse();
50
53
  const digested = parsedData.strings.mapID;
51
54
 
55
+ const user = (await supabase.auth.getUser(session)).data.user!;
56
+ let { data: userData, error: userError } = await supabase
57
+ .from("profiles")
58
+ .select("*")
59
+ .eq("uid", user.id)
60
+ .single();
61
+
62
+ if (!userData) {
63
+ return NextResponse.json({ error: "Bad user" });
64
+ }
65
+
52
66
  let { data: beatmapPage, error: errorlast } = await supabase
53
67
  .from("beatmapPages")
54
68
  .select(`*`)
@@ -56,7 +70,11 @@ export async function handler({
56
70
  .single();
57
71
 
58
72
  if (beatmapPage) {
59
- return NextResponse.json({ error: "Already Exists" });
73
+ if (!updateFlag) {
74
+ return NextResponse.json({ error: "Already Exists" });
75
+ } else if (beatmapPage.owner !== userData.id) {
76
+ return NextResponse.json({ error: "Already Exists" });
77
+ }
60
78
  }
61
79
 
62
80
  const imgkey = `beatmap-img-${Date.now()}-${digested}`;
@@ -46,7 +46,7 @@ export async function handler({
46
46
  let { data: beatmapData, error: bmPageError } = await supabase
47
47
  .from("beatmaps")
48
48
  .select("*")
49
- .eq("beatmapHash", pageData.id)
49
+ .eq("beatmapHash", pageData.latestBeatmapHash || "-1-1-1-1")
50
50
  .single();
51
51
 
52
52
  if (!userData) return NextResponse.json({ error: "No user." });
@@ -40,8 +40,7 @@ export async function handler(
40
40
  export async function getLeaderboard(badge: string) {
41
41
  let { data: queryData, error } = await supabase
42
42
  .from("profiles")
43
- .select("flag,id,username,badges")
44
- .neq("ban", "excluded");
43
+ .select("flag,id,username,badges");
45
44
 
46
45
  const users = queryData?.filter((e) =>
47
46
  ((e.badges || []) as string[]).includes(badge)
@@ -11,14 +11,10 @@ export const Schema = {
11
11
  relayHwid: z.string(),
12
12
  songId: z.string(),
13
13
  misses: z.number(),
14
- squareHits: z.number(),
14
+ hits: z.number(),
15
15
  mapHash: z.string(),
16
- mapTitle: z.string(),
17
- mapDifficulty: z.number(),
18
16
  mapNoteCount: z.number(),
19
- mapLength: z.number(),
20
- passed: z.boolean(),
21
- sspp: z.number(),
17
+ speed: z.number(),
22
18
  }),
23
19
  }),
24
20
  output: z.object({
@@ -26,6 +22,19 @@ export const Schema = {
26
22
  }),
27
23
  };
28
24
 
25
+ function easeInExpoDeq(x: number) {
26
+ return x === 0 ? 0 : Math.pow(2, 50 * x - 50);
27
+ }
28
+
29
+ export function calculatePerformancePoints(
30
+ starRating: number,
31
+ accuracy: number
32
+ ) {
33
+ return Math.round(
34
+ Math.pow((starRating * easeInExpoDeq(accuracy) * 100) / 2, 2) / 1000
35
+ );
36
+ }
37
+
29
38
  export async function POST(request: Request): Promise<NextResponse> {
30
39
  return protectedApi({
31
40
  request,
@@ -79,8 +88,6 @@ export async function handler({
79
88
  );
80
89
  }
81
90
 
82
- let newPlaycount = 1;
83
-
84
91
  if (!beatmaps) {
85
92
  return NextResponse.json(
86
93
  {
@@ -90,14 +97,6 @@ export async function handler({
90
97
  );
91
98
  }
92
99
 
93
- if (beatmaps.noteCount !== data.mapNoteCount) {
94
- return NextResponse.json(
95
- {
96
- error: "Wrong map",
97
- },
98
- { status: 500 }
99
- );
100
- }
101
100
  if (beatmaps.noteCount !== data.mapNoteCount) {
102
101
  return NextResponse.json(
103
102
  {
@@ -107,18 +106,22 @@ export async function handler({
107
106
  );
108
107
  }
109
108
 
110
- newPlaycount = (beatmaps.playcount || 1) + 1;
111
109
  await supabase.from("beatmaps").upsert({
112
110
  beatmapHash: data.mapHash,
113
- title: data.mapTitle,
114
- playcount: newPlaycount,
115
- difficulty: data.mapDifficulty,
116
- noteCount: data.mapNoteCount,
117
- length: data.mapLength,
111
+ playcount: (beatmaps.playcount || 1) + 1,
118
112
  });
119
113
 
114
+ const passed =
115
+ data.misses == 0 && data.misses + data.hits == beatmaps.noteCount;
116
+ const accurracy = data.hits / beatmaps.noteCount;
117
+ let awarded_sp = 0;
118
+
119
+ if (beatmaps.starRating) {
120
+ awarded_sp = calculatePerformancePoints(beatmaps.starRating, accurracy);
121
+ }
122
+
120
123
  if (beatmapPages.status == "UNRANKED") {
121
- data.sspp = 0;
124
+ awarded_sp = 0;
122
125
  }
123
126
 
124
127
  console.log("p1");
@@ -127,9 +130,9 @@ export async function handler({
127
130
  replayHwid: data.relayHwid,
128
131
  songId: data.songId,
129
132
  userId: userData.id,
130
- passed: data.passed,
133
+ passed,
131
134
  misses: data.misses,
132
- awarded_sp: Math.round(data.sspp * 100) / 100,
135
+ awarded_sp: Math.round(awarded_sp * 100) / 100,
133
136
  });
134
137
  console.log("p2");
135
138
 
@@ -172,11 +175,9 @@ export async function handler({
172
175
  id: userData.id,
173
176
  play_count: (userData.play_count || 0) + 1,
174
177
  skill_points: Math.round(totalSp * 100) / 100,
175
- squares_hit: (userData.squares_hit || 0) + data.squareHits,
178
+ squares_hit: (userData.squares_hit || 0) + data.hits,
176
179
  });
177
180
  console.log("p3");
178
181
 
179
- // await Promise.all([p1, p2, p3]);
180
-
181
182
  return NextResponse.json({});
182
183
  }
@@ -73,6 +73,7 @@ export async function handler({
73
73
  owner: userData.id,
74
74
  description,
75
75
  tags,
76
+ nominations: [],
76
77
  })
77
78
  .select("*")
78
79
  .single();
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "rhythia-api",
3
- "version": "139.0.0",
3
+ "version": "142.0.0",
4
4
  "main": "index.ts",
5
5
  "scripts": {
6
6
  "update": "bun ./scripts/update.ts",
@@ -1,76 +0,0 @@
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/test.ts DELETED
@@ -1,96 +0,0 @@
1
- import { createClient } from "@supabase/supabase-js";
2
- import { Database } from "../types/database";
3
- import { SSPMParser } from "../utils/star-calc/sspmParser";
4
- import { rateMap, rateMapOld } from "../utils/star-calc";
5
- import { V1SSPMParser } from "../utils/star-calc/sspmv1Parser";
6
-
7
- export const supabase = createClient<Database>(
8
- `https://pfkajngbllcbdzoylrvp.supabase.co`,
9
- "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiJzdXBhYmFzZSIsInJlZiI6InBma2FqbmdibGxjYmR6b3lscnZwIiwicm9sZSI6InNlcnZpY2Vfcm9sZSIsImlhdCI6MTcxODU3NjA3MCwiZXhwIjoyMDM0MTUyMDcwfQ.XKUlQWvzmcYyirM-Zi4nwhiEKcpx1xLS97QUyuR3MoY",
10
- {
11
- auth: {
12
- autoRefreshToken: false,
13
- persistSession: false,
14
- },
15
- }
16
- );
17
-
18
- async function main() {
19
- let qry = supabase
20
- .from("beatmapPages")
21
- .select(
22
- `
23
- owner,
24
- created_at,
25
- id,
26
- status,
27
- beatmaps!inner(
28
- playcount,
29
- ranked,
30
- beatmapFile,
31
- image,
32
- starRating,
33
- difficulty,
34
- title
35
- ),
36
- profiles!inner(
37
- username
38
- )`
39
- )
40
- .order("created_at", { ascending: false });
41
-
42
- qry = qry.ilike("beatmaps.title", "%Ca%");
43
- qry = qry.ilike("profiles.username", "%Ca%");
44
-
45
- const data = await qry;
46
- console.log(data);
47
- // console.log(data.data[]);
48
- // const req = await fetch(`https://cdn.rhythia.net/index.json`);
49
- // const json = Object.values(await req.json()) as any[];
50
- // console.log(json[0]);
51
-
52
- // let count = 0;
53
- // for (const map of json) {
54
- // const request = await fetch(map.download);
55
- // const bytes = await request.arrayBuffer();
56
- // const parser = new SSPMParser(Buffer.from(bytes));
57
- // let rate = 0;
58
- // try {
59
- // const data = parser.parse();
60
- // rate = rateMap(data);
61
- // } catch (error) {
62
- // const parserOld = new V1SSPMParser(Buffer.from(bytes));
63
- // const data = parserOld.parse();
64
-
65
- // rate = rateMapOld(data);
66
- // }
67
- // await supabase.from("beatmaps").upsert({
68
- // beatmapHash: map.id,
69
- // starRating: rate,
70
- // });
71
- // count++;
72
- // console.log(count, json.length, map.id, rate);
73
- // }
74
- // for (const map of json) {
75
- // const reqMap = await fetch(map.link);
76
- // const buff = await reqMap.arrayBuffer();
77
- // writeFileSync("./toSubmit/" + map.id + ".sspm", Buffer.from(buff));
78
- // }
79
-
80
- // const { data: mapData, error } = await supabase
81
- // .from("beatmapPages")
82
- // .select("id,nominations,owner,status")
83
- // .eq("owner", 10)
84
- // .eq("status", "RANKED");
85
-
86
- // if (!mapData) {
87
- // throw "lolz";
88
- // }
89
-
90
- // for (const element of mapData) {
91
-
92
- // console.log(data.error);
93
- // }
94
- }
95
-
96
- main();
package/scripts/update.ts DELETED
@@ -1,49 +0,0 @@
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`;