Merge branch 'master' of github.com:kevinmidboe/seasonedShows

This commit is contained in:
2018-02-07 14:25:31 +01:00
66 changed files with 1106 additions and 1586 deletions

View File

@@ -1,3 +1,12 @@
{
"extends": "airbnb-base"
}
"extends": [
"airbnb-base"
],
"rules": {
"indent": ["error", 3],
"prefer-destructuring": 0,
"camelcase": 0,
"import/no-unresolved": 0,
"import/no-extraneous-dependencies": 0
}
}

View File

@@ -5,7 +5,7 @@
"start": "cross-env SEASONED_CONFIG=conf/development.json NODE_PATH=. node src/webserver/server.js",
"test": "cross-env SEASONED_CONFIG=conf/development.json NODE_PATH=. mocha --recursive test/system",
"coverage": "cross-env PLANFLIX_CONFIG=conf/test.json NODE_PATH=. istanbul cover -x script/autogenerate-documentation.js --include-all-sources --dir test/.coverage node_modules/mocha/bin/_mocha --recursive test/**/* -- --report lcovonly && cat test/.coverage/lcov.info | coveralls && rm -rf test/.coverage",
"lint": "./node_modules/.bin/eslint src/webserver/"
"lint": "./node_modules/.bin/eslint src/"
},
"dependencies": {
"bcrypt-nodejs": "^0.0.3",

View File

@@ -4,40 +4,40 @@ const Field = require('./field.js');
let instance = null;
class Config {
constructor() {
this.location = Config.determineLocation();
this.fields = require(`${this.location}`);
}
constructor() {
this.location = Config.determineLocation();
this.fields = require(`${this.location}`);
}
static getInstance() {
if (instance == null) {
instance = new Config();
}
return instance;
}
static getInstance() {
if (instance == null) {
instance = new Config();
}
return instance;
}
static determineLocation() {
return path.join(__dirname, '..', '..', process.env.SEASONED_CONFIG);
}
static determineLocation() {
return path.join(__dirname, '..', '..', process.env.SEASONED_CONFIG);
}
get(section, option) {
if (this.fields[section] === undefined || this.fields[section][option] === undefined) {
throw new Error(`Filed "${section} => ${option}" does not exist.`);
}
get(section, option) {
if (this.fields[section] === undefined || this.fields[section][option] === undefined) {
throw new Error(`Filed "${section} => ${option}" does not exist.`);
}
const field = new Field(this.fields[section][option])
const field = new Field(this.fields[section][option]);
if (field.value === '') {
const envField = process.env[[section.toUpperCase(), option.toUpperCase()].join('_')]
if (envField !== undefined && envField.length !== 0) { return envField }
}
if (field.value === '') {
const envField = process.env[[section.toUpperCase(), option.toUpperCase()].join('_')];
if (envField !== undefined && envField.length !== 0) { return envField; }
}
if (field.value === undefined) {
throw new Error(`${section} => ${option} is empty.`);
}
if (field.value === undefined) {
throw new Error(`${section} => ${option} is empty.`);
}
return field.value;
}
return field.value;
}
}
module.exports = Config;
module.exports = Config;

View File

@@ -1,16 +1,15 @@
class EnvironmentVariables {
constructor(variables) {
this.variables = variables || process.env;
}
constructor(variables) {
this.variables = variables || process.env;
}
get(variable) {
return this.variables[variable];
}
get(variable) {
return this.variables[variable];
}
has(variable) {
return this.get(variable) !== undefined;
}
has(variable) {
return this.get(variable) !== undefined;
}
}
module.exports = EnvironmentVariables;

View File

@@ -2,49 +2,48 @@ const Filters = require('./filters.js');
const EnvironmentVariables = require('./environmentVariables.js');
class Field {
constructor(rawValue, environmentVariables) {
this.rawValue = rawValue;
this.filters = new Filters(rawValue);
this.valueWithoutFilters = this.filters.removeFiltersFromValue();
this.environmentVariables = new EnvironmentVariables(environmentVariables);
}
constructor(rawValue, environmentVariables) {
this.rawValue = rawValue;
this.filters = new Filters(rawValue);
this.valueWithoutFilters = this.filters.removeFiltersFromValue();
this.environmentVariables = new EnvironmentVariables(environmentVariables);
}
get value() {
if (this.filters.isEmpty()) {
return this.valueWithoutFilters;
}
get value() {
if (this.filters.isEmpty()) {
return this.valueWithoutFilters;
}
if (this.filters.has('base64') && !this.filters.has('env')) {
return Field.base64Decode(this.valueWithoutFilters);
}
if (this.filters.has('base64') && !this.filters.has('env')) {
return Field.base64Decode(this.valueWithoutFilters);
}
if (this.environmentVariables.has(this.valueWithoutFilters) &&
this.environmentVariables.get(this.valueWithoutFilters) === '') {
return undefined;
}
if (this.environmentVariables.has(this.valueWithoutFilters) &&
this.environmentVariables.get(this.valueWithoutFilters) === '') {
return undefined;
}
if (!this.filters.has('base64') && this.filters.has('env')) {
if (this.environmentVariables.has(this.valueWithoutFilters)) {
return this.environmentVariables.get(this.valueWithoutFilters);
}
return undefined;
}
if (!this.filters.has('base64') && this.filters.has('env')) {
if (this.environmentVariables.has(this.valueWithoutFilters)) {
return this.environmentVariables.get(this.valueWithoutFilters);
}
return undefined;
}
if (this.filters.has('env') && this.filters.has('base64')) {
if (this.environmentVariables.has(this.valueWithoutFilters)) {
const encodedEnvironmentVariable = this.environmentVariables.get(this.valueWithoutFilters);
return Field.base64Decode(encodedEnvironmentVariable);
}
return undefined;
}
if (this.filters.has('env') && this.filters.has('base64')) {
if (this.environmentVariables.has(this.valueWithoutFilters)) {
const encodedEnvironmentVariable = this.environmentVariables.get(this.valueWithoutFilters);
return Field.base64Decode(encodedEnvironmentVariable);
}
return undefined;
}
return this.valueWithoutFilters;
}
return this.valueWithoutFilters;
}
static base64Decode(string) {
return new Buffer(string, 'base64').toString('utf-8');
}
static base64Decode(string) {
return new Buffer(string, 'base64').toString('utf-8');
}
}
module.exports = Field;
module.exports = Field;

View File

@@ -1,35 +1,34 @@
class Filters {
constructor(value) {
this.value = value;
this.delimiter = '|';
}
constructor(value) {
this.value = value;
this.delimiter = '|';
}
get filters() {
return this.value.split(this.delimiter).slice(0, -1);
}
get filters() {
return this.value.split(this.delimiter).slice(0, -1);
}
isEmpty() {
return !this.hasValidType() || this.value.length === 0;
}
isEmpty() {
return !this.hasValidType() || this.value.length === 0;
}
has(filter) {
return this.filters.includes(filter);
}
has(filter) {
return this.filters.includes(filter);
}
hasValidType() {
return (typeof this.value === 'string');
}
hasValidType() {
return (typeof this.value === 'string');
}
removeFiltersFromValue() {
if (this.hasValidType() === false) {
return this.value;
}
removeFiltersFromValue() {
if (this.hasValidType() === false) {
return this.value;
}
let filtersCombined = this.filters.join(this.delimiter);
filtersCombined += this.filters.length >= 1 ? this.delimiter : '';
return this.value.replace(filtersCombined, '');
}
let filtersCombined = this.filters.join(this.delimiter);
filtersCombined += this.filters.length >= 1 ? this.delimiter : '';
return this.value.replace(filtersCombined, '');
}
}
module.exports = Filters;

View File

@@ -1,5 +1,6 @@
const configuration = require('src/config/configuration').getInstance();
const SqliteDatabase = require('src/database/sqliteDatabase');
const database = new SqliteDatabase(configuration.get('database', 'host'));
/**
@@ -9,7 +10,7 @@ const database = new SqliteDatabase(configuration.get('database', 'host'));
* If the tables already exists, it simply proceeds.
*/
Promise.resolve()
.then(() => database.connect())
.then(() => database.setUp());
.then(() => database.connect())
.then(() => database.setUp());
module.exports = database;

View File

@@ -23,7 +23,7 @@ CREATE TABLE IF NOT EXISTS search_history (
CREATE TABLE IF NOT EXISTS requests(
id TEXT,
name TEXT,
title TEXT,
year NUMBER,
poster_path TEXT DEFAULT NULL,
background_path TEXT DEFAULT NULL,
@@ -54,4 +54,4 @@ CREATE TABLE IF NOT EXISTS shows(
show_names TEXT,
date_added DATE,
date_modified DATE DEFUALT CURRENT_DATE NOT NULL
);
);

View File

@@ -16,8 +16,8 @@ class SqliteDatabase {
*/
connect() {
return Promise.resolve()
.then(() => sqlite.open(this.host))
.then(() => sqlite.exec('pragma foreign_keys = on;'));
.then(() => sqlite.open(this.host))
.then(() => sqlite.exec('pragma foreign_keys = on;'));
}
/**
@@ -73,10 +73,10 @@ class SqliteDatabase {
* Tears down the database by running tearDown.sql file in schemas/.
* @returns {Promise}
*/
tearDown() {
const tearDownSchema = this.readSqlFile('tearDown.sql');
return this.execute(tearDownSchema);
}
tearDown() {
const tearDownSchema = this.readSqlFile('tearDown.sql');
return this.execute(tearDownSchema);
}
/**
* Returns the file contents of a SQL file in schemas/.

View File

@@ -1,10 +1,9 @@
const assert = require('assert');
class GitRepository {
dumpHook(body) {
console.log(body);
}
static dumpHook(body) {
/* eslint-disable no-console */
console.log(body);
}
}
module.exports = GitRepository;
module.exports = GitRepository;

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,15 +1,15 @@
class MediaInfo {
constructor() {
this.duration = undefined;
this.height = undefined;
this.width = undefined;
this.bitrate = undefined;
this.resolution = undefined;
this.framerate = undefined;
this.protocol = undefined;
this.container = undefined;
this.audioCodec = undefined;
}
constructor() {
this.duration = undefined;
this.height = undefined;
this.width = undefined;
this.bitrate = undefined;
this.resolution = undefined;
this.framerate = undefined;
this.protocol = undefined;
this.container = undefined;
this.audioCodec = undefined;
}
}
module.exports = MediaInfo;
module.exports = MediaInfo;

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 = undefined;
this.background = undefined;
this.genre = undefined;
this.date_added = undefined;
this.mediaInfo = undefined;
this.matchedInPlex = false;
}
}
module.exports = Movie;

View File

@@ -1,13 +1,12 @@
class Player {
constructor(device, address) {
this.device = device;
this.ip = address;
this.platform = undefined;
this.product = undefined;
this.title = undefined;
this.state = undefined;
}
constructor(device, address) {
this.device = device;
this.ip = address;
this.platform = undefined;
this.product = undefined;
this.title = undefined;
this.state = undefined;
}
}
module.exports = Player;
module.exports = Player;

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,8 +1,8 @@
class User {
constructor(id, title) {
this.id = id;
this.title = title;
}
constructor(id, title) {
this.id = id;
this.title = title;
}
}
module.exports = User;
module.exports = User;

View File

@@ -1,54 +1,53 @@
const assert = require('assert');
var PythonShell = require('python-shell');
var async = require('async');
const PythonShell = require('python-shell');
async function find(searchterm, callback) {
const options = {
pythonPath: '/usr/bin/python3',
// pythonPath: '/Library/Frameworks/Python.framework/Versions/3.6/bin/python3',
args: [searchterm, '-s', 'piratebay', '--print'],
};
var options = {
pythonPath: '/usr/bin/python3',
// pythonPath: '/Library/Frameworks/Python.framework/Versions/3.6/bin/python3',
args: [searchterm, '-s', 'piratebay', '--print']
}
PythonShell.run('../app/torrent_search/torrentSearch/search.py', options, callback);
// PythonShell does not support return
};
PythonShell.run('../app/torrent_search/torrentSearch/search.py', options, callback);
// PythonShell does not support return
}
async function callPythonAddMagnet(magnet, callback) {
var options = {
pythonPath: '/usr/bin/python',
// pythonPath: '/Library/Frameworks/Python.framework/Versions/3.6/bin/python3',
args: [magnet]
}
const options = {
pythonPath: '/usr/bin/python',
// pythonPath: '/Library/Frameworks/Python.framework/Versions/3.6/bin/python3',
args: [magnet],
};
PythonShell.run('../app/magnet.py', options, callback);
PythonShell.run('../app/magnet.py', options, callback);
}
async function SearchPiratebay(query) {
return await new Promise((resolve, reject) => {
return find(query, function(err, results) {
if (err) {
console.log('THERE WAS A FUCKING ERROR!')
reject(Error('There was a error when searching for torrents'))
}
if (results) {
console.log('result', results);
resolve(JSON.parse(results, null, '\t'));
}
})
})
return await new Promise((resolve, reject) => find(query, (err, results) => {
if (err) {
/* eslint-disable no-console */
console.log('THERE WAS A FUCKING ERROR!');
reject(Error('There was a error when searching for torrents'));
}
if (results) {
/* eslint-disable no-console */
console.log('result', results);
resolve(JSON.parse(results, null, '\t'));
}
}));
}
async function AddMagnet(magnet) {
return await new Promise((resolve) => {
return callPythonAddMagnet(magnet, function(err, results) {
if (err) {
console.log(err)
}
resolve({ success: true })
})
})
return await new Promise(resolve => callPythonAddMagnet(magnet, (err, results) => {
if (err) {
/* eslint-disable no-console */
console.log(err);
}
/* eslint-disable no-console */
console.log(results);
resolve({ success: true });
}));
}
module.exports = { SearchPiratebay, AddMagnet }
module.exports = { SearchPiratebay, AddMagnet };

View File

@@ -1,39 +1,24 @@
const Movie = require('src/media_classes/movie');
const Show = require('src/media_classes/show');
const Plex = require('src/media_classes/plex');
function convertPlexToSeasoned(plexObject) {
const mediaType = plexObject.type;
// There are many diff types of content, we only want to look at movies and tv shows
if (mediaType === 'movie') {
const movie = new Movie(plexObject.title, plexObject.year, mediaType);
movie.summary = plexObject.summary;
movie.rating = plexObject.rating;
movie.poster = plexObject.thumb;
movie.background = plexObject.art;
movie.genre = plexObject.genre;
movie.added = new Date(plexObject.addedAt * 1000);
movie.mediaInfo = plexObject.Media;
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;
}
function translateAdded(date_string) {
return new Date(date_string * 1000);
}
module.exports = convertPlexToSeasoned;
function convertPlexToSeasoned(plex) {
const title = plex.title;
const year = plex.year;
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;
const seasoned = new Plex(title, year, type, summary, poster_path, background_path, added, seasons, episodes);
// seasoned.print();
return seasoned;
}
module.exports = convertPlexToSeasoned;

View File

@@ -5,15 +5,15 @@ const convertStreamToUser = require('src/plex/stream/convertStreamToUser');
const ConvertStreamToPlayback = require('src/plex/stream/convertStreamToPlayback');
function convertPlexToStream(plexStream) {
const stream = convertPlexToSeasoned(plexStream)
const plexStreamMedia = plexStream.Media[0]
stream.mediaInfo = convertStreamToMediaInfo(plexStreamMedia);
stream.player = convertStreamToPlayer(plexStream.Player);
const stream = convertPlexToSeasoned(plexStream);
const plexStreamMedia = plexStream.Media[0];
stream.mediaInfo = convertStreamToMediaInfo(plexStreamMedia);
stream.player = convertStreamToPlayer(plexStream.Player);
stream.user = convertStreamToUser(plexStream.User);
stream.playback = new ConvertStreamToPlayback(plexStreamMedia.Part[0]);
stream.user = convertStreamToUser(plexStream.User);
stream.playback = new ConvertStreamToPlayback(plexStreamMedia.Part[0]);
return stream;
return stream;
}
module.exports = convertPlexToStream;
module.exports = convertPlexToStream;

View File

@@ -1,22 +1,22 @@
const MediaInfo = require('src/media_classes/mediaInfo');
function convertStreamToMediaInfo(plexStream) {
const mediaInfo = new MediaInfo();
mediaInfo.duration = plexStream.duration;
mediaInfo.height = plexStream.height;
mediaInfo.width = plexStream.width;
const mediaInfo = new MediaInfo();
if (plexStream.bitrate) {
mediaInfo.bitrate = plexStream.bitrate;
}
mediaInfo.resolution = plexStream.videoResolution;
mediaInfo.framerate = plexStream.videoFrameRate;
mediaInfo.protocol = plexStream.protocol;
mediaInfo.container = plexStream.container;
mediaInfo.audioCodec = plexStream.audioCodec;
mediaInfo.duration = plexStream.duration;
mediaInfo.height = plexStream.height;
mediaInfo.width = plexStream.width;
return mediaInfo;
if (plexStream.bitrate) {
mediaInfo.bitrate = plexStream.bitrate;
}
mediaInfo.resolution = plexStream.videoResolution;
mediaInfo.framerate = plexStream.videoFrameRate;
mediaInfo.protocol = plexStream.protocol;
mediaInfo.container = plexStream.container;
mediaInfo.audioCodec = plexStream.audioCodec;
return mediaInfo;
}
module.exports = convertStreamToMediaInfo;
module.exports = convertStreamToMediaInfo;

View File

@@ -1,14 +1,7 @@
/*
* @Author: KevinMidboe
* @Date: 2017-05-03 23:26:46
* @Last Modified by: KevinMidboe
* @Last Modified time: 2017-05-03 23:27:59
*/
const configuration = require('src/config/configuration').getInstance();
function hookDumpController(req, res) {
console.log(req);
console.log(req);
}
module.exports = hookDumpController;
module.exports = hookDumpController;

View File

@@ -1,26 +1,25 @@
class mailTemplate {
constructor(mediaItem) {
this.mediaItem = mediaItem;
this.posterURL = 'https://image.tmdb.org/t/p/w600';
}
constructor(mediaItem) {
this.mediaItem = mediaItem;
this.posterURL = 'https://image.tmdb.org/t/p/w600';
}
toText() {
return this.mediaItem.title + ' (' + this.mediaItem.year + ')'; // plain text body
}
toText() {
return `${this.mediaItem.title} (${this.mediaItem.year})`; // plain text body
}
toHTML() {
const info = {
name: this.mediaItem.title,
year: '(' + this.mediaItem.year + ')',
poster: this.posterURL + this.mediaItem.poster
}
toHTML() {
const info = {
name: this.mediaItem.title,
year: `(${this.mediaItem.year})`,
poster: this.posterURL + this.mediaItem.poster,
};
return `
<h1>${info.name} ${info.year}</h1>
<img src="${info.poster}">
`
}
return `
<h1>${info.name} ${info.year}</h1>
<img src="${info.poster}">
`;
}
}
module.exports = mailTemplate;
module.exports = mailTemplate;

View File

@@ -1,56 +1,80 @@
const assert = require('assert');
const convertPlexToSeasoned = require('src/plex/convertPlexToSeasoned');
const convertPlexToStream = require('src/plex/convertPlexToStream');
var rp = require('request-promise');
const rp = require('request-promise');
class PlexRepository {
inPlex(tmdbResult) {
return Promise.resolve()
.then(() => this.search(tmdbResult.title))
.then(plexResult => this.compareTmdbToPlex(tmdbResult, plexResult));
}
searchMedia(query) {
var options = {
uri: 'http://10.0.0.42:32400/search?query=' + query,
headers: {
'Accept': 'application/json'
},
json: true
}
search(query) {
const options = {
uri: `http://10.0.0.44:32400/search?query=${query}`,
headers: {
Accept: 'application/json',
},
json: true,
};
return rp(options)
.then((result) => {
var seasonedMediaObjects = result.MediaContainer.Metadata.reduce(function(match, media_item) {
if (media_item.type === 'movie' || media_item.type === 'show') {
match.push(convertPlexToSeasoned(media_item));
}
return match;
}, []);
return seasonedMediaObjects;
})
.catch((err) => {
throw new Error(err);
})
}
return rp(options)
.then(result => this.mapResults(result))
.then(([mappedResults, resultCount]) => ({ results: mappedResults, total_results: resultCount }));
}
nowPlaying() {
var options = {
uri: 'http://10.0.0.42:32400/status/sessions',
headers: {
'Accept': 'application/json'
},
json: true
}
static compareTmdbToPlex(tmdb, plexResult) {
return Promise.resolve()
.then(() => {
plexResult.results.map((plexItem) => {
if (tmdb.title === plexItem.title && tmdb.year === plexItem.year) { tmdb.matchedInPlex = true; }
return tmdb;
});
return tmdb;
});
}
return rp(options)
.then((result) => {
if (result.MediaContainer.size > 0) {
var playing = result.MediaContainer.Video.map(convertPlexToStream);
return {'size': Object.keys(playing).length, 'video': playing };
} else {
return { 'size': 0, 'video': [] };
}
})
.catch((err) => {
throw new Error('Error handling plex playing. Error: ' + err);
})
}
static mapResults(response) {
return Promise.resolve()
.then(() => {
if (!response.MediaContainer.hasOwnProperty('Metadata')) return [[], 0];
const mappedResults = response.MediaContainer.Metadata.filter((element) => {
return (element.type === 'movie' || element.type === 'show');
}).map((element) => convertPlexToSeasoned(element));
return [mappedResults, mappedResults.length];
})
.catch((error) => { throw new Error(error); });
}
nowPlaying() {
const options = {
uri: 'http://10.0.0.44:32400/status/sessions',
headers: {
Accept: 'application/json',
},
json: true,
};
return rp(options)
.then((result) => {
if (result.MediaContainer.size > 0) {
const playing = result.MediaContainer.Video.map(convertPlexToStream);
return { size: Object.keys(playing).length, video: playing };
}
return { size: 0, video: [] };
})
.catch((err) => {
throw new Error(`Error handling plex playing. Error: ${err}`);
});
}
// multipleInPlex(tmdbResults) {
// const results = tmdbResults.results.map(async (tmdb) => {
// return this.inPlex(tmdb)
// })
// return Promise.all(results)
// }
}
module.exports = PlexRepository;

View File

@@ -1,174 +1,117 @@
const assert = require('assert');
const PlexRepository = require('src/plex/plexRepository');
const plexRepository = new PlexRepository();
const configuration = require('src/config/configuration').getInstance();
const Cache = require('src/tmdb/cache');
const configuration = require('src/config/configuration').getInstance();
const TMDB = require('src/tmdb/tmdb');
const cache = new Cache();
const tmdb = new TMDB(cache, configuration.get('tmdb', 'apiKey'));
var Promise = require('bluebird');
var rp = require('request-promise');
const establishedDatabase = require('src/database/database');
const MailTemplate = require('src/plex/mailTemplate')
const plexRepository = new PlexRepository();
const cache = new Cache();
const tmdb = new TMDB(cache, configuration.get('tmdb', 'apiKey'));
var pythonShell = require('python-shell');
const MailTemplate = require('src/plex/mailTemplate');
const nodemailer = require('nodemailer');
class RequestRepository {
constructor(cache, database) {
this.database = database || establishedDatabase;
this.queries = {
insertRequest: "INSERT INTO requests VALUES (?, ?, ?, ?, ?, ?, ?, CURRENT_DATE, 'requested', ?, ?)",
fetchRequstedItems: 'SELECT * FROM requests',
updateRequestedById: 'UPDATE requests SET status = ? WHERE id is ? AND type is ?',
checkIfIdRequested: 'SELECT * FROM requests WHERE id IS ? AND type IS ?',
};
}
constructor(cache, database) {
this.database = database || establishedDatabase;
this.queries = {
'insertRequest': "INSERT INTO requests VALUES (?, ?, ?, ?, ?, ?, ?, CURRENT_DATE, 'requested', ?, ?)",
'fetchRequstedItems': "SELECT * FROM requests",
'updateRequestedById': "UPDATE requests SET status = ? WHERE id is ? AND type is ?",
}
}
search(query, type, page) {
return Promise.resolve()
.then(() => tmdb.search(query, type, page))
// .then((tmdbResult) => plexRepository.multipleInPlex(tmdbResult))
.then(result => result)
.catch(error => `error in the house${error}`);
}
searchRequest(text, page, type) {
// STRIP METADATA THAT IS NOT ALLOWED
lookup(identifier, type = 'movie') {
return Promise.resolve()
.then(() => tmdb.lookup(identifier, type))
.then(tmdbMovie => this.checkID(tmdbMovie))
.then(tmdbMovie => plexRepository.inPlex(tmdbMovie))
.catch((error) => {
throw new Error(error);
});
}
// Do a search in the tmdb api and return the results of the object
let getTmdbResults = function() {
return tmdb.search(text, page, type)
.then((tmdbSearch) => {
return tmdbSearch.results;
})
}
checkID(tmdbMovie) {
return Promise.resolve()
.then(() => this.database.get(this.queries.checkIfIdRequested, [tmdbMovie.id, tmdbMovie.type]))
.then((result, error) => {
if (error) { throw new Error(error); }
let already_requested = false;
if (result) { already_requested = true; }
// Take inputs and verify them with a list. Now we are for every item in tmdb result
// runnning through the entire plex loop. Many loops, but safe.
let checkIfMatchesPlexObjects = function(title, year, plexarray) {
// Iterate all elements in plexarray
for (let plexItem of plexarray) {
// If matches with our title and year return true
if (plexItem.title === title && plexItem.year === year)
return true;
}
// If no matches were found, return false
return false;
}
tmdbMovie.requested = already_requested;
return tmdbMovie;
});
}
return Promise.resolve()
.then(() => plexRepository.searchMedia(text))
// Get the list of plexItems matching the query passed.
.then((plexItem) => {
let tmdbSearchResult = getTmdbResults();
// When we get the result from tmdbSearchResult we pass it along and iterate over each
// element, and updates the matchedInPlex status of a item.
return tmdbSearchResult.then((tmdbResult) => {
for (var i = 0; i < tmdbResult.length; i++) {
let foundMatchInPlex = checkIfMatchesPlexObjects(tmdbResult[i].title, tmdbResult[i].year, plexItem);
tmdbResult[i].matchedInPlex = foundMatchInPlex;
}
return { 'results': tmdbResult, 'page': 1 };
})
// TODO log error
.catch((error) => {
console.log(error);
throw new Error('Search query did not give any results.');
})
})
.catch(() => {
let tmdbSearchResult = getTmdbResults();
// Catch if empty, then 404
return tmdbSearchResult.then((tmdbResult) => {
return {'results': tmdbResult, 'page': 1 };
})
})
}
lookup(identifier, type = 'movie') {
if (type === 'movie') { type = 'movieInfo'}
else if (type === 'tv') { type = 'tvInfo'}
return Promise.resolve()
.then(() => tmdb.lookup(identifier, type))
.then((tmdbMovie) => {
return Promise.resolve(plexRepository.searchMedia(tmdbMovie.title))
.then((plexMovies) => {
for (var i = 0; i < plexMovies.length; i++) {
if (tmdbMovie.title === plexMovies[i].title && tmdbMovie.year === plexMovies[i].year) {
tmdbMovie.matchedInPlex = true;
return tmdbMovie;
}
}
})
.catch((error) => {
return error;
});
return tmdbMovie;
});
}
/**
* Send request for given media id.
* @param {identifier, type} the id of the media object and type of media must be defined
* @returns {Promise} If nothing has gone wrong.
*/
sendRequest(identifier, type, ip, user_agent, user) {
tmdb.lookup(identifier, type).then(movie => {
if (user === 'false')
user = 'NULL';
console.log(user)
// Add request to database
this.database.run(this.queries.insertRequest, [movie.id, movie.title, movie.year, movie.poster, movie.background, user, ip, user_agent, movie.type])
/**
* Send request for given media id.
* @param {identifier, type} the id of the media object and type of media must be defined
* @returns {Promise} If nothing has gone wrong.
*/
sendRequest(identifier, type, ip, user_agent, user) {
tmdb.lookup(identifier, type).then((movie) => {
if (user === 'false') { user = 'NULL'; }
// Add request to database
this.database.run(this.queries.insertRequest, [movie.id, movie.title, movie.year, movie.poster_path, movie.background_path, user, ip, user_agent, movie.type]);
// create reusable transporter object using the default SMTP transport
let transporter = nodemailer.createTransport({
service: 'gmail',
auth: {
user: configuration.get('mail', 'user_pi'),
pass: configuration.get('mail', 'password_pi')
}
// host: configuration.get('mail', 'host'),
// port: 26,
// ignoreTLS: true,
// tls :{rejectUnauthorized: false},
// secure: false, // secure:true for port 465, secure:false for port 587
});
// create reusable transporter object using the default SMTP transport
const transporter = nodemailer.createTransport({
service: 'gmail',
auth: {
user: configuration.get('mail', 'user_pi'),
pass: configuration.get('mail', 'password_pi'),
},
// host: configuration.get('mail', 'host'),
// port: 26,
// ignoreTLS: true,
// tls :{rejectUnauthorized: false},
// secure: false, // secure:true for port 465, secure:false for port 587
});
const mailTemplate = new MailTemplate(movie)
const mailTemplate = new MailTemplate(movie);
// setup email data with unicode symbols
let mailOptions = {
// TODO get the mail adr from global location (easy to add)
from: 'MovieRequester <pi.midboe@gmail.com>', // sender address
to: 'kevin.midboe@gmail.com', // list of receivers
subject: 'Download request', // Subject line
text: mailTemplate.toText(),
html: mailTemplate.toHTML()
};
// setup email data with unicode symbols
const mailOptions = {
// TODO get the mail adr from global location (easy to add)
from: 'MovieRequester <pi.midboe@gmail.com>', // sender address
to: 'kevin.midboe@gmail.com', // list of receivers
subject: 'Download request', // Subject line
text: mailTemplate.toText(),
html: mailTemplate.toHTML(),
};
// send mail with defined transport object
transporter.sendMail(mailOptions, (error, info) => {
if (error) {
return console.log(error);
}
console.log('Message %s sent: %s', info.messageId, info.response);
});
// send mail with defined transport object
transporter.sendMail(mailOptions, (error, info) => {
if (error) {
return console.log(error);
}
console.log('Message %s sent: %s', info.messageId, info.response);
});
});
})
// TODO add better response when done.
return Promise.resolve();
}
// TODO add better response when done.
return Promise.resolve();
}
fetchRequested() {
return this.database.all(this.queries.fetchRequstedItems);
}
updateRequestedById(id, type, status) {
return this.database.run(this.queries.updateRequestedById, [status, id, type]);
}
fetchRequested() {
return this.database.all(this.queries.fetchRequstedItems);
}
updateRequestedById(id, type, status) {
return this.database.run(this.queries.updateRequestedById, [status, id, type]);
}
}
module.exports = RequestRepository;
module.exports = RequestRepository;

View File

@@ -1,15 +1,14 @@
class convertStreamToPlayback {
constructor(plexStream) {
this.bitrate = plexStream.bitrate;
this.width = plexStream.width;
this.height = plexStream.height;
this.decision = plexStream.decision;
this.audioProfile = plexStream.audioProfile;
this.videoProfile = plexStream.videoProfile;
this.duration = plexStream.duration;
this.container = plexStream.container;
}
constructor(plexStream) {
this.bitrate = plexStream.bitrate;
this.width = plexStream.width;
this.height = plexStream.height;
this.decision = plexStream.decision;
this.audioProfile = plexStream.audioProfile;
this.videoProfile = plexStream.videoProfile;
this.duration = plexStream.duration;
this.container = plexStream.container;
}
}
module.exports = convertStreamToPlayback;
module.exports = convertStreamToPlayback;

View File

@@ -1,13 +1,13 @@
const Player = require('src/media_classes/player');
function convertStreamToPlayer(plexStream) {
const player = new Player(plexStream.device, plexStream.address);
player.platform = plexStream.platform;
player.product = plexStream.product;
player.title = plexStream.title;
player.state = plexStream.state;
const player = new Player(plexStream.device, plexStream.address);
player.platform = plexStream.platform;
player.product = plexStream.product;
player.title = plexStream.title;
player.state = plexStream.state;
return player;
return player;
}
module.exports = convertStreamToPlayer;
module.exports = convertStreamToPlayer;

View File

@@ -1,7 +1,7 @@
const User = require('src/media_classes/user');
function convertStreamToUser(plexStream) {
return new User(plexStream.id, plexStream.title);
return new User(plexStream.id, plexStream.title);
}
module.exports = convertStreamToUser;
module.exports = convertStreamToUser;

View File

@@ -1,39 +1,38 @@
const establishedDatabase = require('src/database/database');
class SearchHistory {
constructor(database) {
this.database = database || establishedDatabase;
this.queries = {
'create': 'insert into search_history (search_query, user_name) values (?, ?)',
'read': 'select search_query from search_history where user_name = ? order by id desc',
};
}
constructor(database) {
this.database = database || establishedDatabase;
this.queries = {
'create': 'insert into search_history (search_query, user_name) values (?, ?)',
'read': 'select search_query from search_history where user_name = ? order by id desc',
};
}
/**
/**
* Retrive a search queries for a user from the database.
* @param {User} user existing user
* @returns {Promise}
*/
read(user) {
return this.database.all(this.queries.read, user)
.then(rows => rows.map(row => row.search_query));
}
read(user) {
return this.database.all(this.queries.read, user)
.then(rows => rows.map(row => row.search_query));
}
/**
/**
* Creates a new search entry in the database.
* @param {User} user a new user
* @param {String} searchQuery the query the user searched for
* @returns {Promise}
*/
create(user, searchQuery) {
return this.database.run(this.queries.create, [searchQuery, user]).catch((error) => {
if (error.message.includes('FOREIGN')) {
throw new Error('Could not create search history.');
}
});
}
create(user, searchQuery) {
return this.database.run(this.queries.create, [searchQuery, user])
.catch((error) => {
if (error.message.includes('FOREIGN')) {
throw new Error('Could not create search history.');
}
});
}
}
module.exports = SearchHistory;

View File

@@ -1,7 +1,7 @@
class Stray {
constructor(id) {
this.id = id;
}
constructor(id) {
this.id = id;
}
}
module.exports = Stray;
module.exports = Stray;

View File

@@ -1,67 +1,62 @@
const assert = require('assert');
const Stray = require('src/seasoned/stray');
const establishedDatabase = require('src/database/database');
var pythonShell = require('python-shell');
function foo(e) {
throw('Foooo');
}
const pythonShell = require('python-shell');
class StrayRepository {
constructor(database) {
this.database = database || establishedDatabase;
this.queries = {
read: 'SELECT * FROM stray_eps WHERE id = ?',
readAll: 'SELECT id, name, season, episode, verified FROM stray_eps',
readAllFiltered: 'SELECT id, name, season, episode, verified FROM stray_eps WHERE verified = ',
checkVerified: 'SELECT id FROM stray_eps WHERE verified = 0 AND id = ?',
verify: 'UPDATE stray_eps SET verified = 1 WHERE id = ?',
};
}
constructor(database) {
this.database = database || establishedDatabase;
this.queries = {
'read': 'SELECT * FROM stray_eps WHERE id = ?',
'readAll': 'SELECT id, name, season, episode, verified FROM stray_eps',
'readAllFiltered': 'SELECT id, name, season, episode, verified FROM stray_eps WHERE verified = ',
'checkVerified': 'SELECT id FROM stray_eps WHERE verified = 0 AND id = ?',
'verify': 'UPDATE stray_eps SET verified = 1 WHERE id = ?',
};
}
read(strayId) {
return this.database.get(this.queries.read, strayId).then((row) => {
assert.notEqual(row, undefined, `Could not find list with id ${strayId}.`);
return row;
});
}
read(strayId) {
return this.database.get(this.queries.read, strayId).then((row) => {
assert.notEqual(row, undefined, `Could not find list with id ${strayId}.`);
return row;
})
}
readAll(verified = null) {
let dbSearchQuery = this.queries.readAll;
if (verified != null) {
dbSearchQuery = this.queries.readAllFiltered + verified.toString();
}
return this.database.all(dbSearchQuery).then(rows =>
rows.map((row) => {
const stray = new Stray(row.id);
stray.name = row.name;
stray.season = row.season;
stray.episode = row.episode;
stray.verified = row.verified;
return stray;
}));
}
readAll(verified = null, page = 1) {
var dbSearchQuery = this.queries.readAll;
if (verified != null) {
dbSearchQuery = this.queries.readAllFiltered + verified.toString();
}
return this.database.all(dbSearchQuery).then(rows =>
rows.map((row) => {
const stray = new Stray(row.id);
stray.name = row.name;
stray.season = row.season;
stray.episode = row.episode;
stray.verified = row.verified;
return stray;
}))
}
verifyStray(strayId) {
return this.database.get(this.queries.checkVerified, strayId).then((row) => {
assert.notEqual(row, undefined, `Stray '${strayId}' already verified.`);
verifyStray(strayId) {
return this.database.get(this.queries.checkVerified, strayId).then((row) => {
assert.notEqual(row, undefined, `Stray '${strayId}' already verified.`);
const options = {
pythonPath: '/usr/bin/python3',
args: [strayId],
};
var options = {
pythonPath: '/usr/bin/python3',
args: [strayId]
}
pythonShell.run('../app/moveSeasoned.py', options, (err, results) => {
if (err) throw err;
// TODO Add error handling!! StrayRepository.ERROR
// results is an array consisting of messages collected during execution
console.log('results: %j', results);
});
pythonShell.run('../app/moveSeasoned.py', options, function (err, results) {
if (err) throw err;
// TODO Add error handling!! StrayRepository.ERROR
// results is an array consisting of messages collected during execution
console.log('results: %j', results);
});
return this.database.run(this.queries.verify, strayId);
})
}
return this.database.run(this.queries.verify, strayId);
});
}
}
module.exports = StrayRepository;

View File

@@ -2,43 +2,43 @@ const assert = require('assert');
const establishedDatabase = require('src/database/database');
class Cache {
constructor(database) {
this.database = database || establishedDatabase
this.queries = {
'read': 'SELECT value, time_to_live, created_at, DATETIME("now", "localtime") as now, ' +
'DATETIME(created_at, "+" || time_to_live || " seconds") as expires ' +
'FROM cache WHERE key = ? AND now < expires',
'create': 'INSERT OR REPLACE INTO cache (key, value, time_to_live) VALUES (?, ?, ?)',
};
}
constructor(database) {
this.database = database || establishedDatabase;
this.queries = {
read: 'SELECT value, time_to_live, created_at, DATETIME("now", "localtime") as now, ' +
'DATETIME(created_at, "+" || time_to_live || " seconds") as expires ' +
'FROM cache WHERE key = ? AND now < expires',
create: 'INSERT OR REPLACE INTO cache (key, value, time_to_live) VALUES (?, ?, ?)',
};
}
/**
* Retrieve an unexpired cache entry by key.
* @param {String} key of the cache entry
* @returns {Object}
*/
get(key) {
return Promise.resolve()
.then(() => this.database.get(this.queries.read, [key]))
.then((row) => {
assert(row, 'Could not find cache enrty with that key.');
return JSON.parse(row.value);
})
}
/**
* Retrieve an unexpired cache entry by key.
* @param {String} key of the cache entry
* @returns {Object}
*/
get(key) {
return Promise.resolve()
.then(() => this.database.get(this.queries.read, [key]))
.then((row) => {
assert(row, 'Could not find cache enrty with that key.');
return JSON.parse(row.value);
});
}
/**
* Insert cache entry with key and value.
* @param {String} key of the cache entry
* @param {String} value of the cache entry
* @param {Number} timeToLive the number of seconds before entry expires
* @returns {Object}
*/
set(key, value, timeToLive = 172800) {
const json = JSON.stringify(value);
return Promise.resolve()
.then(() => this.database.run(this.queries.create, [key, json, timeToLive]))
.then(() => value);
}
/**
* Insert cache entry with key and value.
* @param {String} key of the cache entry
* @param {String} value of the cache entry
* @param {Number} timeToLive the number of seconds before entry expires
* @returns {Object}
*/
set(key, value, timeToLive = 172800) {
const json = JSON.stringify(value);
return Promise.resolve()
.then(() => this.database.run(this.queries.create, [key, json, timeToLive]))
.then(() => value);
}
}
module.exports = Cache;

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) {
// 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';
const TMDB = require('src/media_classes/tmdb');
// There are many diff types of content, we only want to look at movies and tv shows
if (mediaType === 'movie') {
const year = new Date(tmdbObject.release_date).getFullYear();
function translateYear(tmdbReleaseDate) {
return new Date(tmdbReleaseDate).getFullYear();
}
if (tmdbObject.title !== undefined) {
var title = tmdbObject.title;
} else if (tmdbObject.name !== undefined) {
var title = tmdbObject.name;
}
function translateGenre(tmdbGenres) {
return tmdbGenres.map(genre => genre.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;
movie.summary = tmdbObject.overview;
movie.rating = tmdbObject.vote_average;
movie.poster = tmdbObject.poster_path;
movie.background = tmdbObject.backdrop_path;
movie.genre = tmdbObject.genre_ids;
const id = tmdb.id;
const summary = tmdb.overview;
const poster_path = tmdb.poster_path;
const background_path = tmdb.backdrop_path;
const popularity = tmdb.popularity;
const score = tmdb.vote_average;
// const genres = translateGenre(tmdb.genres);
const release_status = tmdb.status;
const tagline = tmdb.tagline;
movie.popularity = tmdbObject.popularity;
movie.vote_count = tmdbObject.vote_count;
const seasons = tmdb.number_of_seasons;
const episodes = tmdb.episodes;
return movie;
}
else if (mediaType === 'tv' || mediaType === 'show') {
const year = new Date(tmdbObject.first_air_date).getFullYear();
const seasoned = new TMDB(
title, year, type, id, summary, poster_path, background_path,
popularity, score, release_status, tagline, seasons, episodes,
);
const show = new Show(tmdbObject.name, year, 'show');
show.id = tmdbObject.id;
show.summary = tmdbObject.overview;
show.rating = tmdbObject.vote_average;
show.poster = tmdbObject.poster_path;
show.background = tmdbObject.backdrop_path;
show.genre = tmdbObject.genre_ids;
show.popularity = tmdbObject.popularity;
show.vote_count = tmdbObject.vote_count;
return show;
}
// seasoned.print()
return seasoned;
}
module.exports = convertTmdbToSeasoned;

View File

@@ -1,193 +1,134 @@
const moviedb = require('moviedb');
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 TYPE_LIST = ['upcoming', 'discover', 'popular', 'nowplaying', 'similar']
const TMDB_TYPE_LIST = {
'upcomingmovie': 'miscUpcomingMovies', 'discovermovie': 'discoverMovie',
'discovershow': 'discoverTv', 'popularmovie': 'miscPopularMovies',
'popularshow': 'miscPopularTvs', 'nowplayingmovie': 'miscNowPlayingMovies',
'nowplayingshow': 'tvOnTheAir', 'similarmovie': 'movieSimilar', 'similarshow': 'tvSimilar',
const TMDB_METHODS = {
upcoming: { movie: 'miscUpcomingMovies' },
discover: { movie: 'discoverMovie', show: 'discoverTv' },
popular: { movie: 'miscPopularMovies', show: 'miscPopularTvs' },
nowplaying: { movie: 'miscNowPlayingMovies', show: 'tvOnTheAir' },
similar: { movie: 'movieSimilar', show: 'tvSimilar' },
search: { movie: 'searchMovie', show: 'searchTv', multi: 'searchMulti' },
info: { movie: 'movieInfo', show: 'tvInfo' },
};
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',
}
}
/**
* 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': page };
const cacheKey = `${this.cacheTags.search}:${page}:${type}:${text}`;
return Promise.resolve()
.then(() => this.cache.get(cacheKey))
.catch(() => this.tmdb(methodTypes[type], query))
.catch(() => { throw new Error('Could not search for movies/shows at tmdb.'); })
.then((response) => this.cache.set(cacheKey, response))
.then((response) => {
try {
let filteredTmdbItems = response.results.filter(function(tmdbResultItem) {
return ((tmdbResultItem.vote_count >= 10 || tmdbResultItem.popularity > 2) && (tmdbResultItem.release_date !== undefined || tmdbResultItem.first_air_date !== undefined))
})
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',
};
}
let seasonedItems = filteredTmdbItems.map((tmdbItem) => {
if (type === 'movie')
return convertTmdbToSeasoned(tmdbItem, 'movie');
else if (type === 'show')
return convertTmdbToSeasoned(tmdbItem, 'show');
else
return convertTmdbToSeasoned(tmdbItem);
});
// TODO add page number if results are larger than 20
return { 'results': seasonedItems, 'number_of_items_on_page': seasonedItems.length,
'page': 1, 'total_pages': 1 };
/**
* 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.');
}
});
}
} catch (parseError) {
throw new Error('Could not parse result.');
}
});
}
/**
* 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,
}));
}
/**
* Fetches a given list from tmdb.
* @param {listName} List we want to fetch.
* @param {type} The to specify in the request for discover (default 'movie').
* @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(listName, type = 'movie', id, page = '1') {
const params = { id, page };
const cacheKey = `${this.cacheTags[listName]}:${type}:${id}:${page}`;
return Promise.resolve()
.then(() => this.cache.get(cacheKey))
.catch(() => this.tmdb(this.tmdbMethod(listName, type), params))
.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_pages: totalpages, total_results,
}));
}
tmdbMethod(apiMethod, type) {
const method = TMDB_METHODS[apiMethod][type];
if (method !== undefined) return method;
throw new Error('Could not find tmdb api method.');
}
/**
* 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, queryType = 'movie') {
var type;
if (queryType === 'movie') { type = 'movieInfo'}
else if (queryType === 'show') { type = 'tvInfo'}
else {
return Promise.resolve()
.then(() => {
throw new Error('Invalid type declaration.')
})
}
const query = { id: identifier };
const cacheKey = `${this.cacheTags.lookup}:${type}:${identifier}`;
return Promise.resolve()
.then(() => this.cache.get(cacheKey))
.catch(() => this.tmdb(type, query))
.catch(() => { throw new Error('Could not find a movie with that id.'); })
.then((response) => this.cache.set(cacheKey, response))
.then((response) => {
try {
var car = convertTmdbToSeasoned(response, queryType);
console.log(car);
return car;
} catch (parseError) {
throw new Error('Could not parse movie.');
}
});
}
/**
* Maps our response from tmdb api to a movie/show object.
* @param {response} JSON response from tmdb.
* @param {type} The type declared in listSearch.
* @returns {Promise} dict with tmdb results, mapped as movie/show objects.
*/
mapResults(response, type) {
return Promise.resolve()
.then(() => {
const mappedResults = response.results.map(result => convertTmdbToSeasoned(result, type));
return [mappedResults, response.page, response.total_pages, response.total_results];
})
.catch((error) => { throw new Error(error); });
}
/**
* Verifies that a list_name corresponds to a tmdb list and calls the tmdb
* api with list name and paramters.
* @param {list_name} The name of a list we want to search for.
* @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.')
})
}
tmdb(method, argument) {
return new Promise((resolve, reject) => {
const callback = (error, reponse) => {
if (error) {
return reject(error);
}
return resolve(reponse);
};
/**
* Maps our response from tmdb api to a movie/show object.
* @param {response} JSON response from tmdb.
* @param {type} The type declared in listSearch.
* @returns {Promise} dict with tmdb results, mapped as movie/show objects.
*/
mapResults(response, type) {
return Promise.resolve()
.then(() => {
const mappedResults = response.results.map((result) => {
return convertTmdbToSeasoned(result, type)
})
return [mappedResults, response.page, response.total_pages]
})
.catch((error) => { throw new Error(error)})
}
/**
* Fetches a given list from tmdb.
* @param {list_name} List we want to fetch.
* @param {media_type} The to specify in the request for discover (default 'movie').
* @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]) => {
return {'results': mappedResults, 'page': pagenumber, 'total_pages': totalpages}
})
}
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);
}
})
}
if (!argument) {
this.tmdbLibrary[method](callback);
} else {
this.tmdbLibrary[method](argument, callback);
}
});
}
}
module.exports = TMDB;

View File

@@ -2,37 +2,36 @@ const User = require('src/user/user');
const jwt = require('jsonwebtoken');
class Token {
constructor(user) {
this.user = user;
}
constructor(user) {
this.user = user;
}
/**
* Generate a new token.
* @param {String} secret a cipher of the token
* @returns {String}
*/
toString(secret) {
return jwt.sign({ username: this.user.username }, secret);
}
/**
* Generate a new token.
* @param {String} secret a cipher of the token
* @returns {String}
*/
toString(secret) {
return jwt.sign({ username: this.user.username }, secret);
}
/**
/**
* Decode a token.
* @param {Token} jwtToken an encrypted token
* @param {String} secret a cipher of the token
* @returns {Token}
*/
static fromString(jwtToken, secret) {
let username = null;
static fromString(jwtToken, secret) {
let username = null;
try {
username = jwt.verify(jwtToken, secret).username;
} catch (error) {
throw new Error('The token is invalid.');
}
const user = new User(username);
return new Token(user);
}
try {
username = jwt.verify(jwtToken, secret).username;
} catch (error) {
throw new Error('The token is invalid.');
}
const user = new User(username);
return new Token(user);
}
}
module.exports = Token;

View File

@@ -1,8 +1,8 @@
class User {
constructor(username, email) {
this.username = username;
this.email = email;
}
constructor(username, email) {
this.username = username;
this.email = email;
}
}
module.exports = User;
module.exports = User;

View File

@@ -2,58 +2,56 @@ const assert = require('assert');
const establishedDatabase = require('src/database/database');
class UserRepository {
constructor(database) {
this.database = database || establishedDatabase;
this.queries = {
read: 'select * from user where lower(user_name) = lower(?)',
create: 'insert into user (user_name, email) values(?, ?)',
change: 'update user set password = ? where user_name = ?',
retrieveHash: 'select * from user where user_name = ?',
};
}
constructor(database) {
this.database = database || establishedDatabase;
this.queries = {
read: 'select * from user where lower(user_name) = lower(?)',
create: 'insert into user (user_name, email) values(?, ?)',
change: 'update user set password = ? where user_name = ?',
retrieveHash: 'select * from user where user_name = ?',
};
}
/**
/**
* Create a user in a database.
* @param {User} user the user you want to create
* @returns {Promise}
*/
create(user) {
return Promise.resolve()
.then(() => this.database.get(this.queries.read, user.username))
.then(row => assert.equal(row, undefined))
.then(() => this.database.run(this.queries.create, [user.username, user.email]))
.catch((error) => {
if (error.message.endsWith('email')) {
throw new Error('That email is already taken');
} else if (error.name === 'AssertionError' || error.message.endsWith('user_name')) {
throw new Error('That username is already taken');
}
});
}
create(user) {
return Promise.resolve()
.then(() => this.database.get(this.queries.read, user.username))
.then(row => assert.equal(row, undefined))
.then(() => this.database.run(this.queries.create, [user.username, user.email]))
.catch((error) => {
if (error.message.endsWith('email')) {
throw new Error('That email is already taken');
} else if (error.name === 'AssertionError' || error.message.endsWith('user_name')) {
throw new Error('That username is already taken');
}
});
}
/**
/**
* Retrieve a password from a database.
* @param {User} user the user you want to retrieve the password
* @returns {Promise}
*/
retrieveHash(user) {
return this.database.get(this.queries.retrieveHash, user.username).then((row) => {
assert(row, 'The user does not exist.');
return row.password;
});
}
retrieveHash(user) {
return this.database.get(this.queries.retrieveHash, user.username).then((row) => {
assert(row, 'The user does not exist.');
return row.password;
});
}
/**
/**
* Change a user's password in a database.
* @param {User} user the user you want to create
* @param {String} password the new password you want to change
* @returns {Promise}
*/
changePassword(user, password) {
return this.database.run(this.queries.change, [password, user.username]);
}
changePassword(user, password) {
return this.database.run(this.queries.change, [password, user.username]);
}
}
module.exports = UserRepository;

View File

@@ -2,75 +2,74 @@ const bcrypt = require('bcrypt-nodejs');
const UserRepository = require('src/user/userRepository');
class UserSecurity {
constructor(database) {
this.userRepository = new UserRepository(database);
}
constructor(database) {
this.userRepository = new UserRepository(database);
}
/**
/**
* Create a new user in PlanFlix.
* @param {User} user the new user you want to create
* @param {String} clearPassword a password of the user
* @returns {Promise}
*/
createNewUser(user, clearPassword) {
if (user.username.trim() === '') {
throw new Error('The username is empty.');
} else if (user.email.trim() === '') {
throw new Error('The email is empty.');
} else if (clearPassword.trim() === '') {
throw new Error('The password is empty.');
} else {
return Promise.resolve()
.then(() => this.userRepository.create(user))
.then(() => UserSecurity.hashPassword(clearPassword))
.then(hash => this.userRepository.changePassword(user, hash));
}
}
createNewUser(user, clearPassword) {
if (user.username.trim() === '') {
throw new Error('The username is empty.');
} else if (user.email.trim() === '') {
throw new Error('The email is empty.');
} else if (clearPassword.trim() === '') {
throw new Error('The password is empty.');
} else {
return Promise.resolve()
.then(() => this.userRepository.create(user))
.then(() => UserSecurity.hashPassword(clearPassword))
.then(hash => this.userRepository.changePassword(user, hash));
}
}
/**
/**
* Login into PlanFlix.
* @param {User} user the user you want to login
* @param {String} clearPassword the user's password
* @returns {Promise}
*/
login(user, clearPassword) {
return Promise.resolve()
.then(() => this.userRepository.retrieveHash(user))
.then(hash => UserSecurity.compareHashes(hash, clearPassword))
.catch(() => { throw new Error('Wrong username or password.'); });
}
login(user, clearPassword) {
return Promise.resolve()
.then(() => this.userRepository.retrieveHash(user))
.then(hash => UserSecurity.compareHashes(hash, clearPassword))
.catch(() => { throw new Error('Wrong username or password.'); });
}
/**
/**
* Compare between a password and a hash password from database.
* @param {String} hash the hash password from database
* @param {String} clearPassword the user's password
* @returns {Promise}
*/
static compareHashes(hash, clearPassword) {
return new Promise((resolve, reject) => {
bcrypt.compare(clearPassword, hash, (error, matches) => {
if (matches === true) {
resolve();
} else {
reject();
}
static compareHashes(hash, clearPassword) {
return new Promise((resolve, reject) => {
bcrypt.compare(clearPassword, hash, (error, matches) => {
if (matches === true) {
resolve();
} else {
reject();
}
});
});
});
}
}
/**
/**
* Hashes a password.
* @param {String} clearPassword the user's password
* @returns {Promise}
*/
static hashPassword(clearPassword) {
return new Promise((resolve) => {
bcrypt.hash(clearPassword, null, null, (error, hash) => {
resolve(hash);
static hashPassword(clearPassword) {
return new Promise((resolve) => {
bcrypt.hash(clearPassword, null, null, (error, hash) => {
resolve(hash);
});
});
});
}
}
}
module.exports = UserSecurity;

View File

@@ -5,8 +5,9 @@ const tokenToUser = require('./middleware/tokenToUser');
const mustBeAuthenticated = require('./middleware/mustBeAuthenticated');
const configuration = require('src/config/configuration').getInstance();
// TODO: Have our raven router check if there is a value, if not don't enable raven.
// TODO: Have our raven router check if there is a value, if not don't enable raven.
Raven.config(configuration.get('raven', 'DSN')).install();
const app = express(); // define our app using express
app.use(Raven.requestHandler());
// this will let us get the data from a POST
@@ -18,7 +19,6 @@ app.use(bodyParser.json());
/* Decode the Authorization header if provided */
// router.use(tokenToUser);
const port = 31459; // set our port
const router = express.Router();
const allowedOrigins = ['https://kevinmidboe.com', 'http://localhost:8080'];
@@ -28,32 +28,32 @@ app.use(bodyParser.urlencoded({ extended: true }));
// This is probably a correct middleware/router setup
/* Decode the Authorization header if provided */
/* Translate the user token to a user name */
router.use(tokenToUser);
// TODO: Should have a separate middleware/router for handling headers.
router.use((req, res, next) => {
// TODO add logging of all incoming
console.log('Request: ', req.originalUrl);
const origin = req.headers.origin;
if (allowedOrigins.indexOf(origin) > -1) {
console.log('allowed');
res.setHeader('Access-Control-Allow-Origin', origin);
}
res.header('Access-Control-Allow-Headers', 'Content-Type, Authorization, loggedinuser');
res.header('Access-Control-Allow-Methods', 'POST, GET, PUT');
// TODO add logging of all incoming
console.log('Request: ', req.originalUrl);
const origin = req.headers.origin;
if (allowedOrigins.indexOf(origin) > -1) {
console.log('allowed');
res.setHeader('Access-Control-Allow-Origin', origin);
}
res.header('Access-Control-Allow-Headers', 'Content-Type, Authorization, loggedinuser');
res.header('Access-Control-Allow-Methods', 'POST, GET, PUT');
next();
next();
});
router.get('/', function mainHandler(req, res) {
throw new Error('Broke!');
throw new Error('Broke!');
});
app.use(Raven.errorHandler());
app.use(function onError(err, req, res, next) {
res.statusCode = 500;
res.end(res.sentry + '\n');
res.statusCode = 500;
res.end(res.sentry + '\n');
});
/**
@@ -61,7 +61,7 @@ app.use(function onError(err, req, res, next) {
*/
router.post('/v1/user', require('./controllers/user/register.js'));
router.post('/v1/user/login', require('./controllers/user/login.js'));
router.get('/v1/user/history', mustBeAuthenticated, require('./controllers/user/history.js'));
router.get('/v1/user/history', require('./controllers/user/history.js'));
/**
* Seasoned
@@ -83,7 +83,7 @@ router.get('/v1/plex/hook', require('./controllers/plex/hookDump.js'));
/**
* Requests
*/
router.get('/v1/plex/requests/all', mustBeAuthenticated, require('./controllers/plex/fetchRequested.js'));
router.get('/v1/plex/requests/all', require('./controllers/plex/fetchRequested.js'));
router.put('/v1/plex/request/:requestId', mustBeAuthenticated, require('./controllers/plex/updateRequested.js'));
/**

View File

@@ -3,13 +3,13 @@ const GitRepository = require('src/git/gitRepository');
const gitRepository = new GitRepository();
function dumpHookController(req, res) {
gitRepository.dumpHook(req.body)
.then(() => {
res.status(200);
})
.catch((error) => {
res.status(500);
});
gitRepository.dumpHook(req.body)
.then(() => {
res.status(200);
})
.catch((error) => {
res.status(500);
});
}
module.exports = dumpHookController;

View File

@@ -9,15 +9,15 @@
const PirateRepository = require('src/pirate/pirateRepository');
function updateRequested(req, res) {
const magnet = req.body.magnet;
const magnet = req.body.magnet;
PirateRepository.AddMagnet(magnet)
.then((result) => {
res.send(result);
})
.catch((error) => {
res.status(401).send({ success: false, error: error.message });
});
PirateRepository.AddMagnet(magnet)
.then((result) => {
res.send(result);
})
.catch((error) => {
res.status(401).send({ success: false, error: error.message });
});
}
module.exports = updateRequested;

View File

@@ -15,15 +15,15 @@ const PirateRepository = require('src/pirate/pirateRepository');
* @returns {Callback}
*/
function updateRequested(req, res) {
const { query, page, type } = req.query;
const { query, page, type } = req.query;
PirateRepository.SearchPiratebay(query, page, type)
.then((result) => {
res.send({ success: true, torrents: result });
})
.catch((error) => {
res.status(401).send({ success: false, error: error.message });
});
PirateRepository.SearchPiratebay(query, page, type)
.then((result) => {
res.send({ success: true, torrents: result });
})
.catch((error) => {
res.status(401).send({ success: false, error: error.message });
});
}
module.exports = updateRequested;

View File

@@ -9,15 +9,15 @@ const requestRepository = new RequestRepository();
* @returns {Callback}
*/
function historyController(req, res) {
const user = req.loggedInUser;
// const user = req.loggedInUser;
requestRepository.fetchRequested()
.then((requestedItems) => {
res.send({ success: true, requestedItems });
})
.catch((error) => {
res.status(401).send({ success: false, error: error.message });
});
requestRepository.fetchRequested()
.then((requestedItems) => {
res.send({ success: true, results: requestedItems, total_results: requestedItems.length });
})
.catch((error) => {
res.status(401).send({ success: false, error: error.message });
});
}
module.exports = historyController;

View File

@@ -2,13 +2,11 @@
* @Author: KevinMidboe
* @Date: 2017-05-03 23:26:46
* @Last Modified by: KevinMidboe
* @Last Modified time: 2017-05-03 23:27:59
* @Last Modified time: 2018-02-06 20:54:22
*/
const configuration = require('src/config/configuration').getInstance();
function hookDumpController(req, res) {
console.log(req);
console.log(req);
}
module.exports = hookDumpController;
module.exports = hookDumpController;

View File

@@ -1,14 +1,15 @@
const PlexRepository = require('src/plex/plexRepository');
const plexRepository = new PlexRepository();
function playingController(req, res) {
plexRepository.nowPlaying()
.then((movies) => {
res.send(movies);
})
.catch((error) => {
res.status(500).send({success: false, error: error.message });
})
plexRepository.nowPlaying()
.then((movies) => {
res.send(movies);
})
.catch((error) => {
res.status(500).send({ success: false, error: error.message });
});
}
module.exports = playingController;
module.exports = playingController;

View File

@@ -1,4 +1,5 @@
const RequestRepository = require('src/plex/requestRepository');
const requestRepository = new RequestRepository();
/**
@@ -8,14 +9,14 @@ const requestRepository = new RequestRepository();
* @returns {Callback}
*/
function readRequestController(req, res) {
const mediaId = req.params.mediaId;
const { type } = req.query;
requestRepository.lookup(mediaId, type)
.then((movies) => {
res.send(movies);
}).catch((error) => {
res.status(404).send({ success: false, error: error.message });
});
const mediaId = req.params.mediaId;
const { type } = req.query;
requestRepository.lookup(mediaId, type)
.then((movies) => {
res.send(movies);
}).catch((error) => {
res.status(404).send({ success: false, error: error.message });
});
}
module.exports = readRequestController;

View File

@@ -1,27 +1,28 @@
const PlexRepository = require('src/plex/plexRepository');
const plexRepository = new PlexRepository();
/**
* Controller: Search for media and check existence
* Controller: Search for media and check existence
* in plex by query and page
* @param {Request} req http request variable
* @param {Response} res
* @returns {Callback}
*/
function searchMediaController(req, res) {
const { query, page } = req.query;
const { query } = req.query;
plexRepository.searchMedia(query)
.then((media) => {
if (media !== undefined || media.length > 0) {
res.send(media);
} else {
res.status(404).send({ success: false, error: 'Search query did not return any results.'})
}
})
.catch((error) => {
res.status(500).send({success: false, error: error.message });
})
plexRepository.search(query)
.then((media) => {
if (media !== undefined || media.length > 0) {
res.send(media);
} else {
res.status(404).send({ success: false, error: 'Search query did not return any results.' });
}
})
.catch((error) => {
res.status(500).send({ success: false, error: error.message });
});
}
module.exports = searchMediaController;
module.exports = searchMediaController;

View File

@@ -1,34 +1,25 @@
const SearchHistory = require('src/searchHistory/searchHistory');
const Cache = require('src/tmdb/cache');
const RequestRepository = require('src/plex/requestRepository.js');
const cache = new Cache();
const requestRepository = new RequestRepository(cache);
const searchHistory = new SearchHistory();
function searchRequestController(req, res) {
const user = req.headers.loggedinuser;
const { query, page, type } = req.query;
console.log('searchReq: ' + query, page, type);
const user = req.headers.loggedinuser;
const { query, page, type } = req.query;
Promise.resolve()
.then(() => {
if (user !== 'false') {
searchHistory.create(user, query);
}
})
.then(() => requestRepository.searchRequest(query, page, type))
.then((searchResult) => {
if (searchResult.results.length > 0) {
res.send(searchResult);
}
else {
res.status(404).send({success: false, error: 'Search query did not return any results.'})
}
})
.catch((error) => {
res.status(500).send({success: false, error: error.message });
})
Promise.resolve()
.then(() => searchHistory.create(user, query))
.then(() => requestRepository.search(query, page, type))
.then((searchResult) => {
res.send(searchResult);
})
.catch((error) => {
res.status(500).send({ success: false, error: error.message });
});
}
module.exports = searchRequestController;
module.exports = searchRequestController;

View File

@@ -1,4 +1,5 @@
const RequestRepository = require('src/plex/requestRepository.js');
const requestRepository = new RequestRepository();
/**
@@ -9,20 +10,20 @@ const requestRepository = new RequestRepository();
*/
function submitRequestController(req, res) {
// This is the id that is the param of the url
const id = req.params.mediaId;
const type = req.query.type;
const ip = req.headers['x-forwarded-for'] || req.connection.remoteAddress;
const user_agent = req.headers['user-agent']
const user = req.headers.loggedinuser;
// This is the id that is the param of the url
const id = req.params.mediaId;
const type = req.query.type;
const ip = req.headers['x-forwarded-for'] || req.connection.remoteAddress;
const user_agent = req.headers['user-agent'];
const user = req.headers.loggedinuser;
requestRepository.sendRequest(id, type, ip, user_agent, user)
.then(() => {
res.send({ success: true, message: 'Media item sucessfully requested!' });
})
.catch((error) => {
res.status(500).send({ success: false, error: error.message });
});
requestRepository.sendRequest(id, type, ip, user_agent, user)
.then(() => {
res.send({ success: true, message: 'Media item sucessfully requested!' });
})
.catch((error) => {
res.status(500).send({ success: false, error: error.message });
});
}
module.exports = submitRequestController;
module.exports = submitRequestController;

View File

@@ -1,4 +1,5 @@
const RequestRepository = require('src/plex/requestRepository');
const requestRepository = new RequestRepository();
/**
@@ -8,17 +9,17 @@ const requestRepository = new RequestRepository();
* @returns {Callback}
*/
function updateRequested(req, res) {
const id = req.params.requestId;
const type = req.body.type;
const status = req.body.status;
const id = req.params.requestId;
const type = req.body.type;
const status = req.body.status;
requestRepository.updateRequestedById(id, type, status)
.then(() => {
res.send({ success: true });
})
.catch((error) => {
res.status(401).send({ success: false, error: error.message });
});
requestRepository.updateRequestedById(id, type, status)
.then(() => {
res.send({ success: true });
})
.catch((error) => {
res.status(401).send({ success: false, error: error.message });
});
}
module.exports = updateRequested;

View File

@@ -1,16 +1,17 @@
const StrayRepository = require('src/seasoned/strayRepository');
const strayRepository = new StrayRepository();
function readStraysController(req, res) {
const { verified, page } = req.query;
strayRepository.readAll(verified, page)
.then((strays) => {
res.send(strays);
})
.catch((error) => {
res.status(500).send({success: false, error: error.message });
});
const { verified, page } = req.query;
strayRepository.readAll(verified, page)
.then((strays) => {
res.send(strays);
})
.catch((error) => {
res.status(500).send({ success: false, error: error.message });
});
}
module.exports = readStraysController;
module.exports = readStraysController;

View File

@@ -1,17 +1,17 @@
const configuration = require('src/config/configuration').getInstance();
const StrayRepository = require('src/seasoned/strayRepository');
const strayRepository = new StrayRepository();
function strayByIdController(req, res) {
const id = req.params.strayId;
const id = req.params.strayId;
strayRepository.read(id)
.then((stray) => {
res.send(stray);
})
.catch((error) => {
res.status(500).send({ success: false, error: error.message });
});
strayRepository.read(id)
.then((stray) => {
res.send(stray);
})
.catch((error) => {
res.status(500).send({ success: false, error: error.message });
});
}
module.exports = strayByIdController;

View File

@@ -3,15 +3,15 @@ const StrayRepository = require('src/seasoned/strayRepository');
const strayRepository = new StrayRepository();
function verifyStrayController(req, res) {
const id = req.params.strayId;
const id = req.params.strayId;
strayRepository.verifyStray(id)
.then(() => {
res.send({ success: true, message: 'Episode verified' });
})
.catch((error) => {
res.status(500).send({ success: false, error: error.message });
});
strayRepository.verifyStray(id)
.then(() => {
res.send({ success: true, message: 'Episode verified' });
})
.catch((error) => {
res.status(500).send({ success: false, error: error.message });
});
}
module.exports = verifyStrayController;

View File

@@ -1,10 +1,10 @@
const configuration = require('src/config/configuration').getInstance();
const Cache = require('src/tmdb/cache');
const TMDB = require('src/tmdb/tmdb');
const cache = new Cache();
const tmdb = new TMDB(cache, configuration.get('tmdb', 'apiKey'));
/**
* Controller: Retrieve nowplaying movies / now airing shows
* @param {Request} req http request variable
@@ -12,15 +12,14 @@ const tmdb = new TMDB(cache, configuration.get('tmdb', 'apiKey'));
* @returns {Callback}
*/
function listSearchController(req, res) {
const listname = req.params.listname;
const { type, id, page } = req.query;
console.log(listname, type, id, page)
tmdb.listSearch(listname, type, id, page)
.then((results) => {
res.send(results);
}).catch((error) => {
res.status(404).send({ success: false, error: error.message });
});
const listname = req.params.listname;
const { type, id, page } = req.query;
tmdb.listSearch(listname, type, id, page)
.then((results) => {
res.send(results);
}).catch((error) => {
res.status(404).send({ success: false, error: error.message });
});
}
module.exports = listSearchController;

View File

@@ -1,6 +1,7 @@
const configuration = require('src/config/configuration').getInstance();
const Cache = require('src/tmdb/cache');
const TMDB = require('src/tmdb/tmdb');
const cache = new Cache();
const tmdb = new TMDB(cache, configuration.get('tmdb', 'apiKey'));
@@ -11,14 +12,14 @@ const tmdb = new TMDB(cache, configuration.get('tmdb', 'apiKey'));
* @returns {Callback}
*/
function readMediaController(req, res) {
const mediaId = req.params.mediaId;
const { type } = req.query;
tmdb.lookup(mediaId, type)
.then((movies) => {
res.send(movies);
}).catch((error) => {
res.status(404).send({ success: false, error: error.message });
});
const mediaId = req.params.mediaId;
const { type } = req.query;
tmdb.lookup(mediaId, type)
.then((movies) => {
res.send(movies);
}).catch((error) => {
res.status(404).send({ success: false, error: error.message });
});
}
module.exports = readMediaController;

View File

@@ -1,6 +1,7 @@
const configuration = require('src/config/configuration').getInstance();
const Cache = require('src/tmdb/cache');
const TMDB = require('src/tmdb/tmdb');
const cache = new Cache();
const tmdb = new TMDB(cache, configuration.get('tmdb', 'apiKey'));
@@ -11,20 +12,20 @@ const tmdb = new TMDB(cache, configuration.get('tmdb', 'apiKey'));
* @returns {Callback}
*/
function searchMediaController(req, res) {
const { query, page, type } = req.query;
const { query, page, type } = req.query;
Promise.resolve()
.then(() => tmdb.search(query, page, type))
.then((movies) => {
if (movies !== undefined || movies.length > 0) {
res.send(movies);
} else {
res.status(404).send({ success: false, error: 'Search query did not return any results.'})
}
})
.catch((error) => {
res.status(500).send({ success: false, error: error.message });
});
Promise.resolve()
.then(() => tmdb.search(query, page, type))
.then((movies) => {
if (movies !== undefined || movies.length > 0) {
res.send(movies);
} else {
res.status(404).send({ success: false, error: 'Search query did not return any results.' });
}
})
.catch((error) => {
res.status(500).send({ success: false, error: error.message });
});
}
module.exports = searchMediaController;

View File

@@ -1,4 +1,5 @@
const SearchHistory = require('src/searchHistory/searchHistory');
const searchHistory = new SearchHistory();
/**
@@ -8,15 +9,15 @@ const searchHistory = new SearchHistory();
* @returns {Callback}
*/
function historyController(req, res) {
const user = req.loggedInUser;
const user = req.loggedInUser;
searchHistory.read(user)
.then((searchQueries) => {
res.send({ success: true, searchQueries });
})
.catch((error) => {
res.status(401).send({ success: false, error: error.message });
});
searchHistory.read(user)
.then((searchQueries) => {
res.send({ success: true, searchQueries });
})
.catch((error) => {
res.status(401).send({ success: false, error: error.message });
});
}
module.exports = historyController;

View File

@@ -2,6 +2,7 @@ const User = require('src/user/user');
const Token = require('src/user/token');
const UserSecurity = require('src/user/userSecurity');
const configuration = require('src/config/configuration').getInstance();
const secret = configuration.get('authentication', 'secret');
const userSecurity = new UserSecurity();
@@ -12,17 +13,17 @@ const userSecurity = new UserSecurity();
* @returns {Callback}
*/
function loginController(req, res) {
const user = new User(req.body.username);
const password = req.body.password;
const user = new User(req.body.username);
const password = req.body.password;
userSecurity.login(user, password)
.then(() => {
const token = new Token(user).toString(secret);
res.send({ success: true, token });
})
.catch((error) => {
res.status(401).send({ success: false, error: error.message });
});
userSecurity.login(user, password)
.then(() => {
const token = new Token(user).toString(secret);
res.send({ success: true, token });
})
.catch((error) => {
res.status(401).send({ success: false, error: error.message });
});
}
module.exports = loginController;

View File

@@ -1,5 +1,6 @@
const User = require('src/user/user');
const UserSecurity = require('src/user/userSecurity');
const userSecurity = new UserSecurity();
/**
@@ -9,16 +10,16 @@ const userSecurity = new UserSecurity();
* @returns {Callback}
*/
function registerController(req, res) {
const user = new User(req.body.username, req.body.email);
const password = req.body.password;
const user = new User(req.body.username, req.body.email);
const password = req.body.password;
userSecurity.createNewUser(user, password)
.then(() => {
res.send({ success: true, message: 'Welcome to Seasoned!' });
})
.catch((error) => {
res.status(401).send({ success: false, error: error.message });
});
userSecurity.createNewUser(user, password)
.then(() => {
res.send({ success: true, message: 'Welcome to Seasoned!' });
})
.catch((error) => {
res.status(401).send({ success: false, error: error.message });
});
}
module.exports = registerController;

View File

@@ -1,11 +1,11 @@
const mustBeAuthenticated = (req, res, next) => {
if (req.loggedInUser === undefined) {
return res.status(401).send({
success: false,
error: 'You must be logged in.',
}); }
return next();
if (req.loggedInUser === undefined) {
return res.status(401).send({
success: false,
error: 'You must be logged in.',
});
}
return next();
};
module.exports = mustBeAuthenticated;

View File

@@ -1,5 +1,6 @@
/* eslint-disable no-param-reassign */
const configuration = require('src/config/configuration').getInstance();
const secret = configuration.get('authentication', 'secret');
const Token = require('src/user/token');
@@ -7,16 +8,16 @@ const Token = require('src/user/token');
// curl -i -H "Authorization:[token]" localhost:31459/api/v1/user/history
const tokenToUser = (req, res, next) => {
const rawToken = req.headers.authorization;
if (rawToken) {
try {
const token = Token.fromString(rawToken, secret);
req.loggedInUser = token.user;
} catch (error) {
req.loggedInUser = undefined;
}
}
next();
const rawToken = req.headers.authorization;
if (rawToken) {
try {
const token = Token.fromString(rawToken, secret);
req.loggedInUser = token.user;
} catch (error) {
req.loggedInUser = undefined;
}
}
next();
};
module.exports = tokenToUser;

View File

@@ -2,7 +2,10 @@ const config = require('src/config/configuration').getInstance();
const app = require('./app');
module.exports = app.listen(config.get('webserver', 'port'), () => {
console.log('seasonedAPI');
console.log(`Database is located at ${config.get('database', 'host')}`);
console.log(`Webserver is listening on ${config.get('webserver', 'port')}`);
})
/* eslint-disable no-console */
console.log('seasonedAPI');
/* eslint-disable no-console */
console.log(`Database is located at ${config.get('database', 'host')}`);
/* eslint-disable no-console */
console.log(`Webserver is listening on ${config.get('webserver', 'port')}`);
});

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', () =>
request(app)
.get('/api/v1/plex/requests/all')
.get('/api/v1/pirate/search?query=test')
.set('Authorization', 'maLfOrMed TOKEN')
.expect(401)
.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', () =>
request(app)
.post('/api/v1/plex/request/31749')
.post('/api/v1/plex/request/329865')
.set('Authorization', createToken('test_user', 'secret'))
.expect(200)
);