Merge pull request #79 from KevinMidboe/api

Api
This commit is contained in:
2018-02-07 14:22:50 +01:00
committed by GitHub
11 changed files with 240 additions and 663 deletions

View File

@@ -0,0 +1,19 @@
class Media {
constructor(title, year, type) {
this.title = title;
this.year = year;
this.type = type;
}
toString() {
return `N: ${this.title} | Y: ${this.year} | T: ${this.type}`;
}
print() {
/* eslint-disable no-console */
console.log(this.toString());
}
}
module.exports = Media;

View File

@@ -1,21 +0,0 @@
class Movie {
constructor(title, year, type) {
this.id = undefined;
this.title = title;
this.year = year;
this.type = type;
this.release_date = undefined;
this.summary = undefined;
this.rating = undefined;
this.poster_path = undefined;
this.background = undefined;
this.genre = undefined;
this.date_added = undefined;
this.mediaInfo = undefined;
this.matchedInPlex = false;
}
}
module.exports = Movie;

View File

@@ -0,0 +1,22 @@
const Media = require('src/media_classes/media');
class Plex extends Media {
constructor(title, year, type, summary, poster_path, background_path, added, seasons, episodes) {
super(title, year, type);
this.summary = summary;
this.poster_path = poster_path;
this.background_path = background_path;
this.added = added;
this.seasons = seasons;
this.episodes = episodes;
}
print() {
super.print();
}
}
module.exports = Plex;

View File

@@ -1,22 +0,0 @@
class Movie {
constructor(title, year, type) {
this.id = undefined;
this.title = title;
this.year = year;
this.type = type;
this.release_date = undefined;
this.summary = undefined;
this.rating = undefined;
this.poster = undefined;
this.background = undefined;
this.genre = undefined;
this.added = undefined;
this.seasons = undefined;
this.episodes = undefined;
this.matchedInPlex = false;
}
}
module.exports = Movie;

View File

@@ -0,0 +1,33 @@
const Media = require('src/media_classes/media');
class TMDB extends Media {
// constructor(...args) {
constructor(title, year, type, id, summary, poster_path, background_path, popularity, score, release_status, tagline, seasons, episodes) {
super(title, year, type);
this.id = id;
this.summary = summary;
this.poster_path = poster_path;
this.background_path = background_path;
this.popularity = popularity;
this.score = score;
this.release_status = release_status;
this.tagline = tagline;
this.seasons = seasons;
this.episodes = episodes;
}
toString() {
return `${super.toString()} | ID: ${this.id}`;
}
print() {
/* eslint-disable no-console */
console.log(this.toString());
}
}
module.exports = TMDB;

View File

@@ -1,48 +1,24 @@
const Movie = require('src/media_classes/movie'); const Plex = require('src/media_classes/plex');
const Show = require('src/media_classes/show');
function convertPlexToSeasoned(plexObject) { function translateAdded(date_string) {
return new Date(date_string * 1000);
}
const mediaType = plexObject.type; function convertPlexToSeasoned(plex) {
// There are many diff types of content, we only want to look at movies and tv shows const title = plex.title;
if (mediaType === 'movie') { const year = plex.year;
const movie = new Movie(plexObject.title, plexObject.year, mediaType); const type = plex.type;
const summary = plex.summary;
const poster_path = plex.thumb;
const background_path = plex.art;
const added = translateAdded(plex.addedAt);
// const genre = plex.genre;
const seasons = plex.childCount;
const episodes = plex.leafCount;
movie.summary = plexObject.summary; const seasoned = new Plex(title, year, type, summary, poster_path, background_path, added, seasons, episodes);
movie.rating = plexObject.rating; // seasoned.print();
movie.poster = plexObject.thumb; return seasoned;
movie.background = plexObject.art;
movie.genre = plexObject.genre;
movie.added = new Date(plexObject.addedAt * 1000);
movie.mediaInfo = plexObject.Media;
// Don't need a for-loop when we have it in json format
file_sizes = []
for (let movie_info of plexObject.Media) {
for (let file_data of movie_info.Part) {
file_sizes.push(file_data.size)
}
}
movie.size = file_sizes;
return movie;
}
else if (mediaType === 'show') {
const show = new Show(plexObject.title, plexObject.year, mediaType);
show.summary = plexObject.summary;
show.rating = plexObject.rating;
show.poster = plexObject.thumb;
show.background = plexObject.art;
show.genre = plexObject.genre;
show.added = new Date(plexObject.addedAt * 1000);
show.seasons = plexObject.childCount;
show.episodes = plexObject.leafCount;
return show;
}
} }
module.exports = convertPlexToSeasoned; module.exports = convertPlexToSeasoned;

View File

@@ -1,57 +1,39 @@
const Movie = require('src/media_classes/movie');
const Show = require('src/media_classes/show');
function convertTmdbToSeasoned(tmdbObject, strictType=undefined) { const TMDB = require('src/media_classes/tmdb');
// TODO create a default fallback class to set the when falls to else as both are undefined
if (tmdbObject.media_type !== undefined)
var mediaType = tmdbObject.media_type;
else if (strictType !== undefined)
var mediaType = strictType;
else
var mediaType = 'movie';
// There are many diff types of content, we only want to look at movies and tv shows function translateYear(tmdbReleaseDate) {
if (mediaType === 'movie') { return new Date(tmdbReleaseDate).getFullYear();
const year = new Date(tmdbObject.release_date).getFullYear(); }
if (tmdbObject.title !== undefined) { function translateGenre(tmdbGenres) {
var title = tmdbObject.title; return tmdbGenres.map(genre => genre.name);
} else if (tmdbObject.name !== undefined) { }
var title = tmdbObject.name;
}
const movie = new Movie(title, year, mediaType); function convertTmdbToSeasoned(tmdb, manualType = undefined) {
const title = tmdb.title || tmdb.name;
const year = translateYear(tmdb.release_date || tmdb.first_air_date);
const type = tmdb.media_type || manualType;
movie.id = tmdbObject.id; const id = tmdb.id;
movie.summary = tmdbObject.overview; const summary = tmdb.overview;
movie.rating = tmdbObject.vote_average; const poster_path = tmdb.poster_path;
movie.poster_path = tmdbObject.poster_path; const background_path = tmdb.backdrop_path;
movie.background_path = tmdbObject.backdrop_path; const popularity = tmdb.popularity;
movie.genre = tmdbObject.genre_ids; const score = tmdb.vote_average;
// const genres = translateGenre(tmdb.genres);
const release_status = tmdb.status;
const tagline = tmdb.tagline;
movie.popularity = tmdbObject.popularity; const seasons = tmdb.number_of_seasons;
movie.vote_count = tmdbObject.vote_count; const episodes = tmdb.episodes;
return movie; const seasoned = new TMDB(
} title, year, type, id, summary, poster_path, background_path,
else if (mediaType === 'tv' || mediaType === 'show') { popularity, score, release_status, tagline, seasons, episodes,
const year = new Date(tmdbObject.first_air_date).getFullYear(); );
const show = new Show(tmdbObject.name, year, 'show'); // seasoned.print()
return seasoned;
show.id = tmdbObject.id;
show.summary = tmdbObject.overview;
show.rating = tmdbObject.vote_average;
show.poster_path = tmdbObject.poster_path;
show.background_path = tmdbObject.backdrop_path;
show.genre = tmdbObject.genre_ids;
show.popularity = tmdbObject.popularity;
show.vote_count = tmdbObject.vote_count;
return show;
}
} }
module.exports = convertTmdbToSeasoned; module.exports = convertTmdbToSeasoned;

View File

@@ -1,172 +1,134 @@
const moviedb = require('moviedb'); const moviedb = require('moviedb');
const convertTmdbToSeasoned = require('src/tmdb/convertTmdbToSeasoned'); const convertTmdbToSeasoned = require('src/tmdb/convertTmdbToSeasoned');
var methodTypes = { 'movie': 'searchMovie', 'show': 'searchTv', 'multi': 'searchMulti', 'movieInfo': 'movieInfo',
'tvInfo': 'tvInfo', 'upcomingMovies': 'miscUpcomingMovies', 'discoverMovie': 'discoverMovie',
'discoverShow': 'discoverTv', 'popularMovies': 'miscPopularMovies', 'popularShows': 'miscPopularTvs',
'nowPlayingMovies': 'miscNowPlayingMovies', 'nowAiringShows': 'tvOnTheAir', 'movieSimilar': 'movieSimilar',
'showSimilar': 'tvSimilar' };
const TMDB_METHODS = {
const TYPE_LIST = ['upcoming', 'discover', 'popular', 'nowplaying', 'similar'] upcoming: { movie: 'miscUpcomingMovies' },
const TMDB_TYPE_LIST = { discover: { movie: 'discoverMovie', show: 'discoverTv' },
'upcomingmovie': 'miscUpcomingMovies', 'discovermovie': 'discoverMovie', popular: { movie: 'miscPopularMovies', show: 'miscPopularTvs' },
'discovershow': 'discoverTv', 'popularmovie': 'miscPopularMovies', nowplaying: { movie: 'miscNowPlayingMovies', show: 'tvOnTheAir' },
'popularshow': 'miscPopularTvs', 'nowplayingmovie': 'miscNowPlayingMovies', similar: { movie: 'movieSimilar', show: 'tvSimilar' },
'nowplayingshow': 'tvOnTheAir', 'similarmovie': 'movieSimilar', 'similarshow': 'tvSimilar', search: { movie: 'searchMovie', show: 'searchTv', multi: 'searchMulti' },
info: { movie: 'movieInfo', show: 'tvInfo' },
}; };
class TMDB { class TMDB {
constructor(cache, apiKey, tmdbLibrary) {
this.cache = cache
this.tmdbLibrary = tmdbLibrary || moviedb(apiKey);
this.cacheTags = {
'search': 'se',
'info': 'i',
'upcoming': 'u',
'discover': 'd',
'popular': 'p',
'nowplaying': 'n',
'similar': 'si',
}
}
/** constructor(cache, apiKey, tmdbLibrary) {
* Retrive list of of items from TMDB matching the query and/or type given. this.cache = cache;
* @param {queryText, page, type} the page number to specify in the request for discover, this.tmdbLibrary = tmdbLibrary || moviedb(apiKey);
* @returns {Promise} dict with query results, current page and total_pages this.cacheTags = {
*/ search: 'se',
search(text, page = 1, type = 'multi') { info: 'i',
const query = { 'query': text, 'page': page }; upcoming: 'u',
const cacheKey = `${this.cacheTags.search}:${page}:${type}:${text}`; discover: 'd',
return Promise.resolve() popular: 'p',
.then(() => this.cache.get(cacheKey)) nowplaying: 'n',
.catch(() => this.tmdb(methodTypes[type], query)) similar: 'si',
.catch(() => { throw new Error('Could not search for movies/shows at tmdb.'); }) };
.then((response) => this.cache.set(cacheKey, response)) }
.then((response) => this.mapResults(response))
.catch((error) => { throw new Error(error); })
.then(([mappedResults, pagenumber, totalpages, total_results]) => {
return {'results': mappedResults, 'page': pagenumber, 'total_results': total_results, 'total_pages': totalpages}
})
}
/**
* Retrieve a specific movie by id from TMDB.
* @param {Number} identifier of the movie you want to retrieve
* @returns {Promise} succeeds if movie was found
*/
lookup(identifier, type = 'movie') {
const query = { id: identifier };
const cacheKey = `${this.cacheTags.info}:${type}:${identifier}`;
return Promise.resolve()
.then(() => this.cache.get(cacheKey))
.catch(() => this.tmdb(this.tmdbMethod('info', type), query))
.catch(() => { throw new Error('Could not find a movie with that id.'); })
.then(response => this.cache.set(cacheKey, response))
.then((response) => {
try {
return convertTmdbToSeasoned(response, type);
} catch (parseError) {
console.error(parseError);
throw new Error('Could not parse movie.');
}
});
}
/**
* Retrive list of of items from TMDB matching the query and/or type given.
* @param {queryText, page, type} the page number to specify in the request for discover,
* @returns {Promise} dict with query results, current page and total_pages
*/
search(text, page = 1, type = 'multi') {
const query = { query: text, page };
const cacheKey = `${this.cacheTags.search}:${page}:${type}:${text}`;
return Promise.resolve()
.then(() => this.cache.get(cacheKey))
.catch(() => this.tmdb(this.tmdbMethod('search', type), query))
.catch(() => { throw new Error('Could not search for movies/shows at tmdb.'); })
.then(response => this.cache.set(cacheKey, response))
.then(response => this.mapResults(response, type))
.catch((error) => { throw new Error(error); })
.then(([mappedResults, pagenumber, totalpages, total_results]) => ({
results: mappedResults, page: pagenumber, total_results, total_pages: totalpages,
}));
}
/** /**
* Retrieve a specific movie by id from TMDB. * Fetches a given list from tmdb.
* @param {Number} identifier of the movie you want to retrieve * @param {listName} List we want to fetch.
* @returns {Promise} succeeds if movie was found * @param {type} The to specify in the request for discover (default 'movie').
*/ * @param {id} When finding similar a id can be added to query
lookup(identifier, queryType = 'movie') { * @param {page} Page number we want to fetch.
var type, tmdbType; * @returns {Promise} dict with query results, current page and total_pages
if (queryType === 'movie' || queryType === 'movieInfo') { type = 'movie', tmdbType = 'movieInfo' } */
else if (queryType === 'show' || queryType === 'tvInfo') { type = 'show', tmdbType = 'tvInfo' } listSearch(listName, type = 'movie', id, page = '1') {
else { const params = { id, page };
return Promise.resolve() const cacheKey = `${this.cacheTags[listName]}:${type}:${id}:${page}`;
.then(() => { return Promise.resolve()
throw new Error('Invalid type declaration.') .then(() => this.cache.get(cacheKey))
}) .catch(() => this.tmdb(this.tmdbMethod(listName, type), params))
} .then(response => this.cache.set(cacheKey, response))
const query = { id: identifier }; .then(response => this.mapResults(response, type))
const cacheKey = `${this.cacheTags.lookup}:${type}:${identifier}`; .catch((error) => { throw new Error(error); })
return Promise.resolve() .then(([mappedResults, pagenumber, totalpages, total_results]) => ({
.then(() => this.cache.get(cacheKey)) results: mappedResults, page: pagenumber, total_pages: totalpages, total_results,
.catch(() => this.tmdb(tmdbType, query)) }));
.catch(() => { throw new Error('Could not find a movie with that id.'); }) }
.then((response) => this.cache.set(cacheKey, response))
.then((response) => {
try {
return convertTmdbToSeasoned(response, type);
} catch (parseError) {
throw new Error('Could not parse movie.');
}
});
}
/** tmdbMethod(apiMethod, type) {
* Verifies that a list_name corresponds to a tmdb list and calls the tmdb const method = TMDB_METHODS[apiMethod][type];
* api with list name and paramters. if (method !== undefined) return method;
* @param {list_name} The name of a list we want to search for. throw new Error('Could not find tmdb api method.');
* @param {media_type} The type declared in listSearch. }
* @param {params} Params is page and id given as parameters in listSearch.
* @returns {Promise} dict with raw tmdb results.
*/
searchTmdbList(list_name, media_type, params) {
return new Promise((resolve, reject) => {
if (TYPE_LIST.includes(list_name) && ['movie', 'show'].includes(media_type)) {
const searchQuery = list_name.toLowerCase() + media_type.toLowerCase();
const tmdbList = TMDB_TYPE_LIST[searchQuery]
return Promise.resolve()
.then(() => this.tmdb(tmdbList, params))
.then((response) => {
resolve(response)
})
.catch(() => {
return reject('Error while fetching from tmdb list.')
})
}
return reject('Did not find tmdb list matching query.')
})
}
/** /**
* Maps our response from tmdb api to a movie/show object. * Maps our response from tmdb api to a movie/show object.
* @param {response} JSON response from tmdb. * @param {response} JSON response from tmdb.
* @param {type} The type declared in listSearch. * @param {type} The type declared in listSearch.
* @returns {Promise} dict with tmdb results, mapped as movie/show objects. * @returns {Promise} dict with tmdb results, mapped as movie/show objects.
*/ */
mapResults(response, type) { mapResults(response, type) {
return Promise.resolve() return Promise.resolve()
.then(() => { .then(() => {
const mappedResults = response.results.map((result) => { const mappedResults = response.results.map(result => convertTmdbToSeasoned(result, type));
return convertTmdbToSeasoned(result, type) return [mappedResults, response.page, response.total_pages, response.total_results];
}) })
return [mappedResults, response.page, response.total_pages, response.total_results] .catch((error) => { throw new Error(error); });
}) }
.catch((error) => { throw new Error(error)})
tmdb(method, argument) {
} return new Promise((resolve, reject) => {
const callback = (error, reponse) => {
if (error) {
return reject(error);
}
return resolve(reponse);
};
/** if (!argument) {
* Fetches a given list from tmdb. this.tmdbLibrary[method](callback);
* @param {list_name} List we want to fetch. } else {
* @param {media_type} The to specify in the request for discover (default 'movie'). this.tmdbLibrary[method](argument, callback);
* @param {id} When finding similar a id can be added to query }
* @param {page} Page number we want to fetch. });
* @returns {Promise} dict with query results, current page and total_pages }
*/
listSearch(list_name, media_type='movie', id, page='1') {
const params = {'id': id, 'page': page}
const cacheKey = `${this.cacheTags[list_name]}:${media_type}:${id}:${page}`;
return Promise.resolve()
.then(() => this.cache.get(cacheKey))
.catch(() => this.searchTmdbList(list_name, media_type, params))
.then((response) => this.cache.set(cacheKey, response))
.then((response) => this.mapResults(response, media_type))
.catch((error) => { throw new Error(error); })
.then(([mappedResults, pagenumber, totalpages, total_results]) => {
return {'results': mappedResults, 'page': pagenumber, 'total_pages': totalpages, 'total_results': total_results}
})
}
tmdb(method, argument) {
return new Promise((resolve, reject) => {
const callback = (error, reponse) => {
if (error) {
return reject(error);
}
resolve(reponse);
};
if (!argument) {
this.tmdbLibrary[method](callback);
} else {
this.tmdbLibrary[method](argument, callback);
}
})
}
} }
module.exports = TMDB; module.exports = TMDB;

File diff suppressed because one or more lines are too long

View File

@@ -8,7 +8,7 @@ describe('As a user I want a forbidden error if the token is malformed', () => {
it('should return 401', () => it('should return 401', () =>
request(app) request(app)
.get('/api/v1/plex/requests/all') .get('/api/v1/pirate/search?query=test')
.set('Authorization', 'maLfOrMed TOKEN') .set('Authorization', 'maLfOrMed TOKEN')
.expect(401) .expect(401)
.then(response => assert.equal(response.body.error, 'You must be logged in.')) .then(response => assert.equal(response.body.error, 'You must be logged in.'))

View File

@@ -10,7 +10,7 @@ describe('As a user I want to request a movie', () => {
it('should return 200 when item is requested', () => it('should return 200 when item is requested', () =>
request(app) request(app)
.post('/api/v1/plex/request/31749') .post('/api/v1/plex/request/329865')
.set('Authorization', createToken('test_user', 'secret')) .set('Authorization', createToken('test_user', 'secret'))
.expect(200) .expect(200)
); );