52 lines
1.6 KiB
TypeScript
52 lines
1.6 KiB
TypeScript
|
|
'use server';
|
||
|
|
|
||
|
|
import { auth } from "@/auth";
|
||
|
|
import { prisma } from "@/lib/prisma";
|
||
|
|
import { revalidatePath } from "next/cache";
|
||
|
|
|
||
|
|
export async function syncOneDrive() {
|
||
|
|
const session = await auth();
|
||
|
|
|
||
|
|
if (!session?.user?.id) throw new Error("Unauthorized");
|
||
|
|
|
||
|
|
// 1. Get the OAuth token from your PostgreSQL 'Account' table
|
||
|
|
const account = await prisma.account.findFirst({
|
||
|
|
where: { userId: session.user.id },
|
||
|
|
});
|
||
|
|
|
||
|
|
if (!account?.access_token) throw new Error("Microsoft account not linked properly");
|
||
|
|
|
||
|
|
// 2. Fetch the files from Microsoft Graph
|
||
|
|
const response = await fetch("https://graph.microsoft.com/v1.0/me/drive/root/children", {
|
||
|
|
headers: { Authorization: `Bearer ${account.access_token}` },
|
||
|
|
});
|
||
|
|
|
||
|
|
const data = await response.json();
|
||
|
|
|
||
|
|
// 3. The "Sync Loop": Map OneDrive items to your Postgres FileNode table
|
||
|
|
for (const item of data.value) {
|
||
|
|
const extension = item.name.split('.').pop()?.toUpperCase() || (item.folder ? 'FOLDER' : 'UNKNOWN');
|
||
|
|
|
||
|
|
await prisma.fileNode.upsert({
|
||
|
|
where: { oneDriveId: item.id },
|
||
|
|
update: {
|
||
|
|
name: item.name,
|
||
|
|
size: item.size,
|
||
|
|
metadata: { type: extension }, // Store the "Type" in your JSONB field
|
||
|
|
},
|
||
|
|
create: {
|
||
|
|
oneDriveId: item.id,
|
||
|
|
name: item.name,
|
||
|
|
size: item.size,
|
||
|
|
isFolder: !!item.folder,
|
||
|
|
path: item.parentReference.path + '/' + item.name,
|
||
|
|
ownerId: session.user.id,
|
||
|
|
metadata: { type: extension },
|
||
|
|
}
|
||
|
|
});
|
||
|
|
}
|
||
|
|
|
||
|
|
// Refresh the dashboard UI to show new data
|
||
|
|
revalidatePath('/dashboard');
|
||
|
|
return { success: true, count: data.value.length };
|
||
|
|
}
|