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
const Franchise = require("../models/Franchise");
const Entry = require("../models/Entry");
const EntryId = require("../models/EntryId");
const EntryRating = require("../models/EntryRating");
const EntrySeen = require("../models/EntrySeen");
const Collection = require("../models/Collection");
const UserCollectionEntry = require("../models/UserCollectionEntry");
const Season = require("../models/Season");
const Episode = require("../models/Episode");
const EpisodeSeen = require("../models/EpisodeSeen");
const Genre = require("../models/Genre");
const EntryGenre = require("../models/EntryGenre");
const Media = require("../models/Media");
const Network = require("../models/Network");
const EntryNetwork = require("../models/EntryNetwork");
const People = require("../models/People");
const Credit = require("../models/Credit");
const Franchise = require('../models/Franchise');
const Entry = require('../models/Entry');
const EntryId = require('../models/EntryId');
const EntryRating = require('../models/EntryRating');
const EntrySeen = require('../models/EntrySeen');
const Collection = require('../models/Collection');
const UserCollectionEntry = require('../models/UserCollectionEntry');
const Season = require('../models/Season');
const Episode = require('../models/Episode');
const EpisodeSeen = require('../models/EpisodeSeen');
const Genre = require('../models/Genre');
const EntryGenre = require('../models/EntryGenre');
const Media = require('../models/Media');
const Network = require('../models/Network');
const EntryNetwork = require('../models/EntryNetwork');
const People = require('../models/People');
const Credit = require('../models/Credit');
const WatchBuddy = require('../models/WatchBuddy');
const EntrySeenBuddy = require('../models/EntrySeenBuddy');
const EpisodeSeenBuddy = require('../models/EpisodeSeenBuddy');
// ? one to one
// A hasOne B = A > B
@@ -26,221 +29,263 @@ const Credit = require("../models/Credit");
// * ENTRY & EntryId - ONE TO ONE
Entry.hasOne(EntryId, {
foreignKey: "entry_id",
as: "entryId",
onDelete: "CASCADE",
foreignKey: 'entry_id',
as: 'entryId',
onDelete: 'CASCADE',
});
EntryId.belongsTo(Entry, { foreignKey: "entry_id", as: "entry" });
EntryId.belongsTo(Entry, { foreignKey: 'entry_id', as: 'entry' });
// * ENTRY & EntryRating - ONE TO ONE
Entry.hasOne(EntryRating, {
foreignKey: "entry_id",
as: "entryRating",
onDelete: "CASCADE",
foreignKey: 'entry_id',
as: 'entryRating',
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.hasMany(EntrySeen, {
foreignKey: "entry_id",
as: "entrySeen",
onDelete: "CASCADE",
foreignKey: 'entry_id',
as: 'entrySeen',
onDelete: 'CASCADE',
});
EntrySeen.belongsTo(Entry, { foreignKey: "entry_id", as: "entry" });
EntrySeen.belongsTo(Entry, { foreignKey: 'entry_id', as: 'entry' });
// * ENTRY & LIST - MANY TO MANY
Entry.belongsToMany(Collection, {
through: UserCollectionEntry,
foreignKey: "entry_id",
otherKey: "user_collection_id",
onDelete: "CASCADE",
as: "collections",
foreignKey: 'entry_id',
otherKey: 'user_collection_id',
onDelete: 'CASCADE',
as: 'collections',
});
Collection.belongsToMany(Entry, {
through: UserCollectionEntry,
foreignKey: "user_collection_id",
otherKey: "entry_id",
onDelete: "CASCADE",
as: "entries",
foreignKey: 'user_collection_id',
otherKey: 'entry_id',
onDelete: 'CASCADE',
as: 'entries',
});
Entry.hasMany(UserCollectionEntry, {
foreignKey: "entry_id",
as: "userCollectionEntries",
foreignKey: 'entry_id',
as: 'userCollectionEntries',
});
UserCollectionEntry.belongsTo(Entry, { foreignKey: "entry_id", as: "entry" });
UserCollectionEntry.belongsTo(Entry, { foreignKey: 'entry_id', as: 'entry' });
Collection.hasMany(UserCollectionEntry, {
foreignKey: "user_collection_id",
as: "userCollectionEntries",
foreignKey: 'user_collection_id',
as: 'userCollectionEntries',
});
UserCollectionEntry.belongsTo(Collection, {
foreignKey: "user_collection_id",
as: "userCollection",
foreignKey: 'user_collection_id',
as: 'userCollection',
});
// * ENTRY & GENRE - MANY TO MANY
Entry.belongsToMany(Genre, {
through: EntryGenre,
foreignKey: "entry_id",
otherKey: "genre_id",
onDelete: "CASCADE",
as: "genres",
foreignKey: 'entry_id',
otherKey: 'genre_id',
onDelete: 'CASCADE',
as: 'genres',
});
Genre.belongsToMany(Entry, {
through: EntryGenre,
foreignKey: "genre_id",
otherKey: "entry_id",
onDelete: "CASCADE",
as: "entries",
foreignKey: 'genre_id',
otherKey: 'entry_id',
onDelete: 'CASCADE',
as: 'entries',
});
Entry.hasMany(EntryGenre, { foreignKey: "entry_id", as: "entryGenres" });
EntryGenre.belongsTo(Entry, { foreignKey: "entry_id", as: "entry" });
Genre.hasMany(EntryGenre, { foreignKey: "genre_id", as: "entryGenres" });
EntryGenre.belongsTo(Genre, { foreignKey: "genre_id", as: "genre" });
Entry.hasMany(EntryGenre, { foreignKey: 'entry_id', as: 'entryGenres' });
EntryGenre.belongsTo(Entry, { foreignKey: 'entry_id', as: 'entry' });
Genre.hasMany(EntryGenre, { foreignKey: 'genre_id', as: 'entryGenres' });
EntryGenre.belongsTo(Genre, { foreignKey: 'genre_id', as: 'genre' });
// * ENTRY & NETWORK - MANY TO MANY
Entry.belongsToMany(Network, {
through: EntryNetwork,
foreignKey: "entry_id",
otherKey: "network_id",
onDelete: "CASCADE",
as: "networks",
foreignKey: 'entry_id',
otherKey: 'network_id',
onDelete: 'CASCADE',
as: 'networks',
});
Network.belongsToMany(Entry, {
through: EntryNetwork,
foreignKey: "network_id",
otherKey: "entry_id",
onDelete: "CASCADE",
as: "entries",
foreignKey: 'network_id',
otherKey: 'entry_id',
onDelete: 'CASCADE',
as: 'entries',
});
// ! MEDIA
// * MEDIA & ENTRY - MANY TO ONE
Media.belongsTo(Entry, {
foreignKey: "mediaableId",
as: "entry",
foreignKey: 'mediaableId',
as: 'entry',
constraints: false,
where: {
mediaable: "entry",
mediaable: 'entry',
},
});
Entry.hasMany(Media, {
foreignKey: "mediaableId",
foreignKey: 'mediaableId',
constraints: false,
as: "medias",
scope: { mediaable: "entry" },
as: 'medias',
scope: { mediaable: 'entry' },
});
// * MEDIA & People - MANY TO ONE
Media.belongsTo(People, {
foreignKey: "mediaableId",
as: "people",
foreignKey: 'mediaableId',
as: 'people',
constraints: false,
where: {
mediaable: "people",
mediaable: 'people',
},
});
People.hasMany(Media, {
foreignKey: "mediaableId",
foreignKey: 'mediaableId',
constraints: false,
as: "medias",
scope: { mediaable: "people" },
as: 'medias',
scope: { mediaable: 'people' },
});
// * MEDIA & Collection - MANY TO ONE
Media.belongsTo(Collection, {
foreignKey: "mediaableId",
as: "collection",
foreignKey: 'mediaableId',
as: 'collection',
constraints: false,
where: {
mediaable: "collection",
mediaable: 'collection',
},
});
Collection.hasMany(Media, {
foreignKey: "mediaableId",
foreignKey: 'mediaableId',
constraints: false,
as: "medias",
scope: { mediaable: "collection" },
as: 'medias',
scope: { mediaable: 'collection' },
});
// * MEDIA & Season - MANY TO ONE
Media.belongsTo(Season, {
foreignKey: "mediaableId",
as: "season",
foreignKey: 'mediaableId',
as: 'season',
constraints: false,
where: {
mediaable: "season",
mediaable: 'season',
},
});
Season.hasMany(Media, {
foreignKey: "mediaableId",
foreignKey: 'mediaableId',
constraints: false,
as: "medias",
scope: { mediaable: "season" },
as: 'medias',
scope: { mediaable: 'season' },
});
// * MEDIA & Episode - MANY TO ONE
Media.belongsTo(Episode, {
foreignKey: "mediaableId",
as: "episode",
foreignKey: 'mediaableId',
as: 'episode',
constraints: false,
where: {
mediaable: "episode",
mediaable: 'episode',
},
});
Episode.hasMany(Media, {
foreignKey: "mediaableId",
foreignKey: 'mediaableId',
constraints: false,
as: "medias",
scope: { mediaable: "episode" },
as: 'medias',
scope: { mediaable: 'episode' },
});
// ! MEDIA END
// * ENTRY & SEASON - ONE TO MANY
Entry.hasMany(Season, {
foreignKey: "entry_id",
as: "seasons",
onDelete: "CASCADE",
foreignKey: 'entry_id',
as: 'seasons',
onDelete: 'CASCADE',
});
Season.belongsTo(Entry, { foreignKey: "entry_id", as: "entry" });
Season.belongsTo(Entry, { foreignKey: 'entry_id', as: 'entry' });
// * SEASON & EPISODE - ONE TO MANY
Season.hasMany(Episode, { foreignKey: "season_id", onDelete: "CASCADE" });
Episode.belongsTo(Season, { foreignKey: "season_id" });
Season.hasMany(Episode, { foreignKey: 'season_id', onDelete: 'CASCADE' });
Episode.belongsTo(Season, { foreignKey: 'season_id' });
// * EPISODE & EPISODE_SEEN - ONE TO MANY
Episode.hasMany(EpisodeSeen, { foreignKey: "episode_id", onDelete: "CASCADE" });
EpisodeSeen.belongsTo(Episode, { foreignKey: "episode_id" });
Episode.hasMany(EpisodeSeen, { foreignKey: 'episode_id', onDelete: 'CASCADE' });
EpisodeSeen.belongsTo(Episode, { foreignKey: 'episode_id' });
// * ENTRY & EPISODE_SEEN - ONE TO MANY
Entry.hasMany(EpisodeSeen, { foreignKey: "entry_id", onDelete: "CASCADE" });
EpisodeSeen.belongsTo(Entry, { foreignKey: "entry_id" });
Entry.hasMany(EpisodeSeen, { foreignKey: 'entry_id', onDelete: 'CASCADE' });
EpisodeSeen.belongsTo(Entry, { foreignKey: 'entry_id' });
// * ----
Franchise.hasMany(Entry, { foreignKey: "franchise_id" });
Entry.belongsTo(Franchise, { foreignKey: "franchise_id" });
Franchise.hasMany(Entry, { foreignKey: 'franchise_id' });
Entry.belongsTo(Franchise, { foreignKey: 'franchise_id' });
// * ENTRY & Credit - ONE TO MANY
Entry.hasMany(Credit, {
foreignKey: "entry_id",
as: "credits",
onDelete: "CASCADE",
foreignKey: 'entry_id',
as: 'credits',
onDelete: 'CASCADE',
});
Credit.belongsTo(Entry, { foreignKey: "entry_id", as: "entry" });
Credit.belongsTo(Entry, { foreignKey: 'entry_id', as: 'entry' });
// * PEOPLE & CAST - ONE TO MANY
People.hasMany(Credit, {
foreignKey: "people_id",
as: "roles",
onDelete: "CASCADE",
foreignKey: 'people_id',
as: 'roles',
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 EntrySeen = require('../models/EntrySeen');
const Entry = require("../models/Entry");
const EntrySeen = require("../models/EntrySeen");
const WatchBuddy = require("../models/WatchBuddy");
class EntrySeenController {
constructor() {
@@ -18,34 +19,37 @@ class EntrySeenController {
const entrySeen = await EntrySeen.findByPk(req.params.id);
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);
}
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);
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({
entry_id,
date_seen,
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
if (
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();
}
@@ -56,7 +60,8 @@ class EntrySeenController {
const { entryId } = req.params;
const entrySeens = await EntrySeen.findAll({
where: { entry_id: entryId },
order: [['date_seen', 'DESC']],
order: [["date_seen", "DESC"]],
include: [{ model: WatchBuddy, as: "buddies" }],
});
if (entrySeens.length > 0) {
@@ -64,30 +69,34 @@ class EntrySeenController {
} else {
res
.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) {
const { date_seen, seen_with } = req.body;
const updated = await EntrySeen.update(
const { date_seen, seen_with, buddy_ids } = req.body;
await EntrySeen.update(
{ date_seen, seen_with },
{ where: { id: req.params.id } },
);
if (updated[0] > 0) {
const updatedEntrySeen = await EntrySeen.findByPk(req.params.id);
res.status(200).json(updatedEntrySeen);
} else {
res.status(404).json({ message: 'Entry seen record not found.' });
const record = await EntrySeen.findByPk(req.params.id);
if (!record) {
return 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) {
const entrySeen = await EntrySeen.findByPk(req.params.id);
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();
+34 -26
View File
@@ -1,7 +1,8 @@
const Entry = require('../models/Entry');
const Episode = require('../models/Episode');
const EpisodeSeen = require('../models/EpisodeSeen');
const Season = require('../models/Season');
const Entry = require("../models/Entry");
const Episode = require("../models/Episode");
const EpisodeSeen = require("../models/EpisodeSeen");
const Season = require("../models/Season");
const WatchBuddy = require("../models/WatchBuddy");
class EpisodeSeenController {
constructor() {
@@ -25,7 +26,7 @@ class EpisodeSeenController {
const episodeSeen = await EpisodeSeen.findByPk(req.params.id);
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);
@@ -36,15 +37,15 @@ class EpisodeSeenController {
async createEpisodeSeen(req, res) {
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);
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);
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({
entry_id,
episode_id,
@@ -52,12 +53,17 @@ class EpisodeSeenController {
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
if (
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();
}
@@ -73,7 +79,8 @@ class EpisodeSeenController {
const { episodeId } = req.params;
const episodeSeens = await EpisodeSeen.findAll({
where: { episode_id: episodeId },
order: [['date_seen', 'DESC']],
order: [["date_seen", "DESC"]],
include: [{ model: WatchBuddy, as: "buddies" }],
});
if (episodeSeens.length > 0) {
@@ -81,7 +88,7 @@ class EpisodeSeenController {
} else {
res
.status(404)
.json({ message: 'No records found for the given episode ID.' });
.json({ message: "No records found for the given episode ID." });
}
} catch (error) {
res.status(500).json({ error: error.message });
@@ -99,17 +106,18 @@ class EpisodeSeenController {
include: [
{
model: Season,
attributes: ['season_number'],
attributes: ["season_number"],
},
],
attributes: ['episode_number'],
attributes: ["episode_number"],
},
{ model: WatchBuddy, as: "buddies" },
],
order: [
['date_seen', 'DESC'],
[{ model: Episode }, { model: Season }, 'season_number', 'DESC'],
["date_seen", "DESC"],
[{ model: Episode }, { model: Season }, "season_number", "DESC"],
// [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) {
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);
if (!episodeSeen)
return res
.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) {
res.status(200).json(updated);
} else {
res.status(404).json({ message: 'Episode seen record not found.' });
if (Array.isArray(buddy_ids)) {
await episodeSeen.setBuddies(buddy_ids);
}
res.status(200).json(episodeSeen);
} catch (error) {
res.status(500).json({ error: error.message });
}
@@ -147,7 +155,7 @@ class EpisodeSeenController {
// ? getting the episode seen object
const oldEpisodeSeen = await EpisodeSeen.findByPk(req.params.id);
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
const deleted = await oldEpisodeSeen.destroy();
+1
View File
@@ -52,6 +52,7 @@ class MediaController {
"seasons",
"episodes",
"peoples",
"watch-buddies",
].includes(category)
) {
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 configService = require('../services/configService');
const jwt = require("jsonwebtoken");
const configService = require("../services/configService");
function authMiddleware(req, res, next) {
// Skip auth for login/verify endpoints
if (req.path === '/auth/login' || req.path === '/auth/verify') {
// Skip auth for login/verify/media endpoints
if (
req.path === "/auth/login" ||
req.path === "/auth/verify" ||
req.path.startsWith("/media/")
) {
return next();
}
const auth = req.headers.authorization;
if (!auth || !auth.startsWith('Bearer ')) {
return res.status(401).json({ error: 'Authentication required' });
if (!auth || !auth.startsWith("Bearer ")) {
return res.status(401).json({ error: "Authentication required" });
}
const settings = configService.getSettings();
const jwtSecret = settings.jwtSecret || 'showy-default-secret';
const jwtSecret = settings.jwtSecret || "showy-default-secret";
try {
jwt.verify(auth.slice(7), jwtSecret);
next();
} 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": "",
"main": "server.js",
"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"
},
"pkg": {
+2
View File
@@ -14,9 +14,11 @@ const importRouter = require('./import.routes');
const peopleRouter = require('./people.routes');
const aiQueryRouter = require('./ai-query.routes');
const authRouter = require('./auth.routes');
const watchBuddyRouter = require('./watch-buddy.routes');
const router = express.Router();
router.use('/auth', authRouter);
router.use('/watch-buddies', watchBuddyRouter);
router.use('/media', mediaRouter);
router.use('/entries', entryRouter);
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 bodyParser = require('body-parser');
const routes = require('./routes/routes.js');
const sequelize = require('./config/database.js');
const express = require("express");
const bodyParser = require("body-parser");
const routes = require("./routes/routes.js");
const sequelize = require("./config/database.js");
const app = express();
// Global error handling for unhandled promise rejections
process.on('unhandledRejection', (reason, promise) => {
console.log('Unhandled Rejection at:', promise, 'reason:', reason);
process.on("unhandledRejection", (reason, promise) => {
console.log("Unhandled Rejection at:", promise, "reason:", reason);
// Application specific logging, throwing an error, or other logic here
});
// Global error handling for uncaught exceptions
process.on('uncaughtException', (error) => {
console.log('Uncaught Exception:', error);
process.on("uncaughtException", (error) => {
console.log("Uncaught Exception:", error);
// Application specific logging, throwing an error, or other logic here
process.exit(1); // Exit the process to avoid undefined state
});
const relations = require('./config/relations.js');
const sequelizeHooks = require('./config/sequelizeHooks.js');
const { initializeData } = require('./config/dataInitializer.js');
const killerRouter = require('./routes/killer.routes.js');
const errorHandler = require('./middleware/errorHandler');
const authMiddleware = require('./middleware/authMiddleware');
const configService = require('./services/configService.js');
const { logToFile } = require('./services/logService.js');
const { generatePreview } = require('./services/mediaService.js');
const relations = require("./config/relations.js");
const sequelizeHooks = require("./config/sequelizeHooks.js");
const { initializeData } = require("./config/dataInitializer.js");
const killerRouter = require("./routes/killer.routes.js");
const errorHandler = require("./middleware/errorHandler");
const authMiddleware = require("./middleware/authMiddleware");
const configService = require("./services/configService.js");
const { logToFile } = require("./services/logService.js");
const { generatePreview } = require("./services/mediaService.js");
// ? variables
let settings = configService.getSettings();
const PORT = settings['backPort'] || 4000;
const parrentProcess = JSON.parse(process.env.PARENT_PROCESS || '{}');
const PORT = settings["backPort"] || 4000;
const parrentProcess = JSON.parse(process.env.PARENT_PROCESS || "{}");
// ? Middleware
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
app.use((req, res, next) => {
res.header('Access-Control-Allow-Origin', '*');
res.header("Access-Control-Allow-Origin", "*");
res.header(
'Access-Control-Allow-Headers',
'Origin, X-Requested-With, Content-Type, Accept, Authorization',
"Access-Control-Allow-Headers",
"Origin, X-Requested-With, Content-Type, Accept, Authorization",
);
if (req.method === 'OPTIONS') {
res.header('Access-Control-Allow-Methods', 'PUT, POST, PATCH, DELETE, GET');
if (req.method === "OPTIONS") {
res.header("Access-Control-Allow-Methods", "PUT, POST, PATCH, DELETE, GET");
return res.status(200).json({});
}
next();
});
// ? other api routes
app.use('/api/v1', authMiddleware, routes);
app.use("/api/v1", authMiddleware, routes);
// ? Error handling middleware
app.use(errorHandler);
// ? KILLER ROUTE: used to crash the backend
app.use('/killer', killerRouter);
app.use("/killer", killerRouter);
// * Start the server
const doUpdate = false;
const doForce = false;
console.log('Server started');
console.log("Server started");
console.log(`Syncing database schema...`);
sequelize
// .sync({force: true}) // will drop all tables and recreate them.
@@ -77,6 +77,6 @@ sequelize
});
})
.catch((err) => {
console.log('____________SEQUELIZE SYNC ERROR____________');
console.log("____________SEQUELIZE SYNC ERROR____________");
console.log(err);
});