identify-media
Version:
Analyse file path and content to make search criteria for media APIs
77 lines (67 loc) • 2.3 kB
text/typescript
import {AnalysedMedia, isAnalysedMovie, isAnalysedTVShow} from "../../lib/analyseFilePath";
import {OmdbEntry, OmdbSearchQuery, OmdbSearchResponse} from "./types";
import {Media} from "../index";
export const mapAnalysedMedia = (media: AnalysedMedia): OmdbSearchQuery => {
if (typeof media === 'string') return {s: media};
if (isAnalysedMovie(media) || isAnalysedTVShow(media)) return {s: media.name, type: media.type, y: media.year ? media.year.toString() : undefined};
throw new Error('media of unknown type: ' + JSON.stringify(media));
}
const makeImages = (entry: OmdbEntry): Record<string, string> => {
if (entry.Poster) {
return {'omdb-poster': entry.Poster}
}
return {};
}
const months: Record<string, string> = {
'Jan': '01',
'Feb': '02',
'Mar': '03',
'Apr': '04',
'May': '05',
'Jun': '06',
'Jul': '07',
'Aug': '08',
'Sep': '09',
'Oct': '10',
'Nov': '11',
'Dec': '12',
};
const dateRegex = /([0-9]{2}) ([a-z]+) ([0-9]{4})/i
const mapDate = (date: string): string|undefined => {
const result = dateRegex.exec(date)
if (result) return [result[3], months[result[2]], result[1]].join('-');
return undefined;
}
export const mapResult = (result: OmdbSearchResponse): Media[] => {
if (result.Error) throw new Error(result.Error);
if (!result.Search) throw new Error('No search result');
return result.Search.map((entry) => {
if (entry.Type === 'series') {
return {
type: 'tv',
name: entry.Title,
imdbId: entry.imdbID,
firstAirDate: mapDate(entry.Released),
mediaInfo: {
plot: entry.Plot,
images: makeImages(entry)
}
};
} else {
return {
type: 'movie',
title: entry.Title,
imdbId: entry.imdbID,
release: mapDate(entry.Released),
mediaInfo: {
plot: entry.Plot,
images: makeImages(entry)
}
}
}
});
}
export const isSameQuery = (a: OmdbSearchQuery, b: OmdbSearchQuery): boolean =>
a.y === b.y
&& a.s === b.s
&& a.type === b.type;