import Fastify from "fastify"; import { Yapper } from "./Yapper"; import path from "path"; import { readFileSync, writeFileSync } from "fs"; const state = new Proxy( JSON.parse(readFileSync(path.join(__dirname, "state.json"), "utf-8")), { get(target, prop) { const data = readFileSync( path.join(__dirname, "state.json"), "utf-8" ); return JSON.parse(data); }, set(target, prop, value) { const data = JSON.parse( readFileSync(path.join(__dirname, "state.json"), "utf-8") ); data[prop] = value; writeFileSync( path.join(__dirname, "state.json"), JSON.stringify(data) ); return true; } } ); const fastify = Fastify({ loggerInstance: new Yapper() }); fastify.get("/", (request, reply) => { reply.type("text/html"); return 'auth'; }); fastify.get("/auth", async (request, reply) => { return reply.redirect( `https://accounts.spotify.com/authorize?` + new URLSearchParams({ response_type: "code", client_id: process.env.CLIENT_ID!, scope: "user-library-read user-library-modify playlist-read-private playlist-read-collaborative playlist-modify-private playlist-modify-public", redirect_uri: `https://${request.hostname}/callback`, show_dialog: "true", state: "ballsgamingmeoww" }).toString() ); }); fastify.get("/callback", async (request, reply) => { if ((request.query as any).error) return reply.code(400).send(); const tokenRes = await fetch("https://accounts.spotify.com/api/token", { method: "POST", headers: { "Content-Type": "application/x-www-form-urlencoded", Authorization: "Basic " + Buffer.from( process.env.CLIENT_ID + ":" + process.env.CLIENT_SECRET ).toString("base64") }, body: new URLSearchParams({ code: (request.query as any).code, redirect_uri: `https://${request.hostname}/callback`, grant_type: "authorization_code" }) }); console.log(await tokenRes.json()); }); try { fastify.listen({ port: 4929, host: "0.0.0.0" }); } catch (err) { fastify.log.error(err); process.exit(1); }