From 545ac8bb7bd21ef8071bd9f7af5d3a59d44f85b1 Mon Sep 17 00:00:00 2001
From: castdrian <adrifcastr@gmail.com>
Date: Thu, 29 Jun 2023 21:21:24 +0200
Subject: [PATCH] reduce code duplication

---
 src/backend/metadata/getmeta.ts | 19 +++++++------------
 src/backend/metadata/tmdb.ts    | 25 +++++++++++++++++--------
 2 files changed, 24 insertions(+), 20 deletions(-)

diff --git a/src/backend/metadata/getmeta.ts b/src/backend/metadata/getmeta.ts
index ff83c743..6081e5ad 100644
--- a/src/backend/metadata/getmeta.ts
+++ b/src/backend/metadata/getmeta.ts
@@ -1,8 +1,8 @@
 import { FetchError } from "ofetch";
-import slugify from "slugify";
 
 import { formatJWMeta, mediaTypeToJW } from "./justwatch";
 import {
+  TMDBIdToUrlId,
   TMDBMediaToMediaType,
   formatTMDBMeta,
   getEpisodes,
@@ -187,17 +187,12 @@ export async function convertLegacyUrl(
   // movies always have an imdb id on tmdb
   if (imdbId && mediaType === MWMediaType.MOVIE) {
     const movieId = await getMovieFromExternalId(imdbId);
-    if (movieId)
-      return `/media/tmdb-movie-${movieId}-${slugify(meta.meta.title, {
-        lower: true,
-        strict: true,
-      })}`;
-  }
+    if (movieId) {
+      return `/media/${TMDBIdToUrlId(mediaType, movieId, meta.meta.title)}`;
+    }
 
-  if (tmdbId) {
-    return `/media/tmdb-${type}-${tmdbId}-${slugify(meta.meta.title, {
-      lower: true,
-      strict: true,
-    })}`;
+    if (tmdbId) {
+      return `/media/${TMDBIdToUrlId(mediaType, tmdbId, meta.meta.title)}`;
+    }
   }
 }
diff --git a/src/backend/metadata/tmdb.ts b/src/backend/metadata/tmdb.ts
index 596dd96d..64304900 100644
--- a/src/backend/metadata/tmdb.ts
+++ b/src/backend/metadata/tmdb.ts
@@ -79,15 +79,23 @@ export function formatTMDBMeta(
   };
 }
 
-export function TMDBMediaToId(media: MWMediaMeta): string {
+export function TMDBIdToUrlId(
+  type: MWMediaType,
+  tmdbId: string,
+  title: string
+) {
   return [
     "tmdb",
-    mediaTypeToTMDB(media.type),
-    media.id,
-    slugify(media.title, { lower: true, strict: true }),
+    mediaTypeToTMDB(type),
+    tmdbId,
+    slugify(title, { lower: true, strict: true }),
   ].join("-");
 }
 
+export function TMDBMediaToId(media: MWMediaMeta): string {
+  return TMDBIdToUrlId(media.type, media.id, media.title);
+}
+
 export function decodeTMDBId(
   paramId: string
 ): { id: string; type: MWMediaType } | null {
@@ -178,10 +186,11 @@ export async function generateQuickSearchMediaUrl(
   const type = result.media_type === "movie" ? "movie" : "show";
   const title = result.media_type === "movie" ? result.title : result.name;
 
-  return `/media/tmdb-${type}-${result.id}-${slugify(title, {
-    lower: true,
-    strict: true,
-  })}`;
+  return `/media/${TMDBIdToUrlId(
+    TMDBMediaToMediaType(type),
+    result.id.toString(),
+    title
+  )}`;
 }
 
 // Conditional type which for inferring the return type based on the content type