feat: manual backfill for admin
This commit is contained in:
+25
-27
@@ -1,12 +1,13 @@
|
|||||||
import { Router } from "express";
|
import { Router } from "express";
|
||||||
import { io } from "../index";
|
|
||||||
import {
|
import {
|
||||||
type AuthenticatedRequest,
|
|
||||||
authenticate,
|
authenticate,
|
||||||
|
AuthenticatedRequest,
|
||||||
requireAdmin,
|
requireAdmin,
|
||||||
} from "../middleware/auth";
|
} from "../middleware/auth";
|
||||||
import { asyncHandler } from "../middleware/errorHandler";
|
|
||||||
import { prisma } from "../utils/prisma";
|
import { prisma } from "../utils/prisma";
|
||||||
|
import { asyncHandler } from "../middleware/errorHandler";
|
||||||
|
import { io } from "../index";
|
||||||
|
import { backfillUserHistory } from "../services/tautulli";
|
||||||
|
|
||||||
const router = Router();
|
const router = Router();
|
||||||
|
|
||||||
@@ -20,6 +21,7 @@ router.get(
|
|||||||
res.json(settings);
|
res.json(settings);
|
||||||
}),
|
}),
|
||||||
);
|
);
|
||||||
|
|
||||||
router.put(
|
router.put(
|
||||||
"/settings",
|
"/settings",
|
||||||
authenticate,
|
authenticate,
|
||||||
@@ -43,30 +45,7 @@ router.put(
|
|||||||
res.json(settings);
|
res.json(settings);
|
||||||
}),
|
}),
|
||||||
);
|
);
|
||||||
router.post(
|
|
||||||
"/pause",
|
|
||||||
authenticate,
|
|
||||||
requireAdmin,
|
|
||||||
asyncHandler(async (req: AuthenticatedRequest, res) => {
|
|
||||||
await prisma.systemSettings.update({
|
|
||||||
where: { id: "default" },
|
|
||||||
data: { mintingPaused: true, updatedBy: req.user!.id },
|
|
||||||
});
|
|
||||||
res.json({ message: "Paused" });
|
|
||||||
}),
|
|
||||||
);
|
|
||||||
router.post(
|
|
||||||
"/resume",
|
|
||||||
authenticate,
|
|
||||||
requireAdmin,
|
|
||||||
asyncHandler(async (req: AuthenticatedRequest, res) => {
|
|
||||||
await prisma.systemSettings.update({
|
|
||||||
where: { id: "default" },
|
|
||||||
data: { mintingPaused: false, updatedBy: req.user!.id },
|
|
||||||
});
|
|
||||||
res.json({ message: "Resumed" });
|
|
||||||
}),
|
|
||||||
);
|
|
||||||
router.get(
|
router.get(
|
||||||
"/users",
|
"/users",
|
||||||
authenticate,
|
authenticate,
|
||||||
@@ -114,6 +93,7 @@ router.get(
|
|||||||
});
|
});
|
||||||
}),
|
}),
|
||||||
);
|
);
|
||||||
|
|
||||||
router.put(
|
router.put(
|
||||||
"/users/:id",
|
"/users/:id",
|
||||||
authenticate,
|
authenticate,
|
||||||
@@ -127,6 +107,7 @@ router.put(
|
|||||||
res.json(user);
|
res.json(user);
|
||||||
}),
|
}),
|
||||||
);
|
);
|
||||||
|
|
||||||
router.post(
|
router.post(
|
||||||
"/users/:id/bonus",
|
"/users/:id/bonus",
|
||||||
authenticate,
|
authenticate,
|
||||||
@@ -158,6 +139,7 @@ router.post(
|
|||||||
res.json({ success: true, amount, transaction });
|
res.json({ success: true, amount, transaction });
|
||||||
}),
|
}),
|
||||||
);
|
);
|
||||||
|
|
||||||
router.post(
|
router.post(
|
||||||
"/users/:id/adjust",
|
"/users/:id/adjust",
|
||||||
authenticate,
|
authenticate,
|
||||||
@@ -188,6 +170,22 @@ router.post(
|
|||||||
res.json({ success: true });
|
res.json({ success: true });
|
||||||
}),
|
}),
|
||||||
);
|
);
|
||||||
|
|
||||||
|
router.post(
|
||||||
|
"/users/:id/backfill",
|
||||||
|
authenticate,
|
||||||
|
requireAdmin,
|
||||||
|
asyncHandler(async (req: AuthenticatedRequest, res) => {
|
||||||
|
const user = await prisma.user.findUnique({ where: { id: req.params.id } });
|
||||||
|
if (!user) return res.status(404).json({ error: "User not found" });
|
||||||
|
await backfillUserHistory(user);
|
||||||
|
const updatedUser = await prisma.user.findUnique({
|
||||||
|
where: { id: user.id },
|
||||||
|
});
|
||||||
|
res.json({ success: true, user: updatedUser });
|
||||||
|
}),
|
||||||
|
);
|
||||||
|
|
||||||
router.get(
|
router.get(
|
||||||
"/analytics",
|
"/analytics",
|
||||||
authenticate,
|
authenticate,
|
||||||
|
|||||||
+1
-118
@@ -1,24 +1,9 @@
|
|||||||
import axios from "axios";
|
import axios from "axios";
|
||||||
import crypto from "crypto";
|
|
||||||
import { Router } from "express";
|
import { Router } from "express";
|
||||||
import jwt from "jsonwebtoken";
|
import jwt from "jsonwebtoken";
|
||||||
import { asyncHandler } from "../middleware/errorHandler";
|
import { asyncHandler } from "../middleware/errorHandler";
|
||||||
import { prisma } from "../utils/prisma";
|
import { prisma } from "../utils/prisma";
|
||||||
|
import { backfillUserHistory } from "../services/tautulli";
|
||||||
const ENCRYPTION_KEY =
|
|
||||||
process.env.ENCRYPTION_KEY || "default-key-32-chars-long!!!!!";
|
|
||||||
const TAUTULLI_URL = process.env.TAUTULLI_URL || "";
|
|
||||||
const TAUTULLI_API_KEY = process.env.TAUTULLI_API_KEY || "";
|
|
||||||
|
|
||||||
function encrypt(text: string): string {
|
|
||||||
const iv = crypto.randomBytes(16);
|
|
||||||
const key = crypto.createHash("sha256").update(ENCRYPTION_KEY).digest();
|
|
||||||
const cipher = crypto.createCipheriv("aes-256-gcm", key, iv);
|
|
||||||
let encrypted = cipher.update(text, "utf8", "hex");
|
|
||||||
encrypted += cipher.final("hex");
|
|
||||||
const authTag = cipher.getAuthTag();
|
|
||||||
return `${iv.toString("hex")}:${authTag.toString("hex")}:${encrypted}`;
|
|
||||||
}
|
|
||||||
|
|
||||||
const router = Router();
|
const router = Router();
|
||||||
|
|
||||||
@@ -183,106 +168,4 @@ router.post(
|
|||||||
}),
|
}),
|
||||||
);
|
);
|
||||||
|
|
||||||
async function backfillUserHistory(user: {
|
|
||||||
id: string;
|
|
||||||
plexId: string;
|
|
||||||
plexUsername: string;
|
|
||||||
}) {
|
|
||||||
if (!TAUTULLI_URL || !TAUTULLI_API_KEY) return;
|
|
||||||
try {
|
|
||||||
const usersResponse = await axios.get(`${TAUTULLI_URL}/api/v2`, {
|
|
||||||
params: { apikey: TAUTULLI_API_KEY, cmd: "get_users" },
|
|
||||||
});
|
|
||||||
const tautulliUsers = usersResponse.data?.response?.data || [];
|
|
||||||
const tautulliUser = tautulliUsers.find(
|
|
||||||
(u: any) =>
|
|
||||||
u.username?.toLowerCase() === user.plexUsername.toLowerCase() ||
|
|
||||||
u.email?.toLowerCase() === user.plexUsername.toLowerCase() ||
|
|
||||||
u.friendly_name?.toLowerCase() === user.plexUsername.toLowerCase(),
|
|
||||||
);
|
|
||||||
if (!tautulliUser) return;
|
|
||||||
|
|
||||||
const startDate = (() => {
|
|
||||||
const d = new Date();
|
|
||||||
d.setDate(d.getDate() - 30);
|
|
||||||
return d.toISOString().split("T")[0];
|
|
||||||
})();
|
|
||||||
const historyResponse = await axios.get(`${TAUTULLI_URL}/api/v2`, {
|
|
||||||
params: {
|
|
||||||
apikey: TAUTULLI_API_KEY,
|
|
||||||
cmd: "get_history",
|
|
||||||
user_id: tautulliUser.user_id,
|
|
||||||
start_date: startDate,
|
|
||||||
length: 1000,
|
|
||||||
},
|
|
||||||
});
|
|
||||||
const historyData = historyResponse.data?.response?.data?.data || [];
|
|
||||||
if (!Array.isArray(historyData) || historyData.length === 0) return;
|
|
||||||
|
|
||||||
const settings = await prisma.systemSettings.findFirst();
|
|
||||||
const creditsPerMinute = settings?.creditsPerMinute || 2;
|
|
||||||
const minWatchPercent = settings?.minWatchPercent || 80;
|
|
||||||
const minWatchMinutes = settings?.minWatchMinutes || 5;
|
|
||||||
|
|
||||||
let totalCredits = 0;
|
|
||||||
let totalMinutes = 0;
|
|
||||||
for (const item of historyData) {
|
|
||||||
const sessionId = item.reference_id?.toString() || item.id?.toString();
|
|
||||||
if (!sessionId) continue;
|
|
||||||
if (await prisma.watchEvent.findUnique({ where: { sessionId } }))
|
|
||||||
continue;
|
|
||||||
const percentComplete = item.percent_complete || 0;
|
|
||||||
const watchDurationMinutes = Math.floor(
|
|
||||||
(item.stopped - item.started) / 60,
|
|
||||||
);
|
|
||||||
if (
|
|
||||||
percentComplete < minWatchPercent ||
|
|
||||||
watchDurationMinutes < minWatchMinutes
|
|
||||||
)
|
|
||||||
continue;
|
|
||||||
const creditsEarned = watchDurationMinutes * creditsPerMinute;
|
|
||||||
const watchEvent = await prisma.watchEvent.create({
|
|
||||||
data: {
|
|
||||||
userId: user.id,
|
|
||||||
sessionId,
|
|
||||||
ratingKey: item.rating_key?.toString() || "",
|
|
||||||
contentType: item.media_type || "movie",
|
|
||||||
title: item.title || item.full_title || "Unknown",
|
|
||||||
grandparentTitle: item.grandparent_title || null,
|
|
||||||
duration: item.stopped - item.started,
|
|
||||||
percentComplete: Math.floor(percentComplete),
|
|
||||||
creditsEarned,
|
|
||||||
isProcessed: true,
|
|
||||||
watchedAt: new Date(item.stopped * 1000),
|
|
||||||
},
|
|
||||||
});
|
|
||||||
await prisma.transaction.create({
|
|
||||||
data: {
|
|
||||||
userId: user.id,
|
|
||||||
type: "EARN",
|
|
||||||
amount: creditsEarned,
|
|
||||||
watchEventId: watchEvent.id,
|
|
||||||
description: `Watched ${item.title || item.full_title || "Unknown"}`,
|
|
||||||
contentTitle: item.title || item.full_title || "Unknown",
|
|
||||||
},
|
|
||||||
});
|
|
||||||
totalCredits += creditsEarned;
|
|
||||||
totalMinutes += watchDurationMinutes;
|
|
||||||
}
|
|
||||||
if (totalCredits > 0)
|
|
||||||
await prisma.user.update({
|
|
||||||
where: { id: user.id },
|
|
||||||
data: {
|
|
||||||
totalEarned: { increment: totalCredits },
|
|
||||||
watchTimeMinutes: { increment: totalMinutes },
|
|
||||||
},
|
|
||||||
});
|
|
||||||
} catch (error) {
|
|
||||||
console.error(
|
|
||||||
`Failed to backfill history for ${user.plexUsername}:`,
|
|
||||||
error,
|
|
||||||
);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
export { router as authRouter };
|
export { router as authRouter };
|
||||||
|
|||||||
@@ -0,0 +1,107 @@
|
|||||||
|
import axios from "axios";
|
||||||
|
import { prisma } from "../utils/prisma";
|
||||||
|
|
||||||
|
const TAUTULLI_URL = process.env.TAUTULLI_URL || "";
|
||||||
|
const TAUTULLI_API_KEY = process.env.TAUTULLI_API_KEY || "";
|
||||||
|
|
||||||
|
export async function backfillUserHistory(user: {
|
||||||
|
id: string;
|
||||||
|
plexId: string;
|
||||||
|
plexUsername: string;
|
||||||
|
}) {
|
||||||
|
if (!TAUTULLI_URL || !TAUTULLI_API_KEY) return;
|
||||||
|
try {
|
||||||
|
const usersResponse = await axios.get(`${TAUTULLI_URL}/api/v2`, {
|
||||||
|
params: { apikey: TAUTULLI_API_KEY, cmd: "get_users" },
|
||||||
|
});
|
||||||
|
const tautulliUsers = usersResponse.data?.response?.data || [];
|
||||||
|
const tautulliUser = tautulliUsers.find(
|
||||||
|
(u: any) =>
|
||||||
|
u.username?.toLowerCase() === user.plexUsername.toLowerCase() ||
|
||||||
|
u.email?.toLowerCase() === user.plexUsername.toLowerCase() ||
|
||||||
|
u.friendly_name?.toLowerCase() === user.plexUsername.toLowerCase(),
|
||||||
|
);
|
||||||
|
if (!tautulliUser) return;
|
||||||
|
|
||||||
|
const startDate = (() => {
|
||||||
|
const d = new Date();
|
||||||
|
d.setDate(d.getDate() - 30);
|
||||||
|
return d.toISOString().split("T")[0];
|
||||||
|
})();
|
||||||
|
const historyResponse = await axios.get(`${TAUTULLI_URL}/api/v2`, {
|
||||||
|
params: {
|
||||||
|
apikey: TAUTULLI_API_KEY,
|
||||||
|
cmd: "get_history",
|
||||||
|
user_id: tautulliUser.user_id,
|
||||||
|
start_date: startDate,
|
||||||
|
length: 1000,
|
||||||
|
},
|
||||||
|
});
|
||||||
|
const historyData = historyResponse.data?.response?.data?.data || [];
|
||||||
|
if (!Array.isArray(historyData) || historyData.length === 0) return;
|
||||||
|
|
||||||
|
const settings = await prisma.systemSettings.findFirst();
|
||||||
|
const creditsPerMinute = settings?.creditsPerMinute || 2;
|
||||||
|
const minWatchPercent = settings?.minWatchPercent || 80;
|
||||||
|
const minWatchMinutes = settings?.minWatchMinutes || 5;
|
||||||
|
|
||||||
|
let totalCredits = 0;
|
||||||
|
let totalMinutes = 0;
|
||||||
|
for (const item of historyData) {
|
||||||
|
const sessionId = item.reference_id?.toString() || item.id?.toString();
|
||||||
|
if (!sessionId) continue;
|
||||||
|
if (await prisma.watchEvent.findUnique({ where: { sessionId } }))
|
||||||
|
continue;
|
||||||
|
const percentComplete = item.percent_complete || 0;
|
||||||
|
const watchDurationMinutes = Math.floor(
|
||||||
|
(item.stopped - item.started) / 60,
|
||||||
|
);
|
||||||
|
if (
|
||||||
|
percentComplete < minWatchPercent ||
|
||||||
|
watchDurationMinutes < minWatchMinutes
|
||||||
|
)
|
||||||
|
continue;
|
||||||
|
const creditsEarned = watchDurationMinutes * creditsPerMinute;
|
||||||
|
const watchEvent = await prisma.watchEvent.create({
|
||||||
|
data: {
|
||||||
|
userId: user.id,
|
||||||
|
sessionId,
|
||||||
|
ratingKey: item.rating_key?.toString() || "",
|
||||||
|
contentType: item.media_type || "movie",
|
||||||
|
title: item.title || item.full_title || "Unknown",
|
||||||
|
grandparentTitle: item.grandparent_title || null,
|
||||||
|
duration: item.stopped - item.started,
|
||||||
|
percentComplete: Math.floor(percentComplete),
|
||||||
|
creditsEarned,
|
||||||
|
isProcessed: true,
|
||||||
|
watchedAt: new Date(item.stopped * 1000),
|
||||||
|
},
|
||||||
|
});
|
||||||
|
await prisma.transaction.create({
|
||||||
|
data: {
|
||||||
|
userId: user.id,
|
||||||
|
type: "EARN",
|
||||||
|
amount: creditsEarned,
|
||||||
|
watchEventId: watchEvent.id,
|
||||||
|
description: `Watched ${item.title || item.full_title || "Unknown"}`,
|
||||||
|
contentTitle: item.title || item.full_title || "Unknown",
|
||||||
|
},
|
||||||
|
});
|
||||||
|
totalCredits += creditsEarned;
|
||||||
|
totalMinutes += watchDurationMinutes;
|
||||||
|
}
|
||||||
|
if (totalCredits > 0)
|
||||||
|
await prisma.user.update({
|
||||||
|
where: { id: user.id },
|
||||||
|
data: {
|
||||||
|
totalEarned: { increment: totalCredits },
|
||||||
|
watchTimeMinutes: { increment: totalMinutes },
|
||||||
|
},
|
||||||
|
});
|
||||||
|
} catch (error) {
|
||||||
|
console.error(
|
||||||
|
`Failed to backfill history for ${user.plexUsername}:`,
|
||||||
|
error,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
Reference in New Issue
Block a user