2023-12-30 05:56:40 -05:00
|
|
|
import axios from "axios"
|
|
|
|
import { db } from "@/lib/db"
|
|
|
|
import { NextResponse } from "next/server";
|
|
|
|
import fetchUserUsingAPI from "@/lib/validate-api";
|
|
|
|
|
|
|
|
export async function GET(req: Request) {
|
|
|
|
try {
|
|
|
|
const user = await fetchUserUsingAPI(req)
|
|
|
|
if (!user) {
|
|
|
|
console.log("TWITCH CONNECT", user)
|
|
|
|
return new NextResponse("Unauthorized", { status: 401 });
|
|
|
|
}
|
|
|
|
|
|
|
|
const { searchParams } = new URL(req.url)
|
|
|
|
let userId = searchParams.get('id')
|
|
|
|
|
|
|
|
if (userId == null) {
|
|
|
|
if (user != null) {
|
|
|
|
userId = user.id as string;
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
const connection = await db.twitchConnection.findFirst({
|
|
|
|
where: {
|
|
|
|
userId: userId as string
|
|
|
|
}
|
|
|
|
});
|
|
|
|
|
|
|
|
return NextResponse.json(connection);
|
|
|
|
} catch (error) {
|
|
|
|
console.log("[CONNECTION/TWITCH]", error);
|
|
|
|
return new NextResponse("Internal Error", { status: 500 });
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
export async function POST(req: Request) {
|
|
|
|
try {
|
|
|
|
const { id, secret } = await req.json();
|
|
|
|
const user = await fetchUserUsingAPI(req)
|
2023-12-31 05:41:55 -05:00
|
|
|
|
2023-12-30 05:56:40 -05:00
|
|
|
if (!user) {
|
|
|
|
return new NextResponse("Unauthorized", { status: 401 });
|
|
|
|
}
|
|
|
|
|
|
|
|
let response = null;
|
|
|
|
try {
|
|
|
|
response = await axios.post("https://id.twitch.tv/oauth2/token", {
|
|
|
|
client_id: id,
|
|
|
|
client_secret: secret,
|
|
|
|
grant_type: "client_credentials"
|
|
|
|
});
|
|
|
|
console.log(response.data)
|
|
|
|
} catch (error) {
|
|
|
|
console.log("[CONNECTIONS/TWITCH/TOKEN]", error);
|
|
|
|
return;
|
|
|
|
}
|
|
|
|
|
|
|
|
console.log(user.username)
|
|
|
|
let info = await axios.get("https://api.twitch.tv/helix/users?login=" + user.username, {
|
|
|
|
headers: {
|
|
|
|
"Authorization": "Bearer " + response.data['access_token'],
|
|
|
|
"Client-Id": id
|
|
|
|
}
|
|
|
|
})
|
|
|
|
console.log(info.data.data)
|
|
|
|
const broadcasterId = info.data.data[0]['id']
|
|
|
|
const username = info.data.data[0]['login']
|
|
|
|
|
|
|
|
const connection = await db.twitchConnection.create({
|
|
|
|
data: {
|
2023-12-31 05:41:55 -05:00
|
|
|
id: id,
|
2023-12-30 05:56:40 -05:00
|
|
|
secret,
|
|
|
|
userId: user.id as string,
|
|
|
|
broadcasterId,
|
|
|
|
username
|
|
|
|
}
|
|
|
|
});
|
|
|
|
|
|
|
|
return NextResponse.json(connection);
|
|
|
|
} catch (error) {
|
|
|
|
console.log("[CONNECTION/TWITCH]", error);
|
|
|
|
return new NextResponse("Internal Error", { status: 500 });
|
|
|
|
}
|
|
|
|
}
|