Add Watch Buddies feature

- Created WatchBuddy model
- M:N junctions to EntrySeen/EpisodeSeen
  and Media relation for profile pictures
- Full CRUD + search + profile picture upload
- WatchBuddySelect multi-select with search and inline create, replaced
  all seen_with text inputs
- WatchBuddiesPage (grid) and WatchBuddyProfilePage (edit form,
  icon-based contacts, poster-grid watch history, monthly timeline)
This commit is contained in:
X4Lo committed 2026-06-25 03:11:14 +01:00
1 parent 4313a794ce
commit e82b905886
28 files changed
+6813 -374

No files matched your search

+159 -114
View File
@@ -1,21 +1,24 @@
// Import models // Import models
const Franchise = require("../models/Franchise"); const Franchise = require('../models/Franchise');
const Entry = require("../models/Entry"); const Entry = require('../models/Entry');
const EntryId = require("../models/EntryId"); const EntryId = require('../models/EntryId');
const EntryRating = require("../models/EntryRating"); const EntryRating = require('../models/EntryRating');
const EntrySeen = require("../models/EntrySeen"); const EntrySeen = require('../models/EntrySeen');
const Collection = require("../models/Collection"); const Collection = require('../models/Collection');
const UserCollectionEntry = require("../models/UserCollectionEntry"); const UserCollectionEntry = require('../models/UserCollectionEntry');
const Season = require("../models/Season"); const Season = require('../models/Season');
const Episode = require("../models/Episode"); const Episode = require('../models/Episode');
const EpisodeSeen = require("../models/EpisodeSeen"); const EpisodeSeen = require('../models/EpisodeSeen');
const Genre = require("../models/Genre"); const Genre = require('../models/Genre');
const EntryGenre = require("../models/EntryGenre"); const EntryGenre = require('../models/EntryGenre');
const Media = require("../models/Media"); const Media = require('../models/Media');
const Network = require("../models/Network"); const Network = require('../models/Network');
const EntryNetwork = require("../models/EntryNetwork"); const EntryNetwork = require('../models/EntryNetwork');
const People = require("../models/People"); const People = require('../models/People');
const Credit = require("../models/Credit"); const Credit = require('../models/Credit');
const WatchBuddy = require('../models/WatchBuddy');
const EntrySeenBuddy = require('../models/EntrySeenBuddy');
const EpisodeSeenBuddy = require('../models/EpisodeSeenBuddy');
// ? one to one // ? one to one
// A hasOne B = A > B // A hasOne B = A > B
@@ -26,221 +29,263 @@ const Credit = require("../models/Credit");
// * ENTRY & EntryId - ONE TO ONE // * ENTRY & EntryId - ONE TO ONE
Entry.hasOne(EntryId, { Entry.hasOne(EntryId, {
foreignKey: "entry_id", foreignKey: 'entry_id',
as: "entryId", as: 'entryId',
onDelete: "CASCADE", onDelete: 'CASCADE',
}); });
EntryId.belongsTo(Entry, { foreignKey: "entry_id", as: "entry" }); EntryId.belongsTo(Entry, { foreignKey: 'entry_id', as: 'entry' });
// * ENTRY & EntryRating - ONE TO ONE // * ENTRY & EntryRating - ONE TO ONE
Entry.hasOne(EntryRating, { Entry.hasOne(EntryRating, {
foreignKey: "entry_id", foreignKey: 'entry_id',
as: "entryRating", as: 'entryRating',
onDelete: "CASCADE", onDelete: 'CASCADE',
}); });
EntryRating.belongsTo(Entry, { foreignKey: "entry_id", as: "entry" }); EntryRating.belongsTo(Entry, { foreignKey: 'entry_id', as: 'entry' });
// * ENTRY & ENTRY_SEEN - ONE TO MANY // * ENTRY & ENTRY_SEEN - ONE TO MANY
Entry.hasMany(EntrySeen, { Entry.hasMany(EntrySeen, {
foreignKey: "entry_id", foreignKey: 'entry_id',
as: "entrySeen", as: 'entrySeen',
onDelete: "CASCADE", onDelete: 'CASCADE',
}); });
EntrySeen.belongsTo(Entry, { foreignKey: "entry_id", as: "entry" }); EntrySeen.belongsTo(Entry, { foreignKey: 'entry_id', as: 'entry' });
// * ENTRY & LIST - MANY TO MANY // * ENTRY & LIST - MANY TO MANY
Entry.belongsToMany(Collection, { Entry.belongsToMany(Collection, {
through: UserCollectionEntry, through: UserCollectionEntry,
foreignKey: "entry_id", foreignKey: 'entry_id',
otherKey: "user_collection_id", otherKey: 'user_collection_id',
onDelete: "CASCADE", onDelete: 'CASCADE',
as: "collections", as: 'collections',
}); });
Collection.belongsToMany(Entry, { Collection.belongsToMany(Entry, {
through: UserCollectionEntry, through: UserCollectionEntry,
foreignKey: "user_collection_id", foreignKey: 'user_collection_id',
otherKey: "entry_id", otherKey: 'entry_id',
onDelete: "CASCADE", onDelete: 'CASCADE',
as: "entries", as: 'entries',
}); });
Entry.hasMany(UserCollectionEntry, { Entry.hasMany(UserCollectionEntry, {
foreignKey: "entry_id", foreignKey: 'entry_id',
as: "userCollectionEntries", as: 'userCollectionEntries',
}); });
UserCollectionEntry.belongsTo(Entry, { foreignKey: "entry_id", as: "entry" }); UserCollectionEntry.belongsTo(Entry, { foreignKey: 'entry_id', as: 'entry' });
Collection.hasMany(UserCollectionEntry, { Collection.hasMany(UserCollectionEntry, {
foreignKey: "user_collection_id", foreignKey: 'user_collection_id',
as: "userCollectionEntries", as: 'userCollectionEntries',
}); });
UserCollectionEntry.belongsTo(Collection, { UserCollectionEntry.belongsTo(Collection, {
foreignKey: "user_collection_id", foreignKey: 'user_collection_id',
as: "userCollection", as: 'userCollection',
}); });
// * ENTRY & GENRE - MANY TO MANY // * ENTRY & GENRE - MANY TO MANY
Entry.belongsToMany(Genre, { Entry.belongsToMany(Genre, {
through: EntryGenre, through: EntryGenre,
foreignKey: "entry_id", foreignKey: 'entry_id',
otherKey: "genre_id", otherKey: 'genre_id',
onDelete: "CASCADE", onDelete: 'CASCADE',
as: "genres", as: 'genres',
}); });
Genre.belongsToMany(Entry, { Genre.belongsToMany(Entry, {
through: EntryGenre, through: EntryGenre,
foreignKey: "genre_id", foreignKey: 'genre_id',
otherKey: "entry_id", otherKey: 'entry_id',
onDelete: "CASCADE", onDelete: 'CASCADE',
as: "entries", as: 'entries',
}); });
Entry.hasMany(EntryGenre, { foreignKey: "entry_id", as: "entryGenres" }); Entry.hasMany(EntryGenre, { foreignKey: 'entry_id', as: 'entryGenres' });
EntryGenre.belongsTo(Entry, { foreignKey: "entry_id", as: "entry" }); EntryGenre.belongsTo(Entry, { foreignKey: 'entry_id', as: 'entry' });
Genre.hasMany(EntryGenre, { foreignKey: "genre_id", as: "entryGenres" }); Genre.hasMany(EntryGenre, { foreignKey: 'genre_id', as: 'entryGenres' });
EntryGenre.belongsTo(Genre, { foreignKey: "genre_id", as: "genre" }); EntryGenre.belongsTo(Genre, { foreignKey: 'genre_id', as: 'genre' });
// * ENTRY & NETWORK - MANY TO MANY // * ENTRY & NETWORK - MANY TO MANY
Entry.belongsToMany(Network, { Entry.belongsToMany(Network, {
through: EntryNetwork, through: EntryNetwork,
foreignKey: "entry_id", foreignKey: 'entry_id',
otherKey: "network_id", otherKey: 'network_id',
onDelete: "CASCADE", onDelete: 'CASCADE',
as: "networks", as: 'networks',
}); });
Network.belongsToMany(Entry, { Network.belongsToMany(Entry, {
through: EntryNetwork, through: EntryNetwork,
foreignKey: "network_id", foreignKey: 'network_id',
otherKey: "entry_id", otherKey: 'entry_id',
onDelete: "CASCADE", onDelete: 'CASCADE',
as: "entries", as: 'entries',
}); });
// ! MEDIA // ! MEDIA
// * MEDIA & ENTRY - MANY TO ONE // * MEDIA & ENTRY - MANY TO ONE
Media.belongsTo(Entry, { Media.belongsTo(Entry, {
foreignKey: "mediaableId", foreignKey: 'mediaableId',
as: "entry", as: 'entry',
constraints: false, constraints: false,
where: { where: {
mediaable: "entry", mediaable: 'entry',
}, },
}); });
Entry.hasMany(Media, { Entry.hasMany(Media, {
foreignKey: "mediaableId", foreignKey: 'mediaableId',
constraints: false, constraints: false,
as: "medias", as: 'medias',
scope: { mediaable: "entry" }, scope: { mediaable: 'entry' },
}); });
// * MEDIA & People - MANY TO ONE // * MEDIA & People - MANY TO ONE
Media.belongsTo(People, { Media.belongsTo(People, {
foreignKey: "mediaableId", foreignKey: 'mediaableId',
as: "people", as: 'people',
constraints: false, constraints: false,
where: { where: {
mediaable: "people", mediaable: 'people',
}, },
}); });
People.hasMany(Media, { People.hasMany(Media, {
foreignKey: "mediaableId", foreignKey: 'mediaableId',
constraints: false, constraints: false,
as: "medias", as: 'medias',
scope: { mediaable: "people" }, scope: { mediaable: 'people' },
}); });
// * MEDIA & Collection - MANY TO ONE // * MEDIA & Collection - MANY TO ONE
Media.belongsTo(Collection, { Media.belongsTo(Collection, {
foreignKey: "mediaableId", foreignKey: 'mediaableId',
as: "collection", as: 'collection',
constraints: false, constraints: false,
where: { where: {
mediaable: "collection", mediaable: 'collection',
}, },
}); });
Collection.hasMany(Media, { Collection.hasMany(Media, {
foreignKey: "mediaableId", foreignKey: 'mediaableId',
constraints: false, constraints: false,
as: "medias", as: 'medias',
scope: { mediaable: "collection" }, scope: { mediaable: 'collection' },
}); });
// * MEDIA & Season - MANY TO ONE // * MEDIA & Season - MANY TO ONE
Media.belongsTo(Season, { Media.belongsTo(Season, {
foreignKey: "mediaableId", foreignKey: 'mediaableId',
as: "season", as: 'season',
constraints: false, constraints: false,
where: { where: {
mediaable: "season", mediaable: 'season',
}, },
}); });
Season.hasMany(Media, { Season.hasMany(Media, {
foreignKey: "mediaableId", foreignKey: 'mediaableId',
constraints: false, constraints: false,
as: "medias", as: 'medias',
scope: { mediaable: "season" }, scope: { mediaable: 'season' },
}); });
// * MEDIA & Episode - MANY TO ONE // * MEDIA & Episode - MANY TO ONE
Media.belongsTo(Episode, { Media.belongsTo(Episode, {
foreignKey: "mediaableId", foreignKey: 'mediaableId',
as: "episode", as: 'episode',
constraints: false, constraints: false,
where: { where: {
mediaable: "episode", mediaable: 'episode',
}, },
}); });
Episode.hasMany(Media, { Episode.hasMany(Media, {
foreignKey: "mediaableId", foreignKey: 'mediaableId',
constraints: false, constraints: false,
as: "medias", as: 'medias',
scope: { mediaable: "episode" }, scope: { mediaable: 'episode' },
}); });
// ! MEDIA END // ! MEDIA END
// * ENTRY & SEASON - ONE TO MANY // * ENTRY & SEASON - ONE TO MANY
Entry.hasMany(Season, { Entry.hasMany(Season, {
foreignKey: "entry_id", foreignKey: 'entry_id',
as: "seasons", as: 'seasons',
onDelete: "CASCADE", onDelete: 'CASCADE',
}); });
Season.belongsTo(Entry, { foreignKey: "entry_id", as: "entry" }); Season.belongsTo(Entry, { foreignKey: 'entry_id', as: 'entry' });
// * SEASON & EPISODE - ONE TO MANY // * SEASON & EPISODE - ONE TO MANY
Season.hasMany(Episode, { foreignKey: "season_id", onDelete: "CASCADE" }); Season.hasMany(Episode, { foreignKey: 'season_id', onDelete: 'CASCADE' });
Episode.belongsTo(Season, { foreignKey: "season_id" }); Episode.belongsTo(Season, { foreignKey: 'season_id' });
// * EPISODE & EPISODE_SEEN - ONE TO MANY // * EPISODE & EPISODE_SEEN - ONE TO MANY
Episode.hasMany(EpisodeSeen, { foreignKey: "episode_id", onDelete: "CASCADE" }); Episode.hasMany(EpisodeSeen, { foreignKey: 'episode_id', onDelete: 'CASCADE' });
EpisodeSeen.belongsTo(Episode, { foreignKey: "episode_id" }); EpisodeSeen.belongsTo(Episode, { foreignKey: 'episode_id' });
// * ENTRY & EPISODE_SEEN - ONE TO MANY // * ENTRY & EPISODE_SEEN - ONE TO MANY
Entry.hasMany(EpisodeSeen, { foreignKey: "entry_id", onDelete: "CASCADE" }); Entry.hasMany(EpisodeSeen, { foreignKey: 'entry_id', onDelete: 'CASCADE' });
EpisodeSeen.belongsTo(Entry, { foreignKey: "entry_id" }); EpisodeSeen.belongsTo(Entry, { foreignKey: 'entry_id' });
// * ---- // * ----
Franchise.hasMany(Entry, { foreignKey: "franchise_id" }); Franchise.hasMany(Entry, { foreignKey: 'franchise_id' });
Entry.belongsTo(Franchise, { foreignKey: "franchise_id" }); Entry.belongsTo(Franchise, { foreignKey: 'franchise_id' });
// * ENTRY & Credit - ONE TO MANY // * ENTRY & Credit - ONE TO MANY
Entry.hasMany(Credit, { Entry.hasMany(Credit, {
foreignKey: "entry_id", foreignKey: 'entry_id',
as: "credits", as: 'credits',
onDelete: "CASCADE", onDelete: 'CASCADE',
}); });
Credit.belongsTo(Entry, { foreignKey: "entry_id", as: "entry" }); Credit.belongsTo(Entry, { foreignKey: 'entry_id', as: 'entry' });
// * PEOPLE & CAST - ONE TO MANY // * PEOPLE & CAST - ONE TO MANY
People.hasMany(Credit, { People.hasMany(Credit, {
foreignKey: "people_id", foreignKey: 'people_id',
as: "roles", as: 'roles',
onDelete: "CASCADE", onDelete: 'CASCADE',
});
Credit.belongsTo(People, { foreignKey: 'people_id', as: 'person' });
// * WATCH BUDDY — MEDIA (profile picture)
WatchBuddy.hasMany(Media, {
foreignKey: 'mediaableId',
constraints: false,
as: 'medias',
scope: { mediaable: 'watch_buddy' },
});
Media.belongsTo(WatchBuddy, {
foreignKey: 'mediaableId',
as: 'watchBuddy',
constraints: false,
where: { mediaable: 'watch_buddy' },
});
// * ENTRY_SEEN & WATCH_BUDDY - MANY TO MANY
EntrySeen.belongsToMany(WatchBuddy, {
through: EntrySeenBuddy,
foreignKey: 'entry_seen_id',
otherKey: 'watch_buddy_id',
as: 'buddies',
});
WatchBuddy.belongsToMany(EntrySeen, {
through: EntrySeenBuddy,
foreignKey: 'watch_buddy_id',
otherKey: 'entry_seen_id',
as: 'entrySeens',
});
// * EPISODE_SEEN & WATCH_BUDDY - MANY TO MANY
EpisodeSeen.belongsToMany(WatchBuddy, {
through: EpisodeSeenBuddy,
foreignKey: 'episode_seen_id',
otherKey: 'watch_buddy_id',
as: 'buddies',
});
WatchBuddy.belongsToMany(EpisodeSeen, {
through: EpisodeSeenBuddy,
foreignKey: 'watch_buddy_id',
otherKey: 'episode_seen_id',
as: 'episodeSeens',
}); });
Credit.belongsTo(People, { foreignKey: "people_id", as: "person" });
+28 -19
View File
@@ -1,5 +1,6 @@
const Entry = require('../models/Entry'); const Entry = require("../models/Entry");
const EntrySeen = require('../models/EntrySeen'); const EntrySeen = require("../models/EntrySeen");
const WatchBuddy = require("../models/WatchBuddy");
class EntrySeenController { class EntrySeenController {
constructor() { constructor() {
@@ -18,34 +19,37 @@ class EntrySeenController {
const entrySeen = await EntrySeen.findByPk(req.params.id); const entrySeen = await EntrySeen.findByPk(req.params.id);
if (!entrySeen) { if (!entrySeen) {
res.status(404).json({ message: 'Entry seen record not found.' }); res.status(404).json({ message: "Entry seen record not found." });
} }
res.status(200).json(entrySeen); res.status(200).json(entrySeen);
} }
async createEntrySeen(req, res) { async createEntrySeen(req, res) {
const { entry_id, date_seen, seen_with } = req.body; const { entry_id, date_seen, seen_with, buddy_ids } = req.body;
// ? checking the an entry with the given id does exist
const entry = await Entry.findByPk(entry_id); const entry = await Entry.findByPk(entry_id);
if (!entry) { if (!entry) {
return res.status(404).json({ error: 'Entry not found' }); return res.status(404).json({ error: "Entry not found" });
} }
// Create a new EntrySeen record
const newEntrySeen = await EntrySeen.create({ const newEntrySeen = await EntrySeen.create({
entry_id, entry_id,
date_seen, date_seen,
seen_with, seen_with,
}); });
// Link watch buddies
if (Array.isArray(buddy_ids) && buddy_ids.length > 0) {
await newEntrySeen.setBuddies(buddy_ids);
}
// Auto-upgrade TV series status when first watched // Auto-upgrade TV series status when first watched
if ( if (
entry.is_tvseries && entry.is_tvseries &&
(!entry.watch_status || entry.watch_status === 'plan_to_watch') (!entry.watch_status || entry.watch_status === "plan_to_watch")
) { ) {
entry.watch_status = 'watching'; entry.watch_status = "watching";
await entry.save(); await entry.save();
} }
@@ -56,7 +60,8 @@ class EntrySeenController {
const { entryId } = req.params; const { entryId } = req.params;
const entrySeens = await EntrySeen.findAll({ const entrySeens = await EntrySeen.findAll({
where: { entry_id: entryId }, where: { entry_id: entryId },
order: [['date_seen', 'DESC']], order: [["date_seen", "DESC"]],
include: [{ model: WatchBuddy, as: "buddies" }],
}); });
if (entrySeens.length > 0) { if (entrySeens.length > 0) {
@@ -64,30 +69,34 @@ class EntrySeenController {
} else { } else {
res res
.status(404) .status(404)
.json({ message: 'No records found for the given entry ID.' }); .json({ message: "No records found for the given entry ID." });
} }
} }
async updateEntrySeen(req, res) { async updateEntrySeen(req, res) {
const { date_seen, seen_with } = req.body; const { date_seen, seen_with, buddy_ids } = req.body;
const updated = await EntrySeen.update( await EntrySeen.update(
{ date_seen, seen_with }, { date_seen, seen_with },
{ where: { id: req.params.id } }, { where: { id: req.params.id } },
); );
if (updated[0] > 0) { const record = await EntrySeen.findByPk(req.params.id);
const updatedEntrySeen = await EntrySeen.findByPk(req.params.id); if (!record) {
res.status(200).json(updatedEntrySeen); return res.status(404).json({ message: "Entry seen record not found." });
} else {
res.status(404).json({ message: 'Entry seen record not found.' });
} }
if (Array.isArray(buddy_ids)) {
await record.setBuddies(buddy_ids);
}
res.status(200).json(record);
} }
async deleteEntrySeen(req, res) { async deleteEntrySeen(req, res) {
const entrySeen = await EntrySeen.findByPk(req.params.id); const entrySeen = await EntrySeen.findByPk(req.params.id);
if (!entrySeen) if (!entrySeen)
res.status(404).json({ message: 'Entry seen record not found.' }); res.status(404).json({ message: "Entry seen record not found." });
const deleted = await entrySeen.destroy(); const deleted = await entrySeen.destroy();
+34 -26
View File
@@ -1,7 +1,8 @@
const Entry = require('../models/Entry'); const Entry = require("../models/Entry");
const Episode = require('../models/Episode'); const Episode = require("../models/Episode");
const EpisodeSeen = require('../models/EpisodeSeen'); const EpisodeSeen = require("../models/EpisodeSeen");
const Season = require('../models/Season'); const Season = require("../models/Season");
const WatchBuddy = require("../models/WatchBuddy");
class EpisodeSeenController { class EpisodeSeenController {
constructor() { constructor() {
@@ -25,7 +26,7 @@ class EpisodeSeenController {
const episodeSeen = await EpisodeSeen.findByPk(req.params.id); const episodeSeen = await EpisodeSeen.findByPk(req.params.id);
if (!episodeSeen) { if (!episodeSeen) {
res.status(404).json({ message: 'Episode seen record not found.' }); res.status(404).json({ message: "Episode seen record not found." });
} }
res.status(200).json(episodeSeen); res.status(200).json(episodeSeen);
@@ -36,15 +37,15 @@ class EpisodeSeenController {
async createEpisodeSeen(req, res) { async createEpisodeSeen(req, res) {
try { try {
const { entry_id, episode_id, date_seen, seen_with } = req.body; const { entry_id, episode_id, date_seen, seen_with, buddy_ids } =
req.body;
const entry = await Entry.findByPk(entry_id); const entry = await Entry.findByPk(entry_id);
if (!entry) return res.status(404).json({ error: 'Entry not found' }); if (!entry) return res.status(404).json({ error: "Entry not found" });
const episode = await Episode.findByPk(episode_id); const episode = await Episode.findByPk(episode_id);
if (!episode) return res.status(404).json({ error: 'Episode not found' }); if (!episode) return res.status(404).json({ error: "Episode not found" });
// Create a new EpisodeSeen record
const newEpisodeSeen = await EpisodeSeen.create({ const newEpisodeSeen = await EpisodeSeen.create({
entry_id, entry_id,
episode_id, episode_id,
@@ -52,12 +53,17 @@ class EpisodeSeenController {
seen_with, seen_with,
}); });
// Link watch buddies
if (Array.isArray(buddy_ids) && buddy_ids.length > 0) {
await newEpisodeSeen.setBuddies(buddy_ids);
}
// Auto-upgrade: plan_to_watch or null → watching when first episode is marked // Auto-upgrade: plan_to_watch or null → watching when first episode is marked
if ( if (
entry.is_tvseries && entry.is_tvseries &&
(!entry.watch_status || entry.watch_status === 'plan_to_watch') (!entry.watch_status || entry.watch_status === "plan_to_watch")
) { ) {
entry.watch_status = 'watching'; entry.watch_status = "watching";
await entry.save(); await entry.save();
} }
@@ -73,7 +79,8 @@ class EpisodeSeenController {
const { episodeId } = req.params; const { episodeId } = req.params;
const episodeSeens = await EpisodeSeen.findAll({ const episodeSeens = await EpisodeSeen.findAll({
where: { episode_id: episodeId }, where: { episode_id: episodeId },
order: [['date_seen', 'DESC']], order: [["date_seen", "DESC"]],
include: [{ model: WatchBuddy, as: "buddies" }],
}); });
if (episodeSeens.length > 0) { if (episodeSeens.length > 0) {
@@ -81,7 +88,7 @@ class EpisodeSeenController {
} else { } else {
res res
.status(404) .status(404)
.json({ message: 'No records found for the given episode ID.' }); .json({ message: "No records found for the given episode ID." });
} }
} catch (error) { } catch (error) {
res.status(500).json({ error: error.message }); res.status(500).json({ error: error.message });
@@ -99,17 +106,18 @@ class EpisodeSeenController {
include: [ include: [
{ {
model: Season, model: Season,
attributes: ['season_number'], attributes: ["season_number"],
}, },
], ],
attributes: ['episode_number'], attributes: ["episode_number"],
}, },
{ model: WatchBuddy, as: "buddies" },
], ],
order: [ order: [
['date_seen', 'DESC'], ["date_seen", "DESC"],
[{ model: Episode }, { model: Season }, 'season_number', 'DESC'], [{ model: Episode }, { model: Season }, "season_number", "DESC"],
// [Sequelize.literal('"Episode->Season"."season_number"'), 'DESC'], // ! or this // [Sequelize.literal('"Episode->Season"."season_number"'), 'DESC'], // ! or this
[Episode, 'episode_number', 'DESC'], [Episode, "episode_number", "DESC"],
], ],
}); });
@@ -122,21 +130,21 @@ class EpisodeSeenController {
async updateEpisodeSeen(req, res) { async updateEpisodeSeen(req, res) {
try { try {
const { date_seen, seen_with, episode_id } = req.body; const { date_seen, seen_with, episode_id, buddy_ids } = req.body;
const episodeSeen = await EpisodeSeen.findByPk(req.params.id); const episodeSeen = await EpisodeSeen.findByPk(req.params.id);
if (!episodeSeen) if (!episodeSeen)
return res return res
.status(404) .status(404)
.json({ message: 'Episode seen record not found.' }); .json({ message: "Episode seen record not found." });
const updated = await episodeSeen.update({ date_seen, seen_with }); await episodeSeen.update({ date_seen, seen_with });
if (updated) { if (Array.isArray(buddy_ids)) {
res.status(200).json(updated); await episodeSeen.setBuddies(buddy_ids);
} else {
res.status(404).json({ message: 'Episode seen record not found.' });
} }
res.status(200).json(episodeSeen);
} catch (error) { } catch (error) {
res.status(500).json({ error: error.message }); res.status(500).json({ error: error.message });
} }
@@ -147,7 +155,7 @@ class EpisodeSeenController {
// ? getting the episode seen object // ? getting the episode seen object
const oldEpisodeSeen = await EpisodeSeen.findByPk(req.params.id); const oldEpisodeSeen = await EpisodeSeen.findByPk(req.params.id);
if (!oldEpisodeSeen) if (!oldEpisodeSeen)
res.status(404).json({ message: 'Episode seen record not found.' }); res.status(404).json({ message: "Episode seen record not found." });
// ?deleting the episode seen // ?deleting the episode seen
const deleted = await oldEpisodeSeen.destroy(); const deleted = await oldEpisodeSeen.destroy();
+1
View File
@@ -52,6 +52,7 @@ class MediaController {
"seasons", "seasons",
"episodes", "episodes",
"peoples", "peoples",
"watch-buddies",
].includes(category) ].includes(category)
) { ) {
return res.status(404).send("Category Not Found"); return res.status(404).send("Category Not Found");
+205
View File
@@ -0,0 +1,205 @@
const WatchBuddy = require("../models/WatchBuddy");
const EntrySeen = require("../models/EntrySeen");
const EpisodeSeen = require("../models/EpisodeSeen");
const Media = require("../models/Media");
const { Op } = require("sequelize");
const path = require("path");
const fs = require("fs");
const { v4: uuidv4 } = require("uuid");
const configService = require("../services/configService");
const mediaOptimizerService = require("../services/mediaOptimizerService");
class WatchBuddyController {
async search(req, res) {
const { q } = req.query;
const include = [
{
model: Media,
as: "medias",
required: false,
},
];
if (!q) {
const all = await WatchBuddy.findAll({
include,
order: [["name", "ASC"]],
});
return res.json(all);
}
const results = await WatchBuddy.findAll({
where: { name: { [Op.like]: `%${q}%` } },
include,
order: [["name", "ASC"]],
limit: 20,
});
res.json(results);
}
async getById(req, res) {
const buddy = await WatchBuddy.findByPk(req.params.id, {
include: [
{
model: Media,
as: "medias",
required: false,
},
],
});
if (!buddy) return res.status(404).json({ error: "Not found" });
res.json(buddy);
}
async getHistory(req, res) {
const buddy = await WatchBuddy.findByPk(req.params.id, {
include: [
{
model: EntrySeen,
as: "entrySeens",
include: [
{
model: require("../models/Entry"),
as: "entry",
attributes: ["id", "title", "is_tvseries", "poster_path"],
},
],
},
{
model: EpisodeSeen,
as: "episodeSeens",
include: [
{
model: require("../models/Episode"),
attributes: ["name", "episode_number"],
include: [
{
model: require("../models/Season"),
attributes: ["id", "entry_id", "season_number"],
include: [
{
model: require("../models/Entry"),
as: "entry",
attributes: ["id", "title", "poster_path"],
},
],
},
],
},
],
},
],
});
if (!buddy) return res.status(404).json({ error: "Not found" });
res.json({
entrySeens: buddy.entrySeens || [],
episodeSeens: buddy.episodeSeens || [],
});
}
async create(req, res) {
const { name, gender, instagram, discord, phone, email, note, buddy_type } =
req.body;
if (!name) return res.status(400).json({ error: "Name is required" });
const buddy = await WatchBuddy.create({
name,
gender,
instagram,
discord,
phone,
email,
note,
buddy_type,
});
res.status(201).json(buddy);
}
async update(req, res) {
const buddy = await WatchBuddy.findByPk(req.params.id);
if (!buddy) return res.status(404).json({ error: "Not found" });
const { name, gender, instagram, discord, phone, email, note, buddy_type } =
req.body;
await buddy.update({
name,
gender,
instagram,
discord,
phone,
email,
note,
buddy_type,
});
res.json(buddy);
}
async remove(req, res) {
const buddy = await WatchBuddy.findByPk(req.params.id);
if (!buddy) return res.status(404).json({ error: "Not found" });
await buddy.destroy();
res.status(204).send();
}
async uploadProfilePicture(req, res) {
const buddy = await WatchBuddy.findByPk(req.params.id);
if (!buddy) return res.status(404).json({ error: "Not found" });
if (!req.file) {
return res.status(400).json({ error: "No file uploaded" });
}
const settings = configService.getSettings();
const dataPath = settings.userDataPath;
const dir = path.join(dataPath, "images", "watch-buddies", "profiles");
fs.mkdirSync(dir, { recursive: true });
const ext = path.extname(req.file.originalname);
const fileName = `${uuidv4()}${ext}`;
const destPath = path.join(dir, fileName);
fs.copyFileSync(req.file.path, destPath);
fs.unlinkSync(req.file.path); // remove temp file
// Generate preview
try {
await mediaOptimizerService.doGeneratePreview(
"watch-buddies",
"profiles",
fileName,
);
} catch {
// preview generation failure is non-fatal
}
// Delete old profile picture if exists
const oldMedia = await Media.findOne({
where: {
mediaable: "watch_buddy",
mediaableId: buddy.id,
type: "profiles",
},
});
if (oldMedia) {
const oldPath = path.join(dir, oldMedia.path);
const previewName = oldMedia.path.split(".")[0] + "_preview.jpg";
try {
fs.unlinkSync(oldPath);
} catch {}
try {
fs.unlinkSync(path.join(dir, previewName));
} catch {}
await oldMedia.destroy();
}
const media = await Media.create({
mediaable: "watch_buddy",
mediaableId: buddy.id,
type: "profiles",
path: fileName,
isLocal: true,
isCustom: true,
isSelected: true,
});
res.json({ media });
}
}
module.exports = new WatchBuddyController();
+12 -8
View File
@@ -1,25 +1,29 @@
const jwt = require('jsonwebtoken'); const jwt = require("jsonwebtoken");
const configService = require('../services/configService'); const configService = require("../services/configService");
function authMiddleware(req, res, next) { function authMiddleware(req, res, next) {
// Skip auth for login/verify endpoints // Skip auth for login/verify/media endpoints
if (req.path === '/auth/login' || req.path === '/auth/verify') { if (
req.path === "/auth/login" ||
req.path === "/auth/verify" ||
req.path.startsWith("/media/")
) {
return next(); return next();
} }
const auth = req.headers.authorization; const auth = req.headers.authorization;
if (!auth || !auth.startsWith('Bearer ')) { if (!auth || !auth.startsWith("Bearer ")) {
return res.status(401).json({ error: 'Authentication required' }); return res.status(401).json({ error: "Authentication required" });
} }
const settings = configService.getSettings(); const settings = configService.getSettings();
const jwtSecret = settings.jwtSecret || 'showy-default-secret'; const jwtSecret = settings.jwtSecret || "showy-default-secret";
try { try {
jwt.verify(auth.slice(7), jwtSecret); jwt.verify(auth.slice(7), jwtSecret);
next(); next();
} catch { } catch {
return res.status(401).json({ error: 'Invalid or expired token' }); return res.status(401).json({ error: "Invalid or expired token" });
} }
} }
+10
View File
@@ -0,0 +1,10 @@
const { DataTypes } = require('sequelize');
const sequelize = require('../config/database');
const EntrySeenBuddy = sequelize.define('entry_seen_buddy', {
id: { type: DataTypes.INTEGER, primaryKey: true, autoIncrement: true },
entry_seen_id: { type: DataTypes.INTEGER, allowNull: false },
watch_buddy_id: { type: DataTypes.INTEGER, allowNull: false },
});
module.exports = EntrySeenBuddy;
+10
View File
@@ -0,0 +1,10 @@
const { DataTypes } = require('sequelize');
const sequelize = require('../config/database');
const EpisodeSeenBuddy = sequelize.define('episode_seen_buddy', {
id: { type: DataTypes.INTEGER, primaryKey: true, autoIncrement: true },
episode_seen_id: { type: DataTypes.INTEGER, allowNull: false },
watch_buddy_id: { type: DataTypes.INTEGER, allowNull: false },
});
module.exports = EpisodeSeenBuddy;
+20
View File
@@ -0,0 +1,20 @@
const { DataTypes } = require("sequelize");
const sequelize = require("../config/database");
const WatchBuddy = sequelize.define("watch_buddy", {
id: { type: DataTypes.INTEGER, primaryKey: true, autoIncrement: true },
name: { type: DataTypes.STRING(100), allowNull: false },
gender: { type: DataTypes.STRING(20), allowNull: true },
instagram: { type: DataTypes.STRING(100), allowNull: true },
discord: { type: DataTypes.STRING(100), allowNull: true },
phone: { type: DataTypes.STRING(30), allowNull: true },
email: { type: DataTypes.STRING(100), allowNull: true },
note: { type: DataTypes.STRING(2000), allowNull: true },
buddy_type: {
type: DataTypes.STRING(20),
defaultValue: "person",
allowNull: false,
},
});
module.exports = WatchBuddy;
+1 -1
View File
@@ -4,7 +4,7 @@
"description": "", "description": "",
"main": "server.js", "main": "server.js",
"scripts": { "scripts": {
"backend": "nodemon server.js --trace-warnings", "dev": "nodemon server.js --trace-warnings",
"package": "pkg server.js --output ../dist/backend/backend --targets node18-win-x64" "package": "pkg server.js --output ../dist/backend/backend --targets node18-win-x64"
}, },
"pkg": { "pkg": {
+2
View File
@@ -14,9 +14,11 @@ const importRouter = require('./import.routes');
const peopleRouter = require('./people.routes'); const peopleRouter = require('./people.routes');
const aiQueryRouter = require('./ai-query.routes'); const aiQueryRouter = require('./ai-query.routes');
const authRouter = require('./auth.routes'); const authRouter = require('./auth.routes');
const watchBuddyRouter = require('./watch-buddy.routes');
const router = express.Router(); const router = express.Router();
router.use('/auth', authRouter); router.use('/auth', authRouter);
router.use('/watch-buddies', watchBuddyRouter);
router.use('/media', mediaRouter); router.use('/media', mediaRouter);
router.use('/entries', entryRouter); router.use('/entries', entryRouter);
router.use('/collections', collectionRouter); router.use('/collections', collectionRouter);
+19
View File
@@ -0,0 +1,19 @@
const express = require("express");
const router = express.Router();
const multer = require("multer");
const upload = multer({ dest: require("os").tmpdir() });
const ctrl = require("../controllers/watchBuddyController");
router.get("/search", ctrl.search);
router.get("/:id/history", ctrl.getHistory);
router.get("/:id", ctrl.getById);
router.post("/", ctrl.create);
router.put("/:id", ctrl.update);
router.delete("/:id", ctrl.remove);
router.post(
"/:id/profile-picture",
upload.single("file"),
ctrl.uploadProfilePicture,
);
module.exports = router;
+28 -28
View File
@@ -1,37 +1,37 @@
const express = require('express'); const express = require("express");
const bodyParser = require('body-parser'); const bodyParser = require("body-parser");
const routes = require('./routes/routes.js'); const routes = require("./routes/routes.js");
const sequelize = require('./config/database.js'); const sequelize = require("./config/database.js");
const app = express(); const app = express();
// Global error handling for unhandled promise rejections // Global error handling for unhandled promise rejections
process.on('unhandledRejection', (reason, promise) => { process.on("unhandledRejection", (reason, promise) => {
console.log('Unhandled Rejection at:', promise, 'reason:', reason); console.log("Unhandled Rejection at:", promise, "reason:", reason);
// Application specific logging, throwing an error, or other logic here // Application specific logging, throwing an error, or other logic here
}); });
// Global error handling for uncaught exceptions // Global error handling for uncaught exceptions
process.on('uncaughtException', (error) => { process.on("uncaughtException", (error) => {
console.log('Uncaught Exception:', error); console.log("Uncaught Exception:", error);
// Application specific logging, throwing an error, or other logic here // Application specific logging, throwing an error, or other logic here
process.exit(1); // Exit the process to avoid undefined state process.exit(1); // Exit the process to avoid undefined state
}); });
const relations = require('./config/relations.js'); const relations = require("./config/relations.js");
const sequelizeHooks = require('./config/sequelizeHooks.js'); const sequelizeHooks = require("./config/sequelizeHooks.js");
const { initializeData } = require('./config/dataInitializer.js'); const { initializeData } = require("./config/dataInitializer.js");
const killerRouter = require('./routes/killer.routes.js'); const killerRouter = require("./routes/killer.routes.js");
const errorHandler = require('./middleware/errorHandler'); const errorHandler = require("./middleware/errorHandler");
const authMiddleware = require('./middleware/authMiddleware'); const authMiddleware = require("./middleware/authMiddleware");
const configService = require('./services/configService.js'); const configService = require("./services/configService.js");
const { logToFile } = require('./services/logService.js'); const { logToFile } = require("./services/logService.js");
const { generatePreview } = require('./services/mediaService.js'); const { generatePreview } = require("./services/mediaService.js");
// ? variables // ? variables
let settings = configService.getSettings(); let settings = configService.getSettings();
const PORT = settings['backPort'] || 4000; const PORT = settings["backPort"] || 4000;
const parrentProcess = JSON.parse(process.env.PARENT_PROCESS || '{}'); const parrentProcess = JSON.parse(process.env.PARENT_PROCESS || "{}");
// ? Middleware // ? Middleware
app.use(bodyParser.json()); // for parsing application/json app.use(bodyParser.json()); // for parsing application/json
@@ -39,31 +39,31 @@ app.use(bodyParser.urlencoded({ extended: true })); // for parsing application/x
// * CORS Middleware to allow requests from any origin // * CORS Middleware to allow requests from any origin
app.use((req, res, next) => { app.use((req, res, next) => {
res.header('Access-Control-Allow-Origin', '*'); res.header("Access-Control-Allow-Origin", "*");
res.header( res.header(
'Access-Control-Allow-Headers', "Access-Control-Allow-Headers",
'Origin, X-Requested-With, Content-Type, Accept, Authorization', "Origin, X-Requested-With, Content-Type, Accept, Authorization",
); );
if (req.method === 'OPTIONS') { if (req.method === "OPTIONS") {
res.header('Access-Control-Allow-Methods', 'PUT, POST, PATCH, DELETE, GET'); res.header("Access-Control-Allow-Methods", "PUT, POST, PATCH, DELETE, GET");
return res.status(200).json({}); return res.status(200).json({});
} }
next(); next();
}); });
// ? other api routes // ? other api routes
app.use('/api/v1', authMiddleware, routes); app.use("/api/v1", authMiddleware, routes);
// ? Error handling middleware // ? Error handling middleware
app.use(errorHandler); app.use(errorHandler);
// ? KILLER ROUTE: used to crash the backend // ? KILLER ROUTE: used to crash the backend
app.use('/killer', killerRouter); app.use("/killer", killerRouter);
// * Start the server // * Start the server
const doUpdate = false; const doUpdate = false;
const doForce = false; const doForce = false;
console.log('Server started'); console.log("Server started");
console.log(`Syncing database schema...`); console.log(`Syncing database schema...`);
sequelize sequelize
// .sync({force: true}) // will drop all tables and recreate them. // .sync({force: true}) // will drop all tables and recreate them.
@@ -77,6 +77,6 @@ sequelize
}); });
}) })
.catch((err) => { .catch((err) => {
console.log('____________SEQUELIZE SYNC ERROR____________'); console.log("____________SEQUELIZE SYNC ERROR____________");
console.log(err); console.log(err);
}); });
+5015
View File
File diff suppressed because it is too large. Load diff
+12 -12
View File
@@ -1,4 +1,4 @@
import { api } from '@/lib/api'; import { api } from "@/lib/api";
export interface OrphanResult { export interface OrphanResult {
posters: number; posters: number;
@@ -13,39 +13,39 @@ export interface OrphanPeopleResult {
export const maintenanceApi = { export const maintenanceApi = {
scanOrphanFiles: () => scanOrphanFiles: () =>
api.get<OrphanResult>('/maintenance/orphan-files').then((r) => r.data), api.get<OrphanResult>("/maintenance/orphan-files").then((r) => r.data),
deleteOrphanFiles: () => deleteOrphanFiles: () =>
api.delete<OrphanResult>('/maintenance/orphan-files').then((r) => r.data), api.delete<OrphanResult>("/maintenance/orphan-files").then((r) => r.data),
scanOrphanMediaRecords: () => scanOrphanMediaRecords: () =>
api api
.get<OrphanResult>('/maintenance/orphan-media-records') .get<OrphanResult>("/maintenance/orphan-media-records")
.then((r) => r.data), .then((r) => r.data),
deleteOrphanMediaRecords: () => deleteOrphanMediaRecords: () =>
api api
.delete<OrphanResult>('/maintenance/orphan-media-records') .delete<OrphanResult>("/maintenance/orphan-media-records")
.then((r) => r.data), .then((r) => r.data),
scanOrphanPeople: () => scanOrphanPeople: () =>
api api
.get<OrphanPeopleResult>('/maintenance/orphan-people') .get<OrphanPeopleResult>("/maintenance/orphan-people")
.then((r) => r.data), .then((r) => r.data),
deleteOrphanPeople: () => deleteOrphanPeople: () =>
api api
.delete<OrphanPeopleResult>('/maintenance/orphan-people') .delete<OrphanPeopleResult>("/maintenance/orphan-people")
.then((r) => r.data), .then((r) => r.data),
scanMissingDirectors: () => scanMissingDirectors: () =>
api api
.get<{ count: number; fixed: number }>('/maintenance/missing-directors') .get<{ count: number; fixed: number }>("/maintenance/missing-directors")
.then((r) => r.data), .then((r) => r.data),
fixMissingDirectors: () => fixMissingDirectors: () =>
api api
.post<{ count: number; fixed: number }>('/maintenance/missing-directors') .post<{ count: number; fixed: number }>("/maintenance/missing-directors")
.then((r) => r.data), .then((r) => r.data),
scanDuplicateCredits: () => scanDuplicateCredits: () =>
@@ -54,7 +54,7 @@ export const maintenanceApi = {
groups: number; groups: number;
duplicates: number; duplicates: number;
deleted: number; deleted: number;
}>('/maintenance/duplicate-credits') }>("/maintenance/duplicate-credits")
.then((r) => r.data), .then((r) => r.data),
cleanDuplicateCredits: () => cleanDuplicateCredits: () =>
@@ -63,7 +63,7 @@ export const maintenanceApi = {
groups: number; groups: number;
duplicates: number; duplicates: number;
deleted: number; deleted: number;
}>('/maintenance/duplicate-credits') }>("/maintenance/duplicate-credits")
.then((r) => r.data), .then((r) => r.data),
autoFixWatchStatuses: () => autoFixWatchStatuses: () =>
@@ -72,6 +72,6 @@ export const maintenanceApi = {
completed: number; completed: number;
watching: number; watching: number;
planToWatch: number; planToWatch: number;
}>('/maintenance/auto-fix-watch-statuses') }>("/maintenance/auto-fix-watch-statuses")
.then((r) => r.data), .then((r) => r.data),
}; };
+34
View File
@@ -0,0 +1,34 @@
import { api } from "@/lib/api";
import type { WatchBuddy } from "@/types";
export const watchBuddyApi = {
search: (q?: string) =>
api
.get<WatchBuddy[]>("/watch-buddies/search", { params: { q } })
.then((r) => r.data),
getById: (id: number) =>
api.get<WatchBuddy>(`/watch-buddies/${id}`).then((r) => r.data),
getHistory: (id: number) =>
api.get<any>(`/watch-buddies/${id}/history`).then((r) => r.data),
create: (data: Partial<WatchBuddy>) =>
api.post<WatchBuddy>("/watch-buddies", data).then((r) => r.data),
update: (id: number, data: Partial<WatchBuddy>) =>
api.put<WatchBuddy>(`/watch-buddies/${id}`, data).then((r) => r.data),
remove: (id: number) =>
api.delete(`/watch-buddies/${id}`).then((r) => r.data),
uploadProfilePicture: (id: number, file: File) => {
const formData = new FormData();
formData.append("file", file);
return api
.post(`/watch-buddies/${id}/profile-picture`, formData, {
headers: { "Content-Type": "multipart/form-data" },
})
.then((r) => r.data);
},
};
@@ -1,36 +1,36 @@
import { useState } from 'react'; import { useState } from "react";
import { useForm } from 'react-hook-form'; import { useForm } from "react-hook-form";
import { zodResolver } from '@hookform/resolvers/zod'; import { zodResolver } from "@hookform/resolvers/zod";
import { z } from 'zod'; import { z } from "zod";
import { format } from 'date-fns'; import { format } from "date-fns";
import { Loader2 } from 'lucide-react'; import { Loader2 } from "lucide-react";
import { import {
Dialog, Dialog,
DialogContent, DialogContent,
DialogFooter, DialogFooter,
DialogHeader, DialogHeader,
DialogTitle, DialogTitle,
} from '@/components/ui/dialog'; } from "@/components/ui/dialog";
import { Button } from '@/components/ui/button'; import { Button } from "@/components/ui/button";
import { Input } from '@/components/ui/input'; import { Input } from "@/components/ui/input";
import { Label } from '@/components/ui/label'; import { Label } from "@/components/ui/label";
import { import {
Select, Select,
SelectContent, SelectContent,
SelectItem, SelectItem,
SelectTrigger, SelectTrigger,
SelectValue, SelectValue,
} from '@/components/ui/select'; } from "@/components/ui/select";
import { useCreateEntrySeen, useUpdateEntrySeen } from '@/hooks/useEntrySeen'; import { useCreateEntrySeen, useUpdateEntrySeen } from "@/hooks/useEntrySeen";
import { useCreateEpisodeSeen } from '@/hooks/useEpisodeSeen'; import { useCreateEpisodeSeen } from "@/hooks/useEpisodeSeen";
import type { Entry, Season, EntrySeen, SeenAccuracy } from '@/types'; import { WatchBuddySelect } from "@/components/watch-buddy/WatchBuddySelect";
import type { Entry, Season, EntrySeen, SeenAccuracy } from "@/types";
const seenSchema = z.object({ const seenSchema = z.object({
season_id: z.string().optional(), season_id: z.string().optional(),
episode_id: z.string().optional(), episode_id: z.string().optional(),
date_seen: z.string().min(1, 'Date is required'), date_seen: z.string().min(1, "Date is required"),
seen_with: z.string().optional(), accuracy: z.enum(["EXACT", "ESTIMATED", "UNKNOWN"]).default("EXACT"),
accuracy: z.enum(['EXACT', 'ESTIMATED', 'UNKNOWN']).default('EXACT'),
}); });
interface EntrySeenDialogProps { interface EntrySeenDialogProps {
@@ -38,7 +38,7 @@ interface EntrySeenDialogProps {
onOpenChange: (open: boolean) => void; onOpenChange: (open: boolean) => void;
entry: Entry; entry: Entry;
seasons?: Season[]; seasons?: Season[];
mode: 'add' | 'edit'; mode: "add" | "edit";
editRecord?: EntrySeen; editRecord?: EntrySeen;
} }
@@ -50,7 +50,10 @@ export function EntrySeenDialog({
mode, mode,
editRecord, editRecord,
}: EntrySeenDialogProps) { }: EntrySeenDialogProps) {
const [selectedSeasonId, setSelectedSeasonId] = useState<string>(''); const [selectedSeasonId, setSelectedSeasonId] = useState<string>("");
const [buddyIds, setBuddyIds] = useState<number[]>(
editRecord?.buddies?.map((b) => b.id) ?? [],
);
const isTV = entry.is_tvseries; const isTV = entry.is_tvseries;
const seasonList = Array.isArray(seasons) ? seasons : []; const seasonList = Array.isArray(seasons) ? seasons : [];
@@ -64,15 +67,19 @@ export function EntrySeenDialog({
} = useForm({ } = useForm({
resolver: zodResolver(seenSchema), resolver: zodResolver(seenSchema),
defaultValues: { defaultValues: {
date_seen: editRecord?.date_seen || format(new Date(), 'yyyy-MM-dd'), date_seen:
seen_with: editRecord?.seen_with || '', editRecord?.date_seen?.split("T")[0] ||
season_id: '', format(new Date(), "yyyy-MM-dd"),
episode_id: '', date_seen:
accuracy: (editRecord?.accuracy || 'EXACT') as SeenAccuracy, editRecord?.date_seen?.split("T")[0] ||
format(new Date(), "yyyy-MM-dd"),
season_id: "",
episode_id: "",
accuracy: (editRecord?.accuracy || "EXACT") as SeenAccuracy,
}, },
}); });
const accuracyValue = watch('accuracy') as SeenAccuracy; const accuracyValue = watch("accuracy") as SeenAccuracy;
const createEntrySeen = useCreateEntrySeen(); const createEntrySeen = useCreateEntrySeen();
const updateEntrySeen = useUpdateEntrySeen(); const updateEntrySeen = useUpdateEntrySeen();
@@ -83,27 +90,28 @@ export function EntrySeenDialog({
); );
const onSubmit = (data: Record<string, string | undefined>) => { const onSubmit = (data: Record<string, string | undefined>) => {
const acc = (data.accuracy as SeenAccuracy) || 'EXACT'; const acc = (data.accuracy as SeenAccuracy) || "EXACT";
const buddyIdsToSend = buddyIds;
if (isTV && data.episode_id) { if (isTV && data.episode_id) {
createEpisodeSeen.mutate( createEpisodeSeen.mutate(
{ {
entry_id: entry.id, entry_id: entry.id,
episode_id: parseInt(data.episode_id), episode_id: parseInt(data.episode_id),
date_seen: data.date_seen!, date_seen: data.date_seen!,
seen_with: data.seen_with || undefined,
accuracy: acc, accuracy: acc,
buddy_ids: buddyIdsToSend,
}, },
{ onSuccess: () => onOpenChange(false) }, { onSuccess: () => onOpenChange(false) },
); );
} else if (mode === 'edit' && editRecord) { } else if (mode === "edit" && editRecord) {
updateEntrySeen.mutate( updateEntrySeen.mutate(
{ {
id: editRecord.id, id: editRecord.id,
data: { data: {
entry_id: entry.id, entry_id: entry.id,
date_seen: data.date_seen, date_seen: data.date_seen,
seen_with: data.seen_with || undefined,
accuracy: acc, accuracy: acc,
buddy_ids: buddyIdsToSend,
}, },
}, },
{ onSuccess: () => onOpenChange(false) }, { onSuccess: () => onOpenChange(false) },
@@ -113,8 +121,8 @@ export function EntrySeenDialog({
{ {
entry_id: entry.id, entry_id: entry.id,
date_seen: data.date_seen!, date_seen: data.date_seen!,
seen_with: data.seen_with || undefined,
accuracy: acc, accuracy: acc,
buddy_ids: buddyIdsToSend,
}, },
{ onSuccess: () => onOpenChange(false) }, { onSuccess: () => onOpenChange(false) },
); );
@@ -126,7 +134,7 @@ export function EntrySeenDialog({
<DialogContent className="sm:max-w-md"> <DialogContent className="sm:max-w-md">
<DialogHeader> <DialogHeader>
<DialogTitle> <DialogTitle>
{mode === 'edit' ? 'Edit Watch Record' : 'Mark as Watched'} {mode === "edit" ? "Edit Watch Record" : "Mark as Watched"}
</DialogTitle> </DialogTitle>
</DialogHeader> </DialogHeader>
<form onSubmit={handleSubmit(onSubmit)} className="space-y-4 py-2"> <form onSubmit={handleSubmit(onSubmit)} className="space-y-4 py-2">
@@ -140,8 +148,8 @@ export function EntrySeenDialog({
value={selectedSeasonId} value={selectedSeasonId}
onValueChange={(v) => { onValueChange={(v) => {
setSelectedSeasonId(v); setSelectedSeasonId(v);
setValue('season_id', v); setValue("season_id", v);
setValue('episode_id', ''); setValue("episode_id", "");
}} }}
> >
<SelectTrigger className="w-full"> <SelectTrigger className="w-full">
@@ -152,7 +160,7 @@ export function EntrySeenDialog({
(s) => s.id.toString() === selectedSeasonId, (s) => s.id.toString() === selectedSeasonId,
); );
return s?.season_number === 0 return s?.season_number === 0
? 'Specials' ? "Specials"
: `Season ${s?.season_number}`; : `Season ${s?.season_number}`;
})() })()
: null} : null}
@@ -168,7 +176,7 @@ export function EntrySeenDialog({
.map((s) => ( .map((s) => (
<SelectItem key={s.id} value={s.id.toString()}> <SelectItem key={s.id} value={s.id.toString()}>
{s.season_number === 0 {s.season_number === 0
? 'Specials' ? "Specials"
: `Season ${s.season_number}`} : `Season ${s.season_number}`}
</SelectItem> </SelectItem>
))} ))}
@@ -179,14 +187,14 @@ export function EntrySeenDialog({
<div className="space-y-2"> <div className="space-y-2">
<Label>Episode</Label> <Label>Episode</Label>
<Select <Select
value={watch('episode_id')} value={watch("episode_id")}
onValueChange={(v) => setValue('episode_id', v)} onValueChange={(v) => setValue("episode_id", v)}
disabled={!selectedSeason} disabled={!selectedSeason}
> >
<SelectTrigger className="w-full"> <SelectTrigger className="w-full">
<SelectValue placeholder="Select episode"> <SelectValue placeholder="Select episode">
{(() => { {(() => {
const epId = watch('episode_id'); const epId = watch("episode_id");
if (!epId || !selectedSeason?.episodes) return null; if (!epId || !selectedSeason?.episodes) return null;
const ep = selectedSeason.episodes.find( const ep = selectedSeason.episodes.find(
(e) => e.id.toString() === epId, (e) => e.id.toString() === epId,
@@ -227,9 +235,9 @@ export function EntrySeenDialog({
<Label>Date Seen</Label> <Label>Date Seen</Label>
<Input <Input
type="date" type="date"
value={watch('date_seen')} value={watch("date_seen")}
onChange={(e) => { onChange={(e) => {
setValue('date_seen', e.target.value); setValue("date_seen", e.target.value);
}} }}
/> />
</div> </div>
@@ -237,7 +245,7 @@ export function EntrySeenDialog({
<Label>Accuracy</Label> <Label>Accuracy</Label>
<Select <Select
value={accuracyValue} value={accuracyValue}
onValueChange={(v) => setValue('accuracy', v as SeenAccuracy)} onValueChange={(v) => setValue("accuracy", v as SeenAccuracy)}
> >
<SelectTrigger className="w-full"> <SelectTrigger className="w-full">
<SelectValue /> <SelectValue />
@@ -258,11 +266,11 @@ export function EntrySeenDialog({
{/* Seen with */} {/* Seen with */}
<div className="space-y-2"> <div className="space-y-2">
<Label htmlFor="seen_with">Seen With (optional)</Label> <Label>Seen With</Label>
<Input <WatchBuddySelect
id="seen_with" selectedIds={buddyIds}
{...register('seen_with')} onChange={setBuddyIds}
placeholder="e.g. John, Jane" initialBuddies={editRecord?.buddies}
/> />
</div> </div>
@@ -292,7 +300,7 @@ export function EntrySeenDialog({
createEpisodeSeen.isPending) && ( createEpisodeSeen.isPending) && (
<Loader2 className="mr-2 h-4 w-4 animate-spin" /> <Loader2 className="mr-2 h-4 w-4 animate-spin" />
)} )}
{mode === 'edit' ? 'Save Changes' : 'Mark as Watched'} {mode === "edit" ? "Save Changes" : "Mark as Watched"}
</Button> </Button>
</DialogFooter> </DialogFooter>
</form> </form>
@@ -20,6 +20,7 @@ import {
useUpdateEpisodeSeen, useUpdateEpisodeSeen,
useCreateEpisodeSeen, useCreateEpisodeSeen,
} from "@/hooks/useEpisodeSeen"; } from "@/hooks/useEpisodeSeen";
import { WatchBuddySelect } from "@/components/watch-buddy/WatchBuddySelect";
import type { EpisodeSeen, SeenAccuracy } from "@/types"; import type { EpisodeSeen, SeenAccuracy } from "@/types";
interface EpisodeSeenEditDialogProps { interface EpisodeSeenEditDialogProps {
@@ -52,7 +53,9 @@ export function EpisodeSeenEditDialog({
}: EpisodeSeenEditDialogProps) { }: EpisodeSeenEditDialogProps) {
const today = new Date().toISOString().split("T")[0]; const today = new Date().toISOString().split("T")[0];
const [date, setDate] = useState(record?.date_seen?.split("T")[0] ?? today); const [date, setDate] = useState(record?.date_seen?.split("T")[0] ?? today);
const [seenWith, setSeenWith] = useState(record?.seen_with ?? ""); const [buddyIds, setBuddyIds] = useState<number[]>(
record?.buddies?.map((b) => b.id) ?? [],
);
const [accuracy, setAccuracy] = useState<SeenAccuracy>( const [accuracy, setAccuracy] = useState<SeenAccuracy>(
record?.accuracy ?? "EXACT", record?.accuracy ?? "EXACT",
); );
@@ -62,9 +65,10 @@ export function EpisodeSeenEditDialog({
const handleSave = () => { const handleSave = () => {
if (overrideSubmit) { if (overrideSubmit) {
overrideSubmit(date, seenWith, accuracy); overrideSubmit(date, "", accuracy);
return; return;
} }
const buddyIdsToSend = buddyIds;
if (mode === "edit" && record) { if (mode === "edit" && record) {
updateEpisodeSeen.mutate({ updateEpisodeSeen.mutate({
id: record.id, id: record.id,
@@ -72,8 +76,8 @@ export function EpisodeSeenEditDialog({
episode_id: record.episode_id, episode_id: record.episode_id,
entry_id: entryId, entry_id: entryId,
date_seen: date, date_seen: date,
seen_with: seenWith || null,
accuracy, accuracy,
buddy_ids: buddyIdsToSend,
}, },
}); });
} else { } else {
@@ -83,9 +87,9 @@ export function EpisodeSeenEditDialog({
entry_id: entryId, entry_id: entryId,
episode_id: epId, episode_id: epId,
date_seen: date, date_seen: date,
seen_with: seenWith || undefined,
accuracy, accuracy,
season_id: seasonId, season_id: seasonId,
buddy_ids: buddyIdsToSend,
}); });
} }
onOpenChange(false); onOpenChange(false);
@@ -126,12 +130,11 @@ export function EpisodeSeenEditDialog({
</div> </div>
</div> </div>
<div className="space-y-1.5"> <div className="space-y-1.5">
<Label htmlFor="seen-with">Seen With</Label> <Label>Seen With</Label>
<Input <WatchBuddySelect
id="seen-with" selectedIds={buddyIds}
value={seenWith} onChange={setBuddyIds}
onChange={(e) => setSeenWith(e.target.value)} initialBuddies={record?.buddies}
placeholder="Optional"
/> />
</div> </div>
</div> </div>
@@ -1,4 +1,5 @@
import { format } from "date-fns"; import { format } from "date-fns";
import { Link } from "react-router-dom";
import { import {
Dialog, Dialog,
DialogContent, DialogContent,
@@ -6,7 +7,8 @@ import {
DialogTitle, DialogTitle,
} from "@/components/ui/dialog"; } from "@/components/ui/dialog";
import { Button } from "@/components/ui/button"; import { Button } from "@/components/ui/button";
import { Trash2 } from "lucide-react"; import { Badge } from "@/components/ui/badge";
import { Trash2, Pencil, Users } from "lucide-react";
import type { EntrySeen } from "@/types"; import type { EntrySeen } from "@/types";
interface MovieWatchHistoryDialogProps { interface MovieWatchHistoryDialogProps {
@@ -15,6 +17,7 @@ interface MovieWatchHistoryDialogProps {
entryId: number; entryId: number;
watchHistory: EntrySeen[]; watchHistory: EntrySeen[];
onDelete: (seenId: number) => void; onDelete: (seenId: number) => void;
onEdit?: (record: EntrySeen) => void;
} }
export function MovieWatchHistoryDialog({ export function MovieWatchHistoryDialog({
@@ -22,15 +25,16 @@ export function MovieWatchHistoryDialog({
onOpenChange, onOpenChange,
watchHistory, watchHistory,
onDelete, onDelete,
onEdit,
}: MovieWatchHistoryDialogProps) { }: MovieWatchHistoryDialogProps) {
return ( return (
<Dialog open={open} onOpenChange={onOpenChange}> <Dialog open={open} onOpenChange={onOpenChange}>
<DialogContent className="sm:max-w-md"> <DialogContent className="sm:max-w-lg">
<DialogHeader> <DialogHeader>
<DialogTitle>Watch History</DialogTitle> <DialogTitle>Watch History</DialogTitle>
</DialogHeader> </DialogHeader>
{watchHistory.length === 0 ? ( {watchHistory.length === 0 ? (
<p className="text-sm text-muted-foreground py-4"> <p className="py-4 text-sm text-muted-foreground">
No watch history yet. No watch history yet.
</p> </p>
) : ( ) : (
@@ -39,7 +43,12 @@ export function MovieWatchHistoryDialog({
<thead> <thead>
<tr className="border-b border-border bg-muted/50"> <tr className="border-b border-border bg-muted/50">
<th className="px-4 py-2 text-left font-medium">Date</th> <th className="px-4 py-2 text-left font-medium">Date</th>
<th className="px-4 py-2 text-left font-medium">Seen With</th> <th className="px-4 py-2 text-left font-medium">
<span className="flex items-center gap-1">
<Users className="h-3 w-3" />
Buddies
</span>
</th>
<th className="px-4 py-2 text-right font-medium">Actions</th> <th className="px-4 py-2 text-right font-medium">Actions</th>
</tr> </tr>
</thead> </thead>
@@ -54,11 +63,36 @@ export function MovieWatchHistoryDialog({
? format(new Date(record.date_seen), "MMM d, yyyy") ? format(new Date(record.date_seen), "MMM d, yyyy")
: "-"} : "-"}
</td> </td>
<td className="px-4 py-2 text-muted-foreground"> <td className="px-4 py-2">
{record.seen_with || "-"} <div className="flex flex-wrap gap-1">
{record.buddies && record.buddies.length > 0 ? (
record.buddies.map((b) => (
<Link key={b.id} to={`/watch-buddies/${b.id}`}>
<Badge
variant="secondary"
className="text-xs hover:bg-accent cursor-pointer"
>
{b.name}
</Badge>
</Link>
))
) : (
<span className="text-muted-foreground">-</span>
)}
</div>
</td> </td>
<td className="px-4 py-2"> <td className="px-4 py-2">
<div className="flex justify-end"> <div className="flex justify-end gap-1">
{onEdit && (
<Button
size="icon"
variant="ghost"
className="h-7 w-7"
onClick={() => onEdit(record)}
>
<Pencil className="h-3 w-3" />
</Button>
)}
<Button <Button
size="icon" size="icon"
variant="ghost" variant="ghost"
@@ -1,7 +1,9 @@
import { format } from "date-fns"; import { format } from "date-fns";
import { Link } from "react-router-dom";
import type { EntrySeen, EpisodeSeen } from "@/types"; import type { EntrySeen, EpisodeSeen } from "@/types";
import { Button } from "@/components/ui/button"; import { Button } from "@/components/ui/button";
import { Pencil, Trash2 } from "lucide-react"; import { Badge } from "@/components/ui/badge";
import { Pencil, Trash2, Users } from "lucide-react";
interface EpisodeWatchHistoryProps { interface EpisodeWatchHistoryProps {
watchHistory: (EntrySeen | EpisodeSeen)[]; watchHistory: (EntrySeen | EpisodeSeen)[];
@@ -28,7 +30,12 @@ export function EpisodeWatchHistory({
<thead> <thead>
<tr className="border-b border-border bg-muted/50"> <tr className="border-b border-border bg-muted/50">
<th className="px-4 py-2 text-left font-medium">Date</th> <th className="px-4 py-2 text-left font-medium">Date</th>
<th className="px-4 py-2 text-left font-medium">Seen With</th> <th className="px-4 py-2 text-left font-medium">
<span className="flex items-center gap-1">
<Users className="h-3 w-3" />
Buddies
</span>
</th>
<th className="px-4 py-2 text-right font-medium">Actions</th> <th className="px-4 py-2 text-right font-medium">Actions</th>
</tr> </tr>
</thead> </thead>
@@ -43,8 +50,23 @@ export function EpisodeWatchHistory({
? format(new Date(record.date_seen), "MMM d, yyyy") ? format(new Date(record.date_seen), "MMM d, yyyy")
: "-"} : "-"}
</td> </td>
<td className="px-4 py-2 text-muted-foreground"> <td className="px-4 py-2">
{record.seen_with || "-"} <div className="flex flex-wrap gap-1">
{record.buddies && record.buddies.length > 0 ? (
record.buddies.map((b) => (
<Link key={b.id} to={`/watch-buddies/${b.id}`}>
<Badge
variant="secondary"
className="cursor-pointer text-xs hover:bg-accent"
>
{b.name}
</Badge>
</Link>
))
) : (
<span className="text-muted-foreground">-</span>
)}
</div>
</td> </td>
<td className="px-4 py-2"> <td className="px-4 py-2">
<div className="flex justify-end gap-1"> <div className="flex justify-end gap-1">
@@ -8,6 +8,7 @@ import {
Image, Image,
CalendarDays, CalendarDays,
Users, Users,
UserRoundPlus,
Settings, Settings,
Moon, Moon,
Sun, Sun,
@@ -31,6 +32,7 @@ const libraryNav = [
const otherNav = [ const otherNav = [
{ to: "/calendar", icon: CalendarDays, label: "Calendar" }, { to: "/calendar", icon: CalendarDays, label: "Calendar" },
{ to: "/people", icon: Users, label: "People" }, { to: "/people", icon: Users, label: "People" },
{ to: "/watch-buddies", icon: UserRoundPlus, label: "Buddies" },
]; ];
function NavItem({ function NavItem({
@@ -0,0 +1,178 @@
import { useState, useEffect, useRef } from "react";
import { useQuery, useQueryClient } from "@tanstack/react-query";
import { watchBuddyApi } from "@/api/watchBuddy";
import { Input } from "@/components/ui/input";
import { Badge } from "@/components/ui/badge";
import { Loader2, Plus, X, Users } from "lucide-react";
import { useDebounce } from "@/hooks/useDebounce";
import type { WatchBuddy } from "@/types";
interface WatchBuddySelectProps {
selectedIds: number[];
onChange: (ids: number[]) => void;
initialBuddies?: WatchBuddy[];
}
export function WatchBuddySelect({
selectedIds,
onChange,
initialBuddies = [],
}: WatchBuddySelectProps) {
const queryClient = useQueryClient();
const [open, setOpen] = useState(false);
const [search, setSearch] = useState("");
const [creating, setCreating] = useState(false);
const [localBuddies, setLocalBuddies] = useState<WatchBuddy[]>([]);
const debouncedSearch = useDebounce(search, 200);
const ref = useRef<HTMLDivElement>(null);
const { data: options = [], isLoading } = useQuery({
queryKey: ["watch-buddies", debouncedSearch],
queryFn: () => watchBuddyApi.search(debouncedSearch || undefined),
});
// Display: initialBuddies + locally created/selected ones
const displayed = [
...initialBuddies.filter((b) => selectedIds.includes(b.id)),
...localBuddies.filter((b) => selectedIds.includes(b.id)),
];
// Check if typed name exactly matches an existing buddy
const hasExactMatch =
search.trim().length > 0 &&
options.some((b) => b.name.toLowerCase() === search.trim().toLowerCase());
useEffect(() => {
const handler = (e: MouseEvent) => {
if (ref.current && !ref.current.contains(e.target as Node))
setOpen(false);
};
document.addEventListener("mousedown", handler);
return () => document.removeEventListener("mousedown", handler);
}, []);
const toggle = (id: number) => {
const isSelected = selectedIds.includes(id);
if (!isSelected) {
const buddy = options.find((b) => b.id === id);
if (buddy && !localBuddies.some((b) => b.id === id)) {
setLocalBuddies((prev) => [...prev, buddy]);
}
}
onChange(
isSelected ? selectedIds.filter((i) => i !== id) : [...selectedIds, id],
);
setSearch("");
};
const handleCreate = async () => {
if (!search.trim()) return;
setCreating(true);
try {
const buddy = await watchBuddyApi.create({ name: search.trim() });
queryClient.invalidateQueries({ queryKey: ["watch-buddies"] });
setLocalBuddies((prev) => [...prev, buddy]);
onChange([...selectedIds, buddy.id]);
setSearch("");
} finally {
setCreating(false);
}
};
return (
<div ref={ref} className="relative">
<button
type="button"
onClick={() => setOpen(!open)}
className="flex min-h-9 w-full flex-wrap items-center gap-1 rounded-md border border-input bg-background px-3 py-2 text-sm"
>
{displayed.length > 0 ? (
displayed.map((b) => (
<Badge key={b.id} variant="secondary" className="gap-1 text-xs">
{b.name}
<button
type="button"
onClick={(e) => {
e.stopPropagation();
onChange(selectedIds.filter((i) => i !== b.id));
}}
>
<X className="h-3 w-3" />
</button>
</Badge>
))
) : (
<span className="flex items-center gap-1.5 text-muted-foreground">
<Users className="h-3.5 w-3.5" />
Select buddies
</span>
)}
</button>
{open && (
<div className="absolute z-50 mt-1 w-full rounded-md border border-border bg-popover p-2 shadow-lg">
<Input
placeholder="Search or type name to create..."
value={search}
onChange={(e) => setSearch(e.target.value)}
className="h-8 text-xs mb-2"
autoFocus
/>
<div className="max-h-40 space-y-0.5 overflow-y-auto">
{isLoading && (
<div className="flex justify-center py-3">
<Loader2 className="h-4 w-4 animate-spin text-muted-foreground" />
</div>
)}
{!isLoading && options.length === 0 && search.trim() && (
<button
type="button"
onClick={handleCreate}
disabled={creating}
className="flex w-full items-center gap-2 rounded px-2 py-1.5 text-xs hover:bg-accent"
>
<Plus className="h-3.5 w-3.5" />
{creating ? "Creating..." : `Create "${search.trim()}"`}
</button>
)}
{!isLoading &&
options.map((b) => (
<label
key={b.id}
className={`flex cursor-pointer items-center gap-2 rounded px-2 py-1.5 text-xs hover:bg-accent ${
selectedIds.includes(b.id) ? "bg-accent" : ""
}`}
>
<input
type="checkbox"
checked={selectedIds.includes(b.id)}
onChange={() => toggle(b.id)}
className="h-3.5 w-3.5 rounded"
/>
{b.name}
</label>
))}
{!isLoading &&
search.trim() &&
!hasExactMatch &&
options.length > 0 && (
<button
type="button"
onClick={handleCreate}
disabled={creating}
className="flex w-full items-center gap-2 rounded px-2 py-1.5 text-xs hover:bg-accent"
>
<Plus className="h-3.5 w-3.5" />
{creating ? "Creating..." : `Create "${search.trim()}"`}
</button>
)}
</div>
</div>
)}
</div>
);
}
+81 -63
View File
@@ -1,26 +1,26 @@
import { useState, useEffect } from 'react'; import { useState, useEffect } from "react";
import { useParams, Link, useNavigate } from 'react-router-dom'; import { useParams, Link, useNavigate } from "react-router-dom";
import { import {
useEntry, useEntry,
useEntrySeasons, useEntrySeasons,
useRefreshEntry, useRefreshEntry,
useEntryCredits, useEntryCredits,
} from '@/hooks/useEntries'; } from "@/hooks/useEntries";
import { useEntrySeenByEntry, useDeleteEntrySeen } from '@/hooks/useEntrySeen'; import { useEntrySeenByEntry, useDeleteEntrySeen } from "@/hooks/useEntrySeen";
import { useCollections } from '@/hooks/useCollections'; import { useCollections } from "@/hooks/useCollections";
import { useLibraryStore } from '@/stores/useLibraryStore'; import { useLibraryStore } from "@/stores/useLibraryStore";
import { useCommandPaletteStore } from '@/stores/useCommandPaletteStore'; import { useCommandPaletteStore } from "@/stores/useCommandPaletteStore";
import { Badge } from '@/components/ui/badge'; import { Badge } from "@/components/ui/badge";
import { Button } from '@/components/ui/button'; import { Button } from "@/components/ui/button";
import { Separator } from '@/components/ui/separator'; import { Separator } from "@/components/ui/separator";
import { ScrollArea, ScrollBar } from '@/components/ui/scroll-area'; import { ScrollArea, ScrollBar } from "@/components/ui/scroll-area";
import { import {
DropdownMenu, DropdownMenu,
DropdownMenuContent, DropdownMenuContent,
DropdownMenuItem, DropdownMenuItem,
DropdownMenuSeparator, DropdownMenuSeparator,
DropdownMenuTrigger, DropdownMenuTrigger,
} from '@/components/ui/dropdown-menu'; } from "@/components/ui/dropdown-menu";
import { import {
Heart, Heart,
MoreHorizontal, MoreHorizontal,
@@ -36,31 +36,31 @@ import {
ExternalLink, ExternalLink,
Play, Play,
BookmarkCheck, BookmarkCheck,
} from 'lucide-react'; } from "lucide-react";
import { import {
Tooltip, Tooltip,
TooltipContent, TooltipContent,
TooltipProvider, TooltipProvider,
TooltipTrigger, TooltipTrigger,
} from '@/components/ui/tooltip'; } from "@/components/ui/tooltip";
import { CastList } from '@/components/entries/CastList'; import { CastList } from "@/components/entries/CastList";
import { SeasonsContainer } from '@/components/entries/SeasonsContainer'; import { SeasonsContainer } from "@/components/entries/SeasonsContainer";
import { StreamingSection } from '@/components/streaming/StreamingSection'; import { StreamingSection } from "@/components/streaming/StreamingSection";
// EpisodeWatchHistory is available for future use // EpisodeWatchHistory is available for future use
import { EntrySettingsDialog } from '@/components/dialogs/EntrySettingsDialog'; import { EntrySettingsDialog } from "@/components/dialogs/EntrySettingsDialog";
import { EntrySeenDialog } from '@/components/dialogs/EntrySeenDialog'; import { EntrySeenDialog } from "@/components/dialogs/EntrySeenDialog";
import { EntryMediaDialog } from '@/components/dialogs/EntryMediaDialog'; import { EntryMediaDialog } from "@/components/dialogs/EntryMediaDialog";
import { AddEntryToCollectionDialog } from '@/components/dialogs/AddEntryToCollectionDialog'; import { AddEntryToCollectionDialog } from "@/components/dialogs/AddEntryToCollectionDialog";
import { RatingDialog } from '@/components/dialogs/RatingDialog'; import { RatingDialog } from "@/components/dialogs/RatingDialog";
import { MovieWatchHistoryDialog } from '@/components/dialogs/MovieWatchHistoryDialog'; import { MovieWatchHistoryDialog } from "@/components/dialogs/MovieWatchHistoryDialog";
import { ConfirmDialog } from '@/components/dialogs/ConfirmDialog'; import { ConfirmDialog } from "@/components/dialogs/ConfirmDialog";
import { import {
Dialog, Dialog,
DialogContent, DialogContent,
DialogHeader, DialogHeader,
DialogTitle, DialogTitle,
} from '@/components/ui/dialog'; } from "@/components/ui/dialog";
import { EntryDetailsSkeleton } from '@/components/skeletons/PageSkeletons'; import { EntryDetailsSkeleton } from "@/components/skeletons/PageSkeletons";
import { import {
getPosterUrl, getPosterUrl,
getBackdropUrl, getBackdropUrl,
@@ -68,38 +68,38 @@ import {
getYear, getYear,
formatRuntime, formatRuntime,
formatDate, formatDate,
} from '@/lib/media-utils'; } from "@/lib/media-utils";
import { useUpdateEntry, useDeleteEntry } from '@/hooks/useEntries'; import { useUpdateEntry, useDeleteEntry } from "@/hooks/useEntries";
import type { Collection, Entry } from '@/types'; import type { Collection, Entry, EntrySeen } from "@/types";
const WATCH_STATUSES = [ const WATCH_STATUSES = [
{ {
value: 'plan_to_watch', value: "plan_to_watch",
label: 'Plan to Watch', label: "Plan to Watch",
color: color:
'bg-slate-500/15 border-slate-500/30 text-slate-600 dark:text-slate-400', "bg-slate-500/15 border-slate-500/30 text-slate-600 dark:text-slate-400",
}, },
{ {
value: 'watching', value: "watching",
label: 'Watching', label: "Watching",
color: 'bg-blue-500/15 border-blue-500/30 text-blue-600 dark:text-blue-400', color: "bg-blue-500/15 border-blue-500/30 text-blue-600 dark:text-blue-400",
}, },
{ {
value: 'completed', value: "completed",
label: 'Completed', label: "Completed",
color: color:
'bg-green-500/15 border-green-500/30 text-green-600 dark:text-green-400', "bg-green-500/15 border-green-500/30 text-green-600 dark:text-green-400",
}, },
{ {
value: 'on_hold', value: "on_hold",
label: 'On Hold', label: "On Hold",
color: color:
'bg-amber-500/15 border-amber-500/30 text-amber-600 dark:text-amber-400', "bg-amber-500/15 border-amber-500/30 text-amber-600 dark:text-amber-400",
}, },
{ {
value: 'dropped', value: "dropped",
label: 'Dropped', label: "Dropped",
color: 'bg-red-500/15 border-red-500/30 text-red-600 dark:text-red-400', color: "bg-red-500/15 border-red-500/30 text-red-600 dark:text-red-400",
}, },
]; ];
@@ -135,6 +135,7 @@ export function EntryDetailsPage() {
const [showWatchHistoryDialog, setShowWatchHistoryDialog] = useState(false); const [showWatchHistoryDialog, setShowWatchHistoryDialog] = useState(false);
const [showDeleteConfirm, setShowDeleteConfirm] = useState(false); const [showDeleteConfirm, setShowDeleteConfirm] = useState(false);
const [showStatusDialog, setShowStatusDialog] = useState(false); const [showStatusDialog, setShowStatusDialog] = useState(false);
const [editSeenRecord, setEditSeenRecord] = useState<EntrySeen | null>(null);
// Track recently viewed for command palette // Track recently viewed for command palette
const addRecentlyViewed = useCommandPaletteStore((s) => s.addRecentlyViewed); const addRecentlyViewed = useCommandPaletteStore((s) => s.addRecentlyViewed);
@@ -143,7 +144,7 @@ export function EntryDetailsPage() {
addRecentlyViewed({ addRecentlyViewed({
id: `lib-${entryId}`, id: `lib-${entryId}`,
title: displayEntry.title, title: displayEntry.title,
type: displayEntry.is_tvseries ? 'tv' : 'movie', type: displayEntry.is_tvseries ? "tv" : "movie",
poster_path: displayEntry.poster_path, poster_path: displayEntry.poster_path,
libraryId: entryId, libraryId: entryId,
tmdbId: displayEntry.entryIds?.tmdb_id ?? undefined, tmdbId: displayEntry.entryIds?.tmdb_id ?? undefined,
@@ -162,7 +163,7 @@ export function EntryDetailsPage() {
const backdrop = getBackdropUrl(e); const backdrop = getBackdropUrl(e);
const poster = getPosterUrl(e); const poster = getPosterUrl(e);
const director = credits.find( const director = credits.find(
(c) => c.cast_type === 'crew' && c.job === 'Director', (c) => c.cast_type === "crew" && c.job === "Director",
); );
const toggleFavorite = () => { const toggleFavorite = () => {
@@ -227,9 +228,9 @@ export function EntryDetailsPage() {
disabled={updateEntry.isPending} disabled={updateEntry.isPending}
> >
<Heart <Heart
className={`mr-2 h-4 w-4 ${e.favorit ? 'fill-current' : ''}`} className={`mr-2 h-4 w-4 ${e.favorit ? "fill-current" : ""}`}
/> />
{e.favorit ? 'Unfavorite' : 'Favorite'} {e.favorit ? "Unfavorite" : "Favorite"}
</DropdownMenuItem> </DropdownMenuItem>
<DropdownMenuItem onClick={() => setShowCollectionDialog(true)}> <DropdownMenuItem onClick={() => setShowCollectionDialog(true)}>
<FolderPlus className="mr-2 h-4 w-4" /> <FolderPlus className="mr-2 h-4 w-4" />
@@ -241,7 +242,7 @@ export function EntryDetailsPage() {
} }
> >
<EyeOff className="mr-2 h-4 w-4" /> <EyeOff className="mr-2 h-4 w-4" />
{e.hidden ? 'Unhide' : 'Hide'} {e.hidden ? "Unhide" : "Hide"}
</DropdownMenuItem> </DropdownMenuItem>
<DropdownMenuSeparator /> <DropdownMenuSeparator />
{/* Manage */} {/* Manage */}
@@ -250,9 +251,9 @@ export function EntryDetailsPage() {
disabled={refreshEntry.isPending} disabled={refreshEntry.isPending}
> >
<RefreshCw <RefreshCw
className={`mr-2 h-4 w-4 ${refreshEntry.isPending ? 'animate-spin' : ''}`} className={`mr-2 h-4 w-4 ${refreshEntry.isPending ? "animate-spin" : ""}`}
/> />
{refreshEntry.isPending ? 'Refreshing...' : 'Refresh details'} {refreshEntry.isPending ? "Refreshing..." : "Refresh details"}
</DropdownMenuItem> </DropdownMenuItem>
<DropdownMenuItem onClick={() => setShowMediaDialog(true)}> <DropdownMenuItem onClick={() => setShowMediaDialog(true)}>
<ImageIcon className="mr-2 h-4 w-4" /> <ImageIcon className="mr-2 h-4 w-4" />
@@ -291,7 +292,7 @@ export function EntryDetailsPage() {
<div className="flex items-center justify-center gap-3 mt-3"> <div className="flex items-center justify-center gap-3 mt-3">
{e.entryIds.tmdb_id && ( {e.entryIds.tmdb_id && (
<a <a
href={`https://www.themoviedb.org/${e.is_tvseries ? 'tv' : 'movie'}/${e.entryIds.tmdb_id}`} href={`https://www.themoviedb.org/${e.is_tvseries ? "tv" : "movie"}/${e.entryIds.tmdb_id}`}
target="_blank" target="_blank"
rel="noopener noreferrer" rel="noopener noreferrer"
className="inline-flex items-center gap-1 text-xs text-muted-foreground hover:text-foreground transition-colors" className="inline-flex items-center gap-1 text-xs text-muted-foreground hover:text-foreground transition-colors"
@@ -322,7 +323,7 @@ export function EntryDetailsPage() {
<h1 className="text-3xl font-bold leading-tight">{e.title}</h1> <h1 className="text-3xl font-bold leading-tight">{e.title}</h1>
{director?.people?.name && ( {director?.people?.name && (
<p className="text-sm text-muted-foreground"> <p className="text-sm text-muted-foreground">
by{' '} by{" "}
<Link <Link
to={`/people/${director.people_id}`} to={`/people/${director.people_id}`}
className="font-medium text-foreground hover:underline" className="font-medium text-foreground hover:underline"
@@ -464,19 +465,19 @@ export function EntryDetailsPage() {
disabled={updateEntry.isPending} disabled={updateEntry.isPending}
className={`inline-flex items-center gap-1 rounded-full border px-3 py-1 text-sm font-medium transition-colors ${ className={`inline-flex items-center gap-1 rounded-full border px-3 py-1 text-sm font-medium transition-colors ${
e.favorit e.favorit
? 'bg-yellow-500/15 border-yellow-500/30 text-yellow-600 dark:text-yellow-400 hover:bg-yellow-500/25' ? "bg-yellow-500/15 border-yellow-500/30 text-yellow-600 dark:text-yellow-400 hover:bg-yellow-500/25"
: 'border-dashed border-border text-muted-foreground hover:border-yellow-500/40 hover:text-yellow-500' : "border-dashed border-border text-muted-foreground hover:border-yellow-500/40 hover:text-yellow-500"
}`} }`}
> >
<Star <Star
className={`h-3.5 w-3.5 ${e.favorit ? 'fill-yellow-400 text-yellow-400' : ''}`} className={`h-3.5 w-3.5 ${e.favorit ? "fill-yellow-400 text-yellow-400" : ""}`}
/> />
Favorit Favorit
</button> </button>
</TooltipTrigger> </TooltipTrigger>
<TooltipContent> <TooltipContent>
<p> <p>
{e.favorit ? 'Remove from favorites' : 'Add to favorites'} {e.favorit ? "Remove from favorites" : "Add to favorites"}
</p> </p>
</TooltipContent> </TooltipContent>
</Tooltip> </Tooltip>
@@ -490,7 +491,7 @@ export function EntryDetailsPage() {
return ( return (
<button <button
onClick={() => setShowStatusDialog(true)} onClick={() => setShowStatusDialog(true)}
className={`inline-flex items-center gap-1 rounded-full border px-3 py-1 text-sm font-medium transition-colors cursor-pointer ${info?.color ?? ''}`} className={`inline-flex items-center gap-1 rounded-full border px-3 py-1 text-sm font-medium transition-colors cursor-pointer ${info?.color ?? ""}`}
> >
<BookmarkCheck className="h-3.5 w-3.5" /> <BookmarkCheck className="h-3.5 w-3.5" />
{info?.label} {info?.label}
@@ -514,7 +515,7 @@ export function EntryDetailsPage() {
<div className="flex flex-wrap items-center justify-center gap-2"> <div className="flex flex-wrap items-center justify-center gap-2">
<StreamingSection entry={e} seasons={seasons} /> <StreamingSection entry={e} seasons={seasons} />
<a <a
href={`https://www.youtube.com/results?search_query=${encodeURIComponent(e.title + ' official trailer')}`} href={`https://www.youtube.com/results?search_query=${encodeURIComponent(e.title + " official trailer")}`}
target="_blank" target="_blank"
rel="noopener noreferrer" rel="noopener noreferrer"
className="inline-flex items-center gap-2 h-11 px-6 text-sm font-medium rounded-md border border-input bg-background hover:bg-accent hover:text-accent-foreground transition-colors" className="inline-flex items-center gap-2 h-11 px-6 text-sm font-medium rounded-md border border-input bg-background hover:bg-accent hover:text-accent-foreground transition-colors"
@@ -607,6 +608,23 @@ export function EntryDetailsPage() {
onDelete={(seenId) => onDelete={(seenId) =>
deleteEntrySeen.mutate({ id: seenId, entryId: e.id }) deleteEntrySeen.mutate({ id: seenId, entryId: e.id })
} }
onEdit={(record) => {
setEditSeenRecord(record);
setShowWatchHistoryDialog(false);
}}
/>
)}
{editSeenRecord && (
<EntrySeenDialog
open={!!editSeenRecord}
onOpenChange={(open) => {
if (!open) setEditSeenRecord(null);
}}
entry={e}
seasons={seasons}
mode="edit"
editRecord={editSeenRecord}
/> />
)} )}
<ConfirmDialog <ConfirmDialog
@@ -618,7 +636,7 @@ export function EntryDetailsPage() {
variant="destructive" variant="destructive"
onConfirm={() => { onConfirm={() => {
deleteEntry.mutate(e.id, { deleteEntry.mutate(e.id, {
onSuccess: () => navigate('/library'), onSuccess: () => navigate("/library"),
}); });
setShowDeleteConfirm(false); setShowDeleteConfirm(false);
}} }}
@@ -641,7 +659,7 @@ export function EntryDetailsPage() {
setShowStatusDialog(false); setShowStatusDialog(false);
}} }}
className={`w-full flex items-center gap-2 rounded-md px-3 py-2 text-sm transition-colors hover:bg-accent ${ className={`w-full flex items-center gap-2 rounded-md px-3 py-2 text-sm transition-colors hover:bg-accent ${
e.watch_status === s.value ? 'bg-accent font-medium' : '' e.watch_status === s.value ? "bg-accent font-medium" : ""
}`} }`}
> >
<BookmarkCheck className="h-4 w-4" /> <BookmarkCheck className="h-4 w-4" />
@@ -692,8 +710,8 @@ function EntryCollectionsSection({ entryId }: { entryId: number }) {
</p> </p>
{col.entries && ( {col.entries && (
<p className="text-xs text-white/70 mt-0.5"> <p className="text-xs text-white/70 mt-0.5">
{col.entries.length}{' '} {col.entries.length}{" "}
{col.entries.length === 1 ? 'title' : 'titles'} {col.entries.length === 1 ? "title" : "titles"}
</p> </p>
)} )}
</div> </div>
+30 -30
View File
@@ -1,27 +1,27 @@
import { useState } from 'react'; import { useState } from "react";
import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query'; import { useQuery, useMutation, useQueryClient } from "@tanstack/react-query";
import { settingsApi } from '@/api/settings'; import { settingsApi } from "@/api/settings";
import { maintenanceApi, type OrphanResult } from '@/api/maintenance'; import { maintenanceApi, type OrphanResult } from "@/api/maintenance";
import { useForm } from 'react-hook-form'; import { useForm } from "react-hook-form";
import { zodResolver } from '@hookform/resolvers/zod'; import { zodResolver } from "@hookform/resolvers/zod";
import { z } from 'zod'; import { z } from "zod";
import { import {
Card, Card,
CardContent, CardContent,
CardHeader, CardHeader,
CardTitle, CardTitle,
CardDescription, CardDescription,
} from '@/components/ui/card'; } from "@/components/ui/card";
import { Input } from '@/components/ui/input'; import { Input } from "@/components/ui/input";
import { Label } from '@/components/ui/label'; import { Label } from "@/components/ui/label";
import { Button } from '@/components/ui/button'; import { Button } from "@/components/ui/button";
import { Skeleton } from '@/components/ui/skeleton'; import { Skeleton } from "@/components/ui/skeleton";
import { Tabs, TabsContent, TabsList, TabsTrigger } from '@/components/ui/tabs'; import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs";
import { Save, Search, Trash2, Loader2 } from 'lucide-react'; import { Save, Search, Trash2, Loader2 } from "lucide-react";
import type { Settings } from '@/types'; import type { Settings } from "@/types";
const settingsSchema = z.object({ const settingsSchema = z.object({
tmdbApiKey: z.string().min(1, 'TMDB API key is required'), tmdbApiKey: z.string().min(1, "TMDB API key is required"),
backPort: z.coerce.number().int().positive(), backPort: z.coerce.number().int().positive(),
authPassword: z.string().optional(), authPassword: z.string().optional(),
}); });
@@ -32,7 +32,7 @@ function formatOrphanResult(result: OrphanResult): string {
if (result.logos) parts.push(`${result.logos} logo(s)`); if (result.logos) parts.push(`${result.logos} logo(s)`);
if (result.backdrops) parts.push(`${result.backdrops} backdrop(s)`); if (result.backdrops) parts.push(`${result.backdrops} backdrop(s)`);
if (result.stills) parts.push(`${result.stills} still(s)`); if (result.stills) parts.push(`${result.stills} still(s)`);
return parts.length > 0 ? parts.join(', ') : 'None found'; return parts.length > 0 ? parts.join(", ") : "None found";
} }
function hasOrphans(result: OrphanResult | null): boolean { function hasOrphans(result: OrphanResult | null): boolean {
@@ -90,7 +90,7 @@ function MissingDirectorsSection() {
{result && ( {result && (
<p className="text-xs text-muted-foreground"> <p className="text-xs text-muted-foreground">
{result.count === 0 {result.count === 0
? 'All entries have directors.' ? "All entries have directors."
: result.fixed > 0 : result.fixed > 0
? `Fixed ${result.fixed} of ${result.count} missing directors.` ? `Fixed ${result.fixed} of ${result.count} missing directors.`
: `${result.count} entries missing director.`} : `${result.count} entries missing director.`}
@@ -152,7 +152,7 @@ function DuplicateCreditsSection() {
{result && ( {result && (
<p className="text-xs text-muted-foreground"> <p className="text-xs text-muted-foreground">
{result.duplicates === 0 {result.duplicates === 0
? 'No duplicate credits found.' ? "No duplicate credits found."
: result.deleted > 0 : result.deleted > 0
? `Removed ${result.deleted} duplicates across ${result.groups} groups.` ? `Removed ${result.deleted} duplicates across ${result.groups} groups.`
: `${result.duplicates} duplicates across ${result.groups} groups.`} : `${result.duplicates} duplicates across ${result.groups} groups.`}
@@ -203,7 +203,7 @@ function WatchStatusesSection() {
{fixResult.completed === 0 && {fixResult.completed === 0 &&
fixResult.watching === 0 && fixResult.watching === 0 &&
fixResult.planToWatch === 0 && fixResult.planToWatch === 0 &&
'All statuses up to date.'} "All statuses up to date."}
</p> </p>
)} )}
</div> </div>
@@ -213,14 +213,14 @@ function WatchStatusesSection() {
export function SettingsPage() { export function SettingsPage() {
const queryClient = useQueryClient(); const queryClient = useQueryClient();
const { data: settings, isLoading } = useQuery({ const { data: settings, isLoading } = useQuery({
queryKey: ['settings'], queryKey: ["settings"],
queryFn: settingsApi.get, queryFn: settingsApi.get,
}); });
const updateSettings = useMutation({ const updateSettings = useMutation({
mutationFn: (data: Partial<Settings>) => settingsApi.update(data), mutationFn: (data: Partial<Settings>) => settingsApi.update(data),
onSuccess: () => { onSuccess: () => {
queryClient.invalidateQueries({ queryKey: ['settings'] }); queryClient.invalidateQueries({ queryKey: ["settings"] });
}, },
}); });
@@ -262,7 +262,7 @@ export function SettingsPage() {
? { ? {
tmdbApiKey: settings.tmdbApiKey, tmdbApiKey: settings.tmdbApiKey,
backPort: settings.backPort, backPort: settings.backPort,
authPassword: settings.authPassword || '', authPassword: settings.authPassword || "",
} }
: undefined, : undefined,
}); });
@@ -302,7 +302,7 @@ export function SettingsPage() {
<Input <Input
id="tmdbApiKey" id="tmdbApiKey"
type="password" type="password"
{...register('tmdbApiKey')} {...register("tmdbApiKey")}
/> />
{errors.tmdbApiKey && ( {errors.tmdbApiKey && (
<p className="text-xs text-destructive"> <p className="text-xs text-destructive">
@@ -316,7 +316,7 @@ export function SettingsPage() {
<Input <Input
id="backPort" id="backPort"
type="number" type="number"
{...register('backPort')} {...register("backPort")}
/> />
{errors.backPort && ( {errors.backPort && (
<p className="text-xs text-destructive"> <p className="text-xs text-destructive">
@@ -330,7 +330,7 @@ export function SettingsPage() {
<Input <Input
id="authPassword" id="authPassword"
type="password" type="password"
{...register('authPassword')} {...register("authPassword")}
placeholder="Leave empty to disable" placeholder="Leave empty to disable"
/> />
</div> </div>
@@ -340,7 +340,7 @@ export function SettingsPage() {
disabled={!isDirty || updateSettings.isPending} disabled={!isDirty || updateSettings.isPending}
> >
<Save className="mr-2 h-4 w-4" /> <Save className="mr-2 h-4 w-4" />
{updateSettings.isPending ? 'Saving...' : 'Save Settings'} {updateSettings.isPending ? "Saving..." : "Save Settings"}
</Button> </Button>
</CardContent> </CardContent>
</Card> </Card>
@@ -457,11 +457,11 @@ export function SettingsPage() {
<CardContent> <CardContent>
<ul className="text-xs text-muted-foreground list-disc pl-4 mb-3 space-y-0.5"> <ul className="text-xs text-muted-foreground list-disc pl-4 mb-3 space-y-0.5">
<li> <li>
Entries with all episodes watched → set to{' '} Entries with all episodes watched → set to{" "}
<strong>Completed</strong> <strong>Completed</strong>
</li> </li>
<li> <li>
Entries marked Completed but missing episodes → downgrade to{' '} Entries marked Completed but missing episodes → downgrade to{" "}
<strong>Watching</strong> <strong>Watching</strong>
</li> </li>
<li> <li>
@@ -469,7 +469,7 @@ export function SettingsPage() {
set to <strong>Watching</strong> set to <strong>Watching</strong>
</li> </li>
<li> <li>
Entries in Watchlist with no status → set to{' '} Entries in Watchlist with no status → set to{" "}
<strong>Plan to Watch</strong> <strong>Plan to Watch</strong>
</li> </li>
</ul> </ul>
@@ -0,0 +1,81 @@
import { useState } from "react";
import { Link } from "react-router-dom";
import { useQuery } from "@tanstack/react-query";
import { watchBuddyApi } from "@/api/watchBuddy";
import { Input } from "@/components/ui/input";
import { Avatar, AvatarFallback, AvatarImage } from "@/components/ui/avatar";
import { Skeleton } from "@/components/ui/skeleton";
import { Search, Users } from "lucide-react";
import { useDebounce } from "@/hooks/useDebounce";
export function WatchBuddiesPage() {
const [search, setSearch] = useState("");
const debouncedSearch = useDebounce(search, 300);
const { data: buddies = [], isLoading } = useQuery({
queryKey: ["watch-buddies", "all", debouncedSearch],
queryFn: () => watchBuddyApi.search(debouncedSearch || undefined),
});
return (
<div className="animate-page-enter space-y-6">
<div className="flex items-center gap-2">
<Users className="h-6 w-6 text-primary" />
<h1 className="text-2xl font-bold">Watch Buddies</h1>
</div>
<div className="relative w-full max-w-xs">
<Search className="absolute left-3 top-1/2 h-4 w-4 -translate-y-1/2 text-muted-foreground" />
<Input
placeholder="Search buddies..."
value={search}
onChange={(e) => setSearch(e.target.value)}
className="pl-10"
/>
</div>
{isLoading ? (
<div className="grid grid-cols-3 gap-4 sm:grid-cols-4 md:grid-cols-5 lg:grid-cols-6 xl:grid-cols-8">
{Array.from({ length: 16 }).map((_, i) => (
<div key={i} className="flex flex-col items-center gap-2">
<Skeleton className="h-24 w-24 rounded-full" />
<Skeleton className="h-4 w-20" />
</div>
))}
</div>
) : buddies.length === 0 ? (
<div className="flex h-40 items-center justify-center text-muted-foreground">
No buddies found.
</div>
) : (
<div className="grid grid-cols-3 gap-4 sm:grid-cols-4 md:grid-cols-5 lg:grid-cols-6 xl:grid-cols-8">
{buddies.map((buddy) => (
<Link
key={buddy.id}
to={`/watch-buddies/${buddy.id}`}
className="group flex flex-col items-center gap-2 text-center"
>
<Avatar className="h-24 w-24 transition-transform group-hover:scale-105">
{buddy.medias?.some((m: any) => m.type === "profiles") &&
(() => {
const pic = buddy.medias!.find(
(m: any) => m.type === "profiles",
)!;
const url = `${import.meta.env.VITE_API_URL || ""}/api/v1/media/watch-buddies/profiles/preview/${pic.path.replace(/\.[^.]+$/, "_preview.jpg")}`;
return <AvatarImage src={url} alt={buddy.name} />;
})()}
<AvatarFallback className="bg-primary/10 text-primary text-lg">
{buddy.name
.split(" ")
.map((n) => n[0])
.join("")}
</AvatarFallback>
</Avatar>
<p className="text-sm font-medium line-clamp-2">{buddy.name}</p>
</Link>
))}
</div>
)}
</div>
);
}
@@ -0,0 +1,669 @@
import { useState } from "react";
import { useParams, Link, useNavigate } from "react-router-dom";
import { useQuery, useMutation, useQueryClient } from "@tanstack/react-query";
import { watchBuddyApi } from "@/api/watchBuddy";
import { Button } from "@/components/ui/button";
import { ConfirmDialog } from "@/components/dialogs/ConfirmDialog";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import {
Select,
SelectContent,
SelectItem,
SelectTrigger,
SelectValue,
} from "@/components/ui/select";
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
import {
Dialog,
DialogContent,
DialogHeader,
DialogTitle,
} from "@/components/ui/dialog";
import { Skeleton } from "@/components/ui/skeleton";
import { Separator } from "@/components/ui/separator";
import { Badge } from "@/components/ui/badge";
import { Avatar, AvatarFallback, AvatarImage } from "@/components/ui/avatar";
import {
Loader2,
ArrowLeft,
Film,
Tv,
Trash2,
ChevronDown,
ChevronUp,
Camera,
Phone,
Mail,
Upload,
} from "lucide-react";
import { format } from "date-fns";
import { getPosterUrl } from "@/lib/media-utils";
import type { WatchBuddy, EntrySeen } from "@/types";
const GENDER_OPTIONS = ["Male", "Female"];
export function WatchBuddyProfilePage() {
const { id } = useParams<{ id: string }>();
const buddyId = parseInt(id!, 10);
const queryClient = useQueryClient();
const { data: buddy, isLoading } = useQuery({
queryKey: ["watch-buddy", buddyId],
queryFn: () => watchBuddyApi.getById(buddyId),
enabled: !!buddyId,
});
const { data: history, isLoading: historyLoading } = useQuery({
queryKey: ["watch-buddy", buddyId, "history"],
queryFn: () => watchBuddyApi.getHistory(buddyId),
enabled: !!buddyId,
});
const [editMode, setEditMode] = useState(false);
const [form, setForm] = useState<Partial<WatchBuddy>>({});
const [showDeleteConfirm, setShowDeleteConfirm] = useState(false);
const [showAllHistory, setShowAllHistory] = useState(false);
const [showUploadDialog, setShowUploadDialog] = useState(false);
const [uploadFile, setUploadFile] = useState<File | null>(null);
const [uploadDragOver, setUploadDragOver] = useState(false);
const [uploading, setUploading] = useState(false);
const HISTORY_PREVIEW_COUNT = 16;
const navigate = useNavigate();
const saveMutation = useMutation({
mutationFn: (data: Partial<WatchBuddy>) =>
watchBuddyApi.update(buddyId, data),
onSuccess: () => {
queryClient.invalidateQueries({ queryKey: ["watch-buddy", buddyId] });
setEditMode(false);
},
});
const deleteMutation = useMutation({
mutationFn: () => watchBuddyApi.remove(buddyId),
onSuccess: () => {
queryClient.invalidateQueries({ queryKey: ["watch-buddies"] });
navigate("/watch-buddies", { replace: true });
},
});
const startEdit = () => {
if (buddy) setForm({ ...buddy });
setEditMode(true);
};
const handleSave = () => {
saveMutation.mutate(form);
};
const handleUpload = async () => {
if (!uploadFile) return;
setUploading(true);
try {
await watchBuddyApi.uploadProfilePicture(buddyId, uploadFile);
queryClient.invalidateQueries({ queryKey: ["watch-buddy", buddyId] });
setShowUploadDialog(false);
setUploadFile(null);
} finally {
setUploading(false);
}
};
if (isLoading || !buddy) {
return (
<div className="animate-page-enter space-y-6">
<Skeleton className="h-8 w-48" />
<Skeleton className="h-48 w-full rounded-xl" />
</div>
);
}
// Build combined timeline
const entrySeens: (EntrySeen & { entry?: any })[] = history?.entrySeens || [];
const episodeSeens: any[] = history?.episodeSeens || [];
const timeline = [
...entrySeens.map((r) => ({
id: `e-${r.id}`,
date: r.date_seen,
type: "movie" as const,
title: r.entry?.title ?? "Unknown",
link: `/entry/${r.entry_id}`,
poster: getPosterUrl(r.entry),
subtitle: r.entry?.is_tvseries ? "TV Series" : "Movie",
})),
...episodeSeens.map((r: any) => {
const seasonId = r.episode?.season?.id;
const epId = r.episode_id;
return {
id: `ep-${r.id}`,
date: r.date_seen,
type: "episode" as const,
title: r.episode?.season?.entry?.title ?? "Unknown",
link:
seasonId && epId
? `/entry/${r.entry_id}/season/${seasonId}/episode/${epId}`
: `/entry/${r.entry_id}`,
poster: getPosterUrl(r.episode?.season?.entry),
subtitle: `S${r.episode?.season?.season_number ?? "?"} E${r.episode?.episode_number ?? "?"} — ${r.episode?.name ?? ""}`,
};
}),
].sort((a, b) => new Date(b.date).getTime() - new Date(a.date).getTime());
// Group by month for timeline
const grouped = timeline.reduce(
(acc, item) => {
const month = format(new Date(item.date), "MMMM yyyy");
if (!acc[month]) acc[month] = [];
acc[month].push(item);
return acc;
},
{} as Record<string, typeof timeline>,
);
// Count unique entries for watch history section
const entryMap = new Map<
string,
{ title: string; poster: string; link: string; count: number }
>();
for (const item of timeline) {
const existing = entryMap.get(item.title);
if (existing) {
existing.count++;
} else {
entryMap.set(item.title, {
title: item.title,
poster: item.poster,
link: item.link,
count: 1,
});
}
}
const watchedEntries = Array.from(entryMap.values());
const profilePic = buddy.medias?.find(
(m) => (m.type as string) === "profiles",
);
const profilePicUrl = profilePic
? `${import.meta.env.VITE_API_URL || ""}/api/v1/media/watch-buddies/profiles/preview/${profilePic.path.replace(/\.[^.]+$/, "_preview.jpg")}`
: null;
return (
<div className="animate-page-enter space-y-8">
<Link
to="/watch-buddies"
className="inline-flex items-center gap-1 text-sm text-muted-foreground hover:text-foreground"
>
<ArrowLeft className="h-4 w-4" />
Back to Buddies
</Link>
{/* Header */}
<div className="flex items-start gap-4">
<button
type="button"
className="group relative shrink-0"
onClick={() => setShowUploadDialog(true)}
title="Change profile picture"
>
<Avatar className="h-20 w-20">
{profilePicUrl && (
<AvatarImage src={profilePicUrl} alt={buddy.name} />
)}
<AvatarFallback className="bg-primary/10 text-primary text-xl">
{buddy.name
.split(" ")
.map((n) => n[0])
.join("")}
</AvatarFallback>
</Avatar>
<div className="absolute inset-0 flex items-center justify-center rounded-full bg-black/40 opacity-0 transition-opacity group-hover:opacity-100">
<Camera className="h-5 w-5 text-white" />
</div>
</button>
<div className="min-w-0 flex-1">
<div className="flex items-center gap-2">
<h1 className="text-2xl font-bold">{buddy.name}</h1>
{buddy.buddy_type && buddy.buddy_type !== "person" && (
<Badge variant="secondary" className="capitalize">
{buddy.buddy_type}
</Badge>
)}
</div>
{buddy.gender && (
<p className="text-sm text-muted-foreground">{buddy.gender}</p>
)}
{/* Contact icons */}
{(buddy.instagram || buddy.discord || buddy.phone || buddy.email) && (
<div className="mt-1 flex flex-wrap items-center gap-3 text-sm text-muted-foreground">
{buddy.instagram && (
<a
href={`https://instagram.com/${buddy.instagram.replace(/^@/, "")}`}
target="_blank"
rel="noopener noreferrer"
className="inline-flex items-center gap-1 transition-colors hover:text-pink-500"
title={`Instagram: ${buddy.instagram}`}
>
<svg
className="h-3.5 w-3.5"
viewBox="0 0 24 24"
fill="currentColor"
>
<path d="M12 2.163c3.204 0 3.584.012 4.85.07 3.252.148 4.771 1.691 4.919 4.919.058 1.265.069 1.645.069 4.849 0 3.205-.012 3.584-.069 4.849-.149 3.225-1.664 4.771-4.919 4.919-1.266.058-1.644.07-4.85.07-3.204 0-3.584-.012-4.849-.07-3.26-.149-4.771-1.699-4.919-4.92-.058-1.265-.07-1.644-.07-4.849 0-3.204.013-3.583.07-4.849.149-3.227 1.664-4.771 4.919-4.919 1.266-.057 1.645-.069 4.849-.069zM12 0C8.741 0 8.333.014 7.053.072 2.695.272.273 2.69.073 7.052.014 8.333 0 8.741 0 12c0 3.259.014 3.668.072 4.948.2 4.358 2.618 6.78 6.98 6.98C8.333 23.986 8.741 24 12 24c3.259 0 3.668-.014 4.948-.072 4.354-.2 6.782-2.618 6.979-6.98.059-1.28.073-1.689.073-4.948 0-3.259-.014-3.667-.072-4.947-.196-4.354-2.617-6.78-6.979-6.98C15.668.014 15.259 0 12 0zm0 5.838a6.162 6.162 0 100 12.324 6.162 6.162 0 000-12.324zM12 16a4 4 0 110-8 4 4 0 010 8zm6.406-11.845a1.44 1.44 0 100 2.881 1.44 1.44 0 000-2.881z" />
</svg>
<span>{buddy.instagram}</span>
</a>
)}
{buddy.discord && (
<span
className="inline-flex items-center gap-1"
title={`Discord: ${buddy.discord}`}
>
<svg
className="h-3.5 w-3.5"
viewBox="0 0 24 24"
fill="currentColor"
>
<path d="M20.317 4.37a19.791 19.791 0 00-4.885-1.515.074.074 0 00-.079.037c-.21.375-.444.864-.608 1.25a18.27 18.27 0 00-5.487 0 12.64 12.64 0 00-.617-1.25.077.077 0 00-.079-.037A19.736 19.736 0 003.677 4.37a.07.07 0 00-.032.027C.533 9.046-.32 13.58.099 18.057a.082.082 0 00.031.057 19.9 19.9 0 005.993 3.03.078.078 0 00.084-.028 14.09 14.09 0 001.226-1.994.076.076 0 00-.041-.106 13.107 13.107 0 01-1.872-.892.077.077 0 01-.008-.128 10.2 10.2 0 00.372-.292.074.074 0 01.077-.01c3.928 1.793 8.18 1.793 12.062 0a.074.074 0 01.078.01c.12.098.246.198.373.292a.077.077 0 01-.006.127 12.299 12.299 0 01-1.873.892.077.077 0 00-.041.107c.36.698.772 1.362 1.225 1.993a.076.076 0 00.084.028 19.839 19.839 0 006.002-3.03.077.077 0 00.032-.054c.5-5.177-.838-9.674-3.549-13.66a.061.061 0 00-.031-.03zM8.02 15.33c-1.183 0-2.157-1.085-2.157-2.419 0-1.333.956-2.419 2.157-2.419 1.21 0 2.176 1.096 2.157 2.42 0 1.333-.956 2.418-2.157 2.418zm7.975 0c-1.183 0-2.157-1.085-2.157-2.419 0-1.333.955-2.419 2.157-2.419 1.21 0 2.176 1.096 2.157 2.42 0 1.333-.946 2.418-2.157 2.418z" />
</svg>
<span>{buddy.discord}</span>
</span>
)}
{buddy.phone && (
<a
href={`tel:${buddy.phone}`}
className="inline-flex items-center gap-1 transition-colors hover:text-green-500"
title={`Phone: ${buddy.phone}`}
>
<Phone className="h-3.5 w-3.5" />
<span>{buddy.phone}</span>
</a>
)}
{buddy.email && (
<a
href={`mailto:${buddy.email}`}
className="inline-flex items-center gap-1 transition-colors hover:text-blue-500"
title={`Email: ${buddy.email}`}
>
<Mail className="h-3.5 w-3.5" />
<span>{buddy.email}</span>
</a>
)}
</div>
)}
<p className="text-xs text-muted-foreground mt-1">
Watched together: {timeline.length} time
{timeline.length !== 1 ? "s" : ""}
</p>
{buddy.note && (
<p className="mt-2 text-sm text-muted-foreground italic max-w-prose">
{buddy.note}
</p>
)}
</div>
{!editMode && (
<div className="ml-auto flex gap-1 shrink-0">
<Button
variant="outline"
size="sm"
className="text-destructive"
onClick={() => setShowDeleteConfirm(true)}
>
<Trash2 className="h-4 w-4" />
</Button>
<Button variant="outline" size="sm" onClick={startEdit}>
Edit
</Button>
</div>
)}
</div>
{/* Edit mode */}
{editMode ? (
<Card>
<CardHeader>
<CardTitle>Edit Details</CardTitle>
</CardHeader>
<CardContent className="space-y-4">
{/* Name + Type + Gender */}
<div className="grid grid-cols-1 gap-3 sm:grid-cols-3">
<div className="space-y-2">
<Label>Name</Label>
<Input
value={form.name ?? ""}
onChange={(e) => setForm({ ...form, name: e.target.value })}
/>
</div>
<div className="space-y-2">
<Label>Type</Label>
<Select
value={form.buddy_type ?? "person"}
onValueChange={(v) => setForm({ ...form, buddy_type: v })}
>
<SelectTrigger>
<SelectValue />
</SelectTrigger>
<SelectContent>
<SelectItem value="person">Person</SelectItem>
<SelectItem value="group">Group</SelectItem>
</SelectContent>
</Select>
</div>
{form.buddy_type !== "group" && (
<div className="space-y-2">
<Label>Gender</Label>
<Select
value={form.gender ?? ""}
onValueChange={(v) =>
setForm({ ...form, gender: v || null })
}
>
<SelectTrigger>
<SelectValue placeholder="Select gender" />
</SelectTrigger>
<SelectContent>
{GENDER_OPTIONS.map((g) => (
<SelectItem key={g} value={g}>
{g || "Not set"}
</SelectItem>
))}
</SelectContent>
</Select>
</div>
)}
</div>
{/* Contact fields */}
<div className="grid grid-cols-2 gap-3 sm:grid-cols-4">
<div className="space-y-2">
<Label>Instagram</Label>
<Input
value={form.instagram ?? ""}
onChange={(e) =>
setForm({ ...form, instagram: e.target.value || null })
}
/>
</div>
<div className="space-y-2">
<Label>Discord</Label>
<Input
value={form.discord ?? ""}
onChange={(e) =>
setForm({ ...form, discord: e.target.value || null })
}
/>
</div>
<div className="space-y-2">
<Label>Phone</Label>
<Input
value={form.phone ?? ""}
onChange={(e) =>
setForm({ ...form, phone: e.target.value || null })
}
/>
</div>
<div className="space-y-2">
<Label>Email</Label>
<Input
value={form.email ?? ""}
onChange={(e) =>
setForm({ ...form, email: e.target.value || null })
}
/>
</div>
</div>
<div className="space-y-2">
<Label>Note</Label>
<textarea
value={form.note ?? ""}
onChange={(e) =>
setForm({ ...form, note: e.target.value || null })
}
placeholder="Optional notes about this buddy..."
className="flex min-h-[80px] w-full rounded-md border border-input bg-background px-3 py-2 text-sm shadow-xs placeholder:text-muted-foreground focus-visible:outline-hidden focus-visible:ring-1 focus-visible:ring-ring disabled:cursor-not-allowed disabled:opacity-50"
/>
</div>
<div className="flex gap-2">
<Button onClick={handleSave} disabled={saveMutation.isPending}>
{saveMutation.isPending && (
<Loader2 className="mr-2 h-4 w-4 animate-spin" />
)}
Save
</Button>
<Button variant="outline" onClick={() => setEditMode(false)}>
Cancel
</Button>
</div>
</CardContent>
</Card>
) : (
<>{/* Empty — contacts now shown under the name */}</>
)}
<Separator />
{/* Watch History — poster grid */}
<div className="space-y-4">
<h2 className="text-lg font-semibold">Watch History</h2>
{historyLoading ? (
<div className="grid grid-cols-4 gap-3 sm:grid-cols-5 md:grid-cols-6 lg:grid-cols-8">
{Array.from({ length: 6 }).map((_, i) => (
<Skeleton key={i} className="aspect-2/3 w-full rounded-lg" />
))}
</div>
) : watchedEntries.length === 0 ? (
<p className="text-sm text-muted-foreground">No watch history yet.</p>
) : (
<>
<div className="grid grid-cols-4 gap-3 sm:grid-cols-5 md:grid-cols-6 lg:grid-cols-8">
{(showAllHistory
? watchedEntries
: watchedEntries.slice(0, HISTORY_PREVIEW_COUNT)
).map((entry) => (
<Link
key={entry.title}
to={entry.link}
className="group space-y-2"
>
<div className="relative aspect-2/3 overflow-hidden rounded-lg bg-muted">
{entry.poster &&
entry.poster !== "/images/default-poster.png" ? (
<img
src={entry.poster}
alt=""
className="h-full w-full object-cover transition-transform group-hover:scale-105"
/>
) : (
<div className="flex h-full items-center justify-center text-xs text-muted-foreground">
No poster
</div>
)}
{entry.count > 1 && (
<Badge
variant="secondary"
className="absolute top-1.5 right-1.5 text-[10px]"
>
×{entry.count}
</Badge>
)}
</div>
<p className="truncate text-xs font-medium">{entry.title}</p>
</Link>
))}
</div>
{watchedEntries.length > HISTORY_PREVIEW_COUNT && (
<div className="flex justify-center">
<Button
variant="ghost"
size="sm"
onClick={() => setShowAllHistory(!showAllHistory)}
>
{showAllHistory ? (
<>
<ChevronUp className="mr-1 h-4 w-4" />
Show less
</>
) : (
<>
<ChevronDown className="mr-1 h-4 w-4" />
Show all ({watchedEntries.length})
</>
)}
</Button>
</div>
)}
</>
)}
</div>
{/* Timeline */}
<div className="space-y-4">
<h2 className="text-lg font-semibold">Timeline</h2>
{historyLoading ? (
<Skeleton className="h-48 w-full" />
) : timeline.length === 0 ? (
<p className="text-sm text-muted-foreground">No timeline yet.</p>
) : (
<div className="space-y-6">
{Object.entries(grouped).map(([month, items]) => (
<div key={month} className="space-y-2">
<h3 className="sticky top-0 z-10 bg-background py-1 text-sm font-semibold text-muted-foreground">
{month}
</h3>
<div className="space-y-1">
{items.map((item) => (
<Link
key={item.id}
to={item.link}
className="flex items-center gap-3 rounded-lg border border-border p-2 transition-colors hover:bg-accent/50"
>
<Badge variant="outline" className="shrink-0">
{item.type === "movie" ? (
<Film className="h-3 w-3" />
) : (
<Tv className="h-3 w-3" />
)}
</Badge>
<div className="min-w-0 flex-1">
<p className="truncate text-sm font-medium">
{item.title}
</p>
<p className="text-xs text-muted-foreground">
{format(new Date(item.date), "MMM d")} —{" "}
{item.subtitle}
</p>
</div>
</Link>
))}
</div>
</div>
))}
</div>
)}
</div>
<ConfirmDialog
open={showDeleteConfirm}
onOpenChange={setShowDeleteConfirm}
title="Delete Buddy"
description={`Are you sure you want to delete "${buddy.name}"? This cannot be undone.`}
confirmLabel="Delete"
variant="destructive"
onConfirm={() => deleteMutation.mutate()}
/>
{/* Profile picture upload dialog */}
<Dialog open={showUploadDialog} onOpenChange={setShowUploadDialog}>
<DialogContent className="sm:max-w-sm">
<DialogHeader>
<DialogTitle>Upload Profile Picture</DialogTitle>
</DialogHeader>
<div
className={`flex flex-col items-center justify-center gap-4 rounded-lg border-2 border-dashed p-8 transition-colors ${
uploadDragOver ? "border-primary bg-primary/5" : "border-border"
}`}
onDragOver={(e) => {
e.preventDefault();
setUploadDragOver(true);
}}
onDragLeave={() => setUploadDragOver(false)}
onDrop={(e) => {
e.preventDefault();
setUploadDragOver(false);
const file = e.dataTransfer.files?.[0];
if (file?.type.startsWith("image/")) setUploadFile(file);
}}
>
{uploadFile ? (
<div className="text-center">
<img
src={URL.createObjectURL(uploadFile)}
alt="Preview"
className="mx-auto mb-3 h-32 w-32 rounded-full object-cover"
/>
<p className="text-sm font-medium">{uploadFile.name}</p>
<Button
variant="ghost"
size="sm"
className="mt-1"
onClick={() => setUploadFile(null)}
>
Remove
</Button>
</div>
) : (
<>
<Upload className="h-8 w-8 text-muted-foreground" />
<p className="text-sm text-muted-foreground text-center">
Drag & drop an image here, or click to browse
</p>
<label className="cursor-pointer">
<input
type="file"
accept="image/*"
className="hidden"
onChange={(e) => {
const file = e.target.files?.[0];
if (file) setUploadFile(file);
}}
/>
<Button
variant="outline"
size="sm"
type="button"
onClick={(e) => {
const input = (e.currentTarget as HTMLElement)
.previousElementSibling as HTMLInputElement;
input?.click();
}}
>
Choose File
</Button>
</label>
</>
)}
</div>
<div className="flex justify-end gap-2">
<Button
variant="outline"
onClick={() => {
setShowUploadDialog(false);
setUploadFile(null);
}}
>
Cancel
</Button>
<Button onClick={handleUpload} disabled={!uploadFile || uploading}>
{uploading && <Loader2 className="mr-2 h-4 w-4 animate-spin" />}
Upload
</Button>
</div>
</DialogContent>
</Dialog>
</div>
);
}
+26
View File
@@ -76,6 +76,16 @@ const EntryCastsPage = lazy(() =>
const PeoplePage = lazy(() => const PeoplePage = lazy(() =>
import("@/pages/PeoplePage").then((m) => ({ default: m.PeoplePage })), import("@/pages/PeoplePage").then((m) => ({ default: m.PeoplePage })),
); );
const WatchBuddiesPage = lazy(() =>
import("@/pages/WatchBuddiesPage").then((m) => ({
default: m.WatchBuddiesPage,
})),
);
const WatchBuddyProfilePage = lazy(() =>
import("@/pages/WatchBuddyProfilePage").then((m) => ({
default: m.WatchBuddyProfilePage,
})),
);
const PersonDetailsPage = lazy(() => const PersonDetailsPage = lazy(() =>
import("@/pages/PersonDetailsPage").then((m) => ({ import("@/pages/PersonDetailsPage").then((m) => ({
default: m.PersonDetailsPage, default: m.PersonDetailsPage,
@@ -262,6 +272,22 @@ export const router = createRouter([
</SuspensePage> </SuspensePage>
), ),
}, },
{
path: "/watch-buddies",
element: (
<SuspensePage fallback={<PeopleSkeleton />}>
<WatchBuddiesPage />
</SuspensePage>
),
},
{
path: "/watch-buddies/:id",
element: (
<SuspensePage fallback={<PersonDetailsSkeleton />}>
<WatchBuddyProfilePage />
</SuspensePage>
),
},
{ {
path: "/settings", path: "/settings",
element: ( element: (
+21 -5
View File
@@ -15,9 +15,9 @@ export interface EntryRatings {
export interface Media { export interface Media {
id: number; id: number;
mediaable: 'entry' | 'people' | 'collection' | 'season' | 'episode'; mediaable: "entry" | "people" | "collection" | "season" | "episode";
mediaable_id: number; mediaable_id: number;
type: 'poster' | 'backdrop' | 'logo' | 'still' | 'profile'; type: "poster" | "backdrop" | "logo" | "still" | "profile";
path: string; path: string;
is_local: boolean; is_local: boolean;
is_selected: boolean; is_selected: boolean;
@@ -105,7 +105,7 @@ export interface Episode {
season?: Season; season?: Season;
} }
export type SeenAccuracy = 'EXACT' | 'ESTIMATED' | 'UNKNOWN'; export type SeenAccuracy = "EXACT" | "ESTIMATED" | "UNKNOWN";
export interface EntrySeen { export interface EntrySeen {
id: number; id: number;
@@ -115,6 +115,7 @@ export interface EntrySeen {
accuracy: SeenAccuracy; accuracy: SeenAccuracy;
createdAt: string; createdAt: string;
updatedAt: string; updatedAt: string;
buddies?: WatchBuddy[];
} }
export interface EpisodeSeen { export interface EpisodeSeen {
@@ -126,6 +127,8 @@ export interface EpisodeSeen {
accuracy: SeenAccuracy; accuracy: SeenAccuracy;
createdAt: string; createdAt: string;
updatedAt: string; updatedAt: string;
buddies?: WatchBuddy[];
episode?: Episode;
} }
export interface Collection { export interface Collection {
@@ -169,7 +172,7 @@ export interface Credit {
entry_id: number; entry_id: number;
people_id: number; people_id: number;
character: string | null; // might contain multiple separated by ; character: string | null; // might contain multiple separated by ;
cast_type: 'cast' | 'crew'; cast_type: "cast" | "crew";
department: string | null; department: string | null;
job: string | null; job: string | null;
episode_count?: number | null; episode_count?: number | null;
@@ -208,6 +211,19 @@ export interface Settings {
jwtSecret?: string; jwtSecret?: string;
} }
export interface WatchBuddy {
id: number;
name: string;
gender?: string | null;
instagram?: string | null;
discord?: string | null;
phone?: string | null;
email?: string | null;
note?: string | null;
buddy_type?: string;
medias?: Media[];
}
export interface Statistics { export interface Statistics {
totalMovies: number; totalMovies: number;
totalTvSeries: number; totalTvSeries: number;
@@ -253,7 +269,7 @@ export interface TmdbPaginatedResponse<T> {
export interface TmdbPreviewCredit { export interface TmdbPreviewCredit {
id: string | number; id: string | number;
cast_type: 'cast'; cast_type: "cast";
character: string | null; character: string | null;
people_id: number; people_id: number;
people: { people: {