identify-media
Version:
Analyse file path and content to make search criteria for media APIs
46 lines (39 loc) • 1.3 kB
text/typescript
import {RequestConfig} from "../index";
import {ListSubtitlesArgs} from "./types";
const keyMappings: Record<string, string> = {
hash: 'moviehash-',
size: 'moviebytesize-',
imdbId: 'imdbid-',
query: 'query-',
episode: 'episode-',
season: 'season-',
language: 'sublanguageid-',
tags: 'tags-',
}
const imdbRex = /tt(\d{7,9})/;
const mapKeyValue = (key: string, value: unknown): string | undefined => {
if (!value) return undefined;
if (key === 'imdbId') {
const imdbIdReg = imdbRex.exec(value as string);
if (!imdbIdReg) return undefined
return `${keyMappings[key]}${imdbIdReg[1]}`
}
if (typeof value === 'string') {
return `${keyMappings[key]}${encodeURI(value)}`;
}
return `${keyMappings[key]}${value}`;
}
const mapKeys = (args: ListSubtitlesArgs): string =>
Object.entries(args).map(([key, value]) => mapKeyValue(key, value))
.filter((key) => !!key).sort().join('/').toLocaleLowerCase();
const search = (args: ListSubtitlesArgs, userAgent: string): RequestConfig => {
return {
baseURL: 'https://rest.opensubtitles.org',
method: 'GET',
headers: {
'X-User-Agent': userAgent,
},
url: `/search/${mapKeys(args)}`,
}
};
export default search;