Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 3 additions & 0 deletions app/components/nav.vue
Original file line number Diff line number Diff line change
Expand Up @@ -103,6 +103,9 @@ nav {
<nuxt-link to="/my-shows?category=cancelled" class="nav-link" :class="{ active: $route.query.category === 'cancelled' }">
Cancelled
</nuxt-link>
<nuxt-link to="/my-shows?category=rewatch" class="nav-link" :class="{ active: $route.query.category === 'rewatch' }">
Rewatch
</nuxt-link>
<nuxt-link to="/watch-partners" class="nav-link" :class="{ active: $route.path === '/watch-partners' }">
Friends & Family
</nuxt-link>
Expand Down
3 changes: 1 addition & 2 deletions app/pages/my-shows.vue
Original file line number Diff line number Diff line change
@@ -1,13 +1,12 @@
<style lang="scss" scoped>
.sort-controls {
display: flex;
flex-wrap: wrap;
gap: .5rem;
align-items: center;
justify-content: end;
margin-top: 1rem;
margin-bottom: 1rem;
flex-wrap: wrap;

> div {
display: flex;
gap: .5rem;
Expand Down
40 changes: 38 additions & 2 deletions app/pages/show/[id].vue
Original file line number Diff line number Diff line change
Expand Up @@ -21,14 +21,15 @@ h1 {
display: grid;
gap: 1rem;
}
.show-tags,
.watching-with {
display: grid;
gap: 0.5rem;
label {
color: white;
font-weight: 600;
}
.watching-with-header {
.section-header {
display: flex;
gap: 1rem;
align-items: center;
Expand Down Expand Up @@ -56,10 +57,12 @@ h1 {
color: #d1d5db;
font-size: 0.9rem;
}
.tag-option,
.partner-options {
display: grid;
gap: 0.5rem;
}
.tag-option,
.partner-option {
display: flex;
gap: 0.6rem;
Expand Down Expand Up @@ -132,8 +135,22 @@ h1 {
<h1 v-html="name" />
<p v-html="description" />
<div class="info">
<div class="show-tags">
<div class="section-header">
<p>Tags:</p>
</div>
<label class="tag-option" for="rewatch">
<input
id="rewatch"
type="checkbox"
:checked="rewatch"
@change="updateRewatch"
>
<span>Rewatch</span>
</label>
</div>
<div class="watching-with">
<div class="watching-with-header">
<div class="section-header">
<p>Watching together with:</p>
<button
type="button"
Expand Down Expand Up @@ -213,6 +230,7 @@ export default defineComponent({
const show = ref<EpisodateShowTransformed | null>(null)
const partners = ref<{id:number, name:string}[]>([])
const selectedPartners = ref<number[]>([])
const rewatch = ref(false)

const loadPartners = async () => {
try {
Expand All @@ -234,6 +252,7 @@ export default defineComponent({
const showState = reactive(response.data.value) as EpisodateShowTransformed
show.value = showState
selectedPartners.value = showState.watchingWith.map(item => item.id)
rewatch.value = showState.rewatch

const seasons: ComputedRef<Season[]> = computed(() => {
if (show.value && show.value.episodes.length > 0) {
Expand All @@ -258,6 +277,21 @@ export default defineComponent({
await $fetch<{ success: boolean, watchedEpisodeIds: number[] }>(`/api/show/${showId}` as string, { method: 'PATCH', headers, body: { watchPartnerIds } })
}

async function updateRewatch (event: Event) {
const target = event.target as HTMLInputElement
rewatch.value = target.checked
await $fetch<{ success: boolean, watchedEpisodeIds: number[] }>(`/api/show/${showId}` as string, { method: 'PATCH', headers, body: { rewatch: rewatch.value } })
if (show.value) {
const hasRewatchTag = show.value.tags.some(tag => tag.slug === 'rewatch')
if (rewatch.value && !hasRewatchTag) {
show.value.tags = [...show.value.tags, { id: 0, slug: 'rewatch', name: 'Rewatch' }]
} else if (!rewatch.value) {
show.value.tags = show.value.tags.filter(tag => tag.slug !== 'rewatch')
}
show.value.rewatch = rewatch.value
}
}

async function updateWatchingWith (partnerId: number, event: Event) {
const target = event.target as HTMLInputElement
const selectedSet = new Set(selectedPartners.value)
Expand Down Expand Up @@ -309,6 +343,8 @@ export default defineComponent({
deleteShowCallback,
partners,
selectedPartners,
rewatch,
updateRewatch,
updateWatchingWith,
clearWatchingWith
}
Expand Down
18 changes: 18 additions & 0 deletions drizzle/0003_rewatch_shows.sql
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
CREATE TABLE IF NOT EXISTS `tags` (
`id` integer PRIMARY KEY AUTOINCREMENT NOT NULL,
`slug` text NOT NULL,
`name` text NOT NULL
);

CREATE UNIQUE INDEX IF NOT EXISTS `tagsSlugIdx` ON `tags` (`slug`);

CREATE TABLE IF NOT EXISTS `showTags` (
`showId` integer NOT NULL,
`tagId` integer NOT NULL,
FOREIGN KEY (`showId`) REFERENCES `tv_shows`(`id`) ON UPDATE no action ON DELETE cascade,
FOREIGN KEY (`tagId`) REFERENCES `tags`(`id`) ON UPDATE no action ON DELETE cascade
);

CREATE UNIQUE INDEX IF NOT EXISTS `showTagsIdx` ON `showTags` (`showId`,`tagId`);

INSERT OR IGNORE INTO `tags` (`slug`, `name`) VALUES ('rewatch', 'Rewatch');
29 changes: 28 additions & 1 deletion server/api/show/[id].get.ts
Original file line number Diff line number Diff line change
@@ -1,14 +1,18 @@
import type { H3Event } from 'h3'
import { eq, and, asc, sql, gt } from 'drizzle-orm'
import { getAuthenticatedUserEmail } from '../../lib/auth'
import { tvShows, users, episodateTvShows, episodes, showWatchPartners, watchPartners } from '../../db/schema'
import { tvShows, users, episodateTvShows, episodes, showWatchPartners, watchPartners, showTags, tags } from '../../db/schema'
import { useDb } from '../../lib/db'
import { getEpisodesForShow } from '../../lib/getEpisodesForShow'

function isWatchPartner (item: { id: number | null, name: string | null }): item is { id: number, name: string } {
return item.id !== null && item.name !== null
}

function isShowTag (item: { id: number | null, slug: string | null, name: string | null }): item is ShowTag {
return item.id !== null && item.slug !== null && item.name !== null
}

export default defineEventHandler(async (event: H3Event): Promise<EpisodateShowTransformed|null> => {
const userEmail = await getAuthenticatedUserEmail(event)

Expand Down Expand Up @@ -69,6 +73,11 @@ export default defineEventHandler(async (event: H3Event): Promise<EpisodateShowT
genres: episodateTvShows.genres,
pictures: episodateTvShows.pictures,
updatedAt: episodateTvShows.updatedAt,
rewatch: sql<boolean>`exists (
select 1 from ${showTags} st
join ${tags} t on t.id = st.tagId
where st.showId = ${tvShows.id} and t.slug = 'rewatch'
)`,
countdown: {
id: countdown.id,
season: countdown.season,
Expand Down Expand Up @@ -127,10 +136,28 @@ export default defineEventHandler(async (event: H3Event): Promise<EpisodateShowT
)

const episodesFromDb = await getEpisodesForShow(showId, userEmail, event)
const showTagsResponse = await DB.select({
id: tags.id,
slug: tags.slug,
name: tags.name
})
.from(tvShows)
.leftJoin(showTags, eq(showTags.showId, tvShows.id))
.leftJoin(tags, eq(tags.id, showTags.tagId))
.leftJoin(users, eq(users.id, tvShows.userId))
.where(
and(
eq(tvShows.showId, showId),
eq(users.email, userEmail),
sql`${tags.id} is not null`
)
)

return {
...showResponse[0],
tracked: true,
rewatch: Boolean(showResponse[0].rewatch),
tags: showTagsResponse.filter(isShowTag),
genres: showResponse[0]?.genres ? showResponse[0].genres.split(',') : [],
pictures: showResponse[0]?.pictures ? showResponse[0].pictures.split(',') : [],
episodes: episodesFromDb,
Expand Down
58 changes: 49 additions & 9 deletions server/api/show/[id].patch.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ import type { H3Event } from 'h3'
import { eq, and, inArray, sql } from 'drizzle-orm'
import type { BatchItem } from 'drizzle-orm/batch'
import { getShowExists } from '../../lib/getShowExists'
import { episodes, watchedEpisodes, users, tvShows, showWatchPartners, watchPartners } from '../../db/schema'
import { episodes, watchedEpisodes, users, tvShows, showWatchPartners, watchPartners, showTags, tags } from '../../db/schema'
import { getAuthenticatedUserEmail } from '../../lib/auth'
import { useDb } from '../../lib/db'
import { getUserByEmail } from '../../lib/getUserByEmail'
Expand Down Expand Up @@ -42,9 +42,14 @@ export default defineEventHandler(async (event: H3Event) => {

const hasEpisode = body.episode !== undefined
const hasWatchPartnerIds = body.watchPartnerIds !== undefined
const hasRewatch = body.rewatch !== undefined

if (!hasEpisode && !hasWatchPartnerIds) {
throw createError({ statusMessage: 'You must pass at least one supported field (episode or watchPartnerIds)', statusCode: 400 })
if (!hasEpisode && !hasWatchPartnerIds && !hasRewatch) {
throw createError({ statusMessage: 'You must pass at least one supported field (episode, watchPartnerIds or rewatch)', statusCode: 400 })
}

if (hasRewatch && typeof body.rewatch !== 'boolean') {
throw createError({ statusMessage: 'rewatch must be a boolean', statusCode: 400 })
}

if (hasWatchPartnerIds && !Array.isArray(body.watchPartnerIds)) {
Expand All @@ -56,7 +61,7 @@ export default defineEventHandler(async (event: H3Event) => {
}


const showRecord = Array.isArray(body.watchPartnerIds)
const showRecord = (Array.isArray(body.watchPartnerIds) || hasRewatch)
? await DB.select({ id: tvShows.id })
.from(tvShows)
.leftJoin(users, eq(users.id, tvShows.userId))
Expand All @@ -65,6 +70,20 @@ export default defineEventHandler(async (event: H3Event) => {
: []

let validWatchPartnerIds: number[] = []
let rewatchTagId = 0

if (hasRewatch) {
const rewatchTag = await DB.select({ id: tags.id })
.from(tags)
.where(eq(tags.slug, 'rewatch'))
.limit(1)

if (!rewatchTag[0]) {
throw createError({ statusMessage: 'Rewatch tag does not exist', statusCode: 500 })
}

rewatchTagId = rewatchTag[0].id
}

if (Array.isArray(body.watchPartnerIds) && body.watchPartnerIds.length > 0) {
// Validate that all provided IDs actually belong to the authenticated user
Expand All @@ -80,14 +99,35 @@ export default defineEventHandler(async (event: H3Event) => {
// Set up batch requests after validation so partner and episode mutations commit together.
const dbRequestBatch: BatchItem<'sqlite'>[] = []

if (Array.isArray(body.watchPartnerIds) && showRecord[0]) {
if (showRecord[0]) {
const showDbId = showRecord[0].id

dbRequestBatch.push(
DB.delete(showWatchPartners).where(eq(showWatchPartners.showId, showDbId))
)
if (hasRewatch) {
if (body.rewatch) {
dbRequestBatch.push(
DB.insert(showTags)
.values({ showId: showDbId, tagId: rewatchTagId })
.onConflictDoNothing()
)
} else {
dbRequestBatch.push(
DB.delete(showTags).where(
and(
eq(showTags.showId, showDbId),
eq(showTags.tagId, rewatchTagId)
)
)
)
}
}

if (Array.isArray(body.watchPartnerIds)) {
dbRequestBatch.push(
DB.delete(showWatchPartners).where(eq(showWatchPartners.showId, showDbId))
)
}

if (validWatchPartnerIds.length > 0) {
if (Array.isArray(body.watchPartnerIds) && validWatchPartnerIds.length > 0) {
dbRequestBatch.push(
DB.insert(showWatchPartners).values(validWatchPartnerIds.map((watchPartnerId: number) => ({
showId: showDbId,
Expand Down
31 changes: 27 additions & 4 deletions server/api/shows.get.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,11 +3,11 @@ import { asc, desc, eq, inArray, and, countDistinct, gt, sql, notInArray, lte }
import { alias } from 'drizzle-orm/sqlite-core'
import type { SQLiteSelect } from 'drizzle-orm/sqlite-core'
import { getAuthenticatedUserEmail } from '../lib/auth'
import { tvShows, users, episodateTvShows, episodes, watchedEpisodes, showWatchPartners } from '../db/schema'
import { tvShows, users, episodateTvShows, episodes, watchedEpisodes, showWatchPartners, showTags, tags } from '../db/schema'
import { pageSize as ps } from '../api/shows.get'
import { useDb } from '../lib/db'

type ShowCategory = 'wantToWatch'|'toCatchUpOn'|'waitingFor'|'cancelled'|''
type ShowCategory = 'wantToWatch'|'toCatchUpOn'|'waitingFor'|'cancelled'|'rewatch'|''
type SortType =
| 'alphabetical'
| 'episodesToWatch'
Expand Down Expand Up @@ -87,7 +87,20 @@ export default defineEventHandler(async (event: H3Event): Promise<CustomSearch>
: sql`1=1`,
watchingWith === -1
? sql`not exists (select 1 from ${showWatchPartners} swp where swp.showId = ${tvShows.id})`
: sql`1=1`
: sql`1=1`,
showCategory === 'rewatch'
? sql`exists (
select 1 from ${showTags} st
join ${tags} t on t.id = st.tagId
where st.showId = ${tvShows.id} and t.slug = 'rewatch'
)`
: showCategory
? sql`not exists (
select 1 from ${showTags} st
join ${tags} t on t.id = st.tagId
where st.showId = ${tvShows.id} and t.slug = 'rewatch'
)`
: sql`1=1`
)
)

Expand Down Expand Up @@ -130,6 +143,7 @@ export default defineEventHandler(async (event: H3Event): Promise<CustomSearch>
} else {
q = q.orderBy(order === 'asc' ? asc(episodateTvShows.name) : desc(episodateTvShows.name))
}

return q
}

Expand Down Expand Up @@ -206,7 +220,12 @@ export default defineEventHandler(async (event: H3Event): Promise<CustomSearch>
updatedAt: episodateTvShows.updatedAt,
watchedEpisodeCount: countDistinct(watchedEpisodes.id),
pastEpisodeCount: countDistinct(episodes.id),
episodesToWatch: sql<number>`count(distinct ${episodes.id}) - count(distinct ${watchedEpisodes.id})`
episodesToWatch: sql<number>`count(distinct ${episodes.id}) - count(distinct ${watchedEpisodes.id})`,
rewatch: sql<boolean>`exists (
select 1 from ${showTags} st
join ${tags} t on t.id = st.tagId
where st.showId = ${tvShows.id} and t.slug = 'rewatch'
)`
})
.from(episodateTvShows)
.$dynamic()
Expand Down Expand Up @@ -238,8 +257,12 @@ export default defineEventHandler(async (event: H3Event): Promise<CustomSearch>
])

const showsToReturn = batch[1].map((show) => {
const rewatch = Boolean(show.rewatch)

return {
...show,
rewatch,
tags: rewatch ? [{ id: 0, slug: 'rewatch', name: 'Rewatch' }] : [],
tracked: true
} as EpisodateShowFromSearchTransformed
})
Expand Down
19 changes: 19 additions & 0 deletions server/db/schema.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,25 @@ export const tvShows = sqliteTable('tv_shows', {
}
})

export const tags = sqliteTable('tags', {
id: integer('id').notNull().primaryKey({ autoIncrement: true }),
slug: text('slug').notNull(),
name: text('name').notNull()
}, (table) => {
return {
tagsSlugIdx: uniqueIndex('tagsSlugIdx').on(table.slug)
}
})

export const showTags = sqliteTable('showTags', {
showId: integer('showId').notNull().references(() => tvShows.id, { onDelete: 'cascade' }),
tagId: integer('tagId').notNull().references(() => tags.id, { onDelete: 'cascade' })
}, (table) => {
return {
showTagsIdx: uniqueIndex('showTagsIdx').on(table.showId, table.tagId)
}
})

export const episodateTvShows = sqliteTable('episodateTvShows', {
id: integer('id').notNull().primaryKey(),
name: text('name'),
Expand Down
Loading
Loading