Automaticly fixable eslint issues, mostly 3 -> 2 space indentation

This commit is contained in:
2022-08-19 10:41:44 +02:00
parent 11fb803838
commit 2aace85418
62 changed files with 498 additions and 375 deletions

4
src/cache/redis.js vendored
View File

@@ -21,11 +21,11 @@ try {
console.error("Unable to connect to redis, setting up redis-mock.");
client = {
get: function () {
get() {
console.log("redis-dummy get", arguments[0]);
return Promise.resolve();
},
set: function () {
set() {
console.log("redis-dummy set", arguments[0]);
return Promise.resolve();
}

View File

@@ -1,15 +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

@@ -1,49 +1,53 @@
const Filters = require('./filters.js');
const EnvironmentVariables = require('./environmentVariables.js');
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);
}
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.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('env') && this.filters.has('base64')) {
if (this.environmentVariables.has(this.valueWithoutFilters)) {
const encodedEnvironmentVariable = this.environmentVariables.get(this.valueWithoutFilters);
return Field.base64Decode(encodedEnvironmentVariable);
}
return undefined;
}
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;
}
}
static base64Decode(string) {
return new Buffer(string, 'base64').toString('utf-8');
}
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.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;
}
return this.valueWithoutFilters;
}
static base64Decode(string) {
return new Buffer(string, "base64").toString("utf-8");
}
}
module.exports = Field;

View File

@@ -1,34 +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,9 +1,8 @@
class GitRepository {
static dumpHook(body) {
/* eslint-disable no-console */
console.log(body);
}
static dumpHook(body) {
/* eslint-disable no-console */
console.log(body);
}
}
module.exports = GitRepository;

View File

@@ -1,19 +1,18 @@
class Media {
constructor(title, year, type) {
this.title = title;
this.year = year;
this.type = type;
}
constructor(title, year, type) {
this.title = title;
this.year = year;
this.type = type;
}
toString() {
return `N: ${this.title} | Y: ${this.year} | T: ${this.type}`;
}
toString() {
return `N: ${this.title} | Y: ${this.year} | T: ${this.type}`;
}
print() {
/* eslint-disable no-console */
console.log(this.toString());
}
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;

View File

@@ -1,12 +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;

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;

View File

@@ -24,7 +24,7 @@ const sendSMS = message => {
}
},
function (err, r, body) {
console.log(err ? err : body);
console.log(err || body);
console.log("sms provider response:", body);
resolve();
}

View File

@@ -92,8 +92,8 @@ async function AddMagnet(magnet, name, tmdb_id) {
"INSERT INTO requested_torrent(magnet,torrent_name,tmdb_id) \
VALUES (?,?,?)";
let response = database.run(insert_query, [magnet, name, tmdb_id]);
console.log("Response from requsted_torrent insert: " + response);
const response = database.run(insert_query, [magnet, name, tmdb_id]);
console.log(`Response from requsted_torrent insert: ${response}`);
resolve({ success: true });
})

View File

@@ -5,10 +5,10 @@ function translateAdded(date_string) {
}
function convertPlexToSeasoned(plex) {
const title = plex.title;
const year = plex.year;
const type = plex.type;
const summary = plex.summary;
const { title } = plex;
const { year } = plex;
const { type } = plex;
const { summary } = plex;
const poster_path = plex.thumb;
const background_path = plex.art;
const added = translateAdded(plex.addedAt);

View File

@@ -1,25 +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 `
return `
<h1>${info.name} ${info.year}</h1>
<img src="${info.poster}">
`;
}
}
}
module.exports = mailTemplate;

View File

@@ -11,23 +11,22 @@ const sanitize = string => string.toLowerCase().replace(/[^\w]/gi, "");
function fixedEncodeURIComponent(str) {
return encodeURIComponent(str).replace(/[!'()*]/g, function (c) {
return "%" + c.charCodeAt(0).toString(16).toUpperCase();
return `%${c.charCodeAt(0).toString(16).toUpperCase()}`;
});
}
const matchingTitleAndYear = (plex, tmdb) => {
let matchingTitle, matchingYear;
let matchingTitle;
let matchingYear;
if (plex["title"] != null && tmdb["title"] != null) {
if (plex.title != null && tmdb.title != null) {
const plexTitle = sanitize(plex.title);
const tmdbTitle = sanitize(tmdb.title);
matchingTitle = plexTitle == tmdbTitle;
matchingTitle = matchingTitle
? matchingTitle
: plexTitle.startsWith(tmdbTitle);
matchingTitle = matchingTitle || plexTitle.startsWith(tmdbTitle);
} else matchingTitle = false;
if (plex["year"] != null && tmdb["year"] != null)
if (plex.year != null && tmdb.year != null)
matchingYear = plex.year == tmdb.year;
else matchingYear = false;
@@ -35,12 +34,12 @@ const matchingTitleAndYear = (plex, tmdb) => {
};
const successfullResponse = response => {
if (response && response["MediaContainer"]) return response;
if (response && response.MediaContainer) return response;
if (
response == null ||
response["status"] == null ||
response["statusText"] == null
response.status == null ||
response.statusText == null
) {
throw Error("Unable to decode response");
}
@@ -49,9 +48,8 @@ const successfullResponse = response => {
if (status === 200) {
return response.json();
} else {
throw { message: statusText, status: status };
}
throw { message: statusText, status };
};
class Plex {
@@ -77,13 +75,13 @@ class Plex {
return new Promise((resolve, reject) =>
this.cache
.get(cacheKey)
.then(machineInfo => resolve(machineInfo["machineIdentifier"]))
.then(machineInfo => resolve(machineInfo.machineIdentifier))
.catch(() => fetch(url, options))
.then(response => response.json())
.then(machineInfo =>
this.cache.set(cacheKey, machineInfo["MediaContainer"], 2628000)
this.cache.set(cacheKey, machineInfo.MediaContainer, 2628000)
)
.then(machineInfo => resolve(machineInfo["machineIdentifier"]))
.then(machineInfo => resolve(machineInfo.machineIdentifier))
.catch(error => {
if (error != undefined && error.type === "request-timeout") {
reject({
@@ -104,7 +102,7 @@ class Plex {
if (plex == null || tmdb == null) return false;
if (plex instanceof Array) {
let possibleMatches = plex.map(plexItem =>
const possibleMatches = plex.map(plexItem =>
matchingTitleAndYear(plexItem, tmdb)
);
match = possibleMatches.includes(true);
@@ -120,7 +118,7 @@ class Plex {
tmdb.title,
tmdb.year
);
return plexMatch ? true : false;
return !!plexMatch;
}
findPlexItemByTitleAndYear(title, year) {
@@ -149,7 +147,7 @@ class Plex {
if (
matchingObjectInPlex == false ||
matchingObjectInPlex == null ||
matchingObjectInPlex["key"] == null ||
matchingObjectInPlex.key == null ||
machineIdentifier == null
)
return false;
@@ -227,9 +225,11 @@ class Plex {
.map(category => {
if (category.type === "movie") {
return category.Metadata;
} else if (category.type === "show") {
}
if (category.type === "show") {
return category.Metadata.map(convertPlexToShow);
} else if (category.type === "episode") {
}
if (category.type === "episode") {
return category.Metadata.map(convertPlexToEpisode);
}
})

View File

@@ -1,6 +1,6 @@
const rp = require("request-promise");
const convertPlexToSeasoned = require("./convertPlexToSeasoned");
const convertPlexToStream = require("./convertPlexToStream");
const rp = require("request-promise");
class PlexRepository {
constructor(plexIP) {
@@ -24,7 +24,7 @@ class PlexRepository {
`http://${this.plexIP}:32400/search?query=${queryUri}`
);
const options = {
uri: uri,
uri,
headers: {
Accept: "application/json"
},

View File

@@ -56,7 +56,7 @@ class RequestRepository {
if (error) {
throw new Error(error);
}
tmdbMovie.requested = result ? true : false;
tmdbMovie.requested = !!result;
return tmdbMovie;
});
}
@@ -98,7 +98,7 @@ class RequestRepository {
type,
page
]);
else return this.database.all(this.queries.fetchRequestedItems, page);
return this.database.all(this.queries.fetchRequestedItems, page);
});
}

View File

@@ -1,14 +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;

View File

@@ -8,9 +8,9 @@ class Episode {
this.summary = null;
this.rating = null;
this.views = null;
this.aired = null;
this.type = 'episode';
this.aired = null;
this.type = "episode";
}
}
module.exports = Episode;
module.exports = Episode;

View File

@@ -5,8 +5,8 @@ class Movie {
this.summary = null;
this.rating = null;
this.tagline = null;
this.type = 'movie';
this.type = "movie";
}
}
module.exports = Movie;
module.exports = Movie;

View File

@@ -9,4 +9,4 @@ class Show {
}
}
module.exports = Show;
module.exports = Show;

View File

@@ -1,6 +1,7 @@
const assert = require("assert");
const configuration = require("../config/configuration").getInstance();
const TMDB = require("../tmdb/tmdb");
const tmdb = new TMDB(configuration.get("tmdb", "apiKey"));
const establishedDatabase = require("../database/database");
const utils = require("./utils");
@@ -33,7 +34,7 @@ class RequestRepository {
}
sortAndFilterToDbQuery(by, direction, filter, query) {
let dbQuery = undefined;
let dbQuery;
if (query !== undefined) {
const dbParams = [query, query];
@@ -87,7 +88,7 @@ class RequestRepository {
mapToTmdbByType(rows) {
return rows.map(row => {
if (row.type === "movie") return tmdb.movieInfo(row.id);
else if (row.type === "show") return tmdb.showInfo(row.id);
if (row.type === "show") return tmdb.showInfo(row.id);
});
}
@@ -189,9 +190,9 @@ class RequestRepository {
.then(async rows => {
const sqliteResponse = await this.database.get(
fetchTotalResults,
filter ? filter : undefined
filter || undefined
);
const totalRequests = sqliteResponse["totalRequests"];
const { totalRequests } = sqliteResponse;
const totalPages = Math.ceil(totalRequests / 26);
return [
@@ -211,7 +212,7 @@ class RequestRepository {
Promise.resolve({
results: result,
total_results: totalRequests,
page: page,
page,
total_pages: totalPages
})
)

View File

@@ -1,34 +1,48 @@
// TODO : test title and date are valid matches to columns in the database
const validSortParams = ['title', 'date']
const validSortDirs = ['asc', 'desc']
const validFilterParams = ['movie', 'show', 'seeding', 'downloading', 'paused', 'finished', 'downloaded']
const validSortParams = ["title", "date"];
const validSortDirs = ["asc", "desc"];
const validFilterParams = [
"movie",
"show",
"seeding",
"downloading",
"paused",
"finished",
"downloaded"
];
function validSort(by, direction) {
return new Promise((resolve, reject) => {
if (by === undefined) {
resolve()
resolve();
}
if (validSortParams.includes(by) && validSortDirs.includes(direction)) {
resolve()
resolve();
} else {
reject(new Error(`invalid sort parameter, must be of: ${validSortParams} with optional sort directions: ${validSortDirs} appended with ':'`))
reject(
new Error(
`invalid sort parameter, must be of: ${validSortParams} with optional sort directions: ${validSortDirs} appended with ':'`
)
);
}
});
}
function validFilter(filter_param) {
return new Promise((resolve, reject) => {
if (filter_param === undefined) {
resolve()
if (filter_param === undefined) {
resolve();
}
if (filter_param && validFilterParams.includes(filter_param)) {
resolve()
resolve();
} else {
reject(new Error(`filter parameteres must be of type: ${validFilterParams}`))
reject(
new Error(`filter parameteres must be of type: ${validFilterParams}`)
);
}
});
}
module.exports = { validSort, validFilter }
module.exports = { validSort, validFilter };

View File

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

View File

@@ -1,7 +1,7 @@
const assert = require("assert");
const pythonShell = require("python-shell");
const Stray = require("./stray");
const establishedDatabase = require("../database/database");
const pythonShell = require("python-shell");
class StrayRepository {
constructor(database) {

View File

@@ -5,11 +5,11 @@ const { Movie, Show, Person, Credits, ReleaseDates } = require("./types");
const tmdbErrorResponse = (error, typeString = undefined) => {
if (error.status === 404) {
let message = error.response.body.status_message;
const message = error.response.body.status_message;
throw {
status: 404,
message: message.slice(0, -1) + " in tmdb."
message: `${message.slice(0, -1)} in tmdb.`
};
} else if (error.status === 401) {
throw {
@@ -221,7 +221,7 @@ class TMDB {
}
movieList(listname, page = 1) {
const query = { page: page };
const query = { page };
const cacheKey = `tmdb/${this.cacheTags[listname]}:${page}`;
return this.getFromCacheOrFetchFromTmdb(cacheKey, listname, query)
@@ -230,7 +230,7 @@ class TMDB {
}
showList(listname, page = 1) {
const query = { page: page };
const query = { page };
const cacheKey = `tmdb/${this.cacheTags[listname]}:${page}`;
return this.getFromCacheOrFetchFromTmdb(cacheKey, listName, query)
@@ -245,21 +245,23 @@ class TMDB {
* @returns {Promise} dict with tmdb results, mapped as movie/show objects.
*/
mapResults(response, type = undefined) {
let results = response.results.map(result => {
const results = response.results.map(result => {
if (type === "movie" || result.media_type === "movie") {
const movie = Movie.convertFromTmdbResponse(result);
return movie.createJsonResponse();
} else if (type === "show" || result.media_type === "tv") {
}
if (type === "show" || result.media_type === "tv") {
const show = Show.convertFromTmdbResponse(result);
return show.createJsonResponse();
} else if (type === "person" || result.media_type === "person") {
}
if (type === "person" || result.media_type === "person") {
const person = Person.convertFromTmdbResponse(result);
return person.createJsonResponse();
}
});
return {
results: results,
results,
page: response.page,
total_results: response.total_results,
total_pages: response.total_pages

View File

@@ -1,7 +1,7 @@
const Movie = require('./types/movie.js')
const Show = require('./types/show.js')
const Person = require('./types/person.js')
const Credits = require('./types/credits.js')
const ReleaseDates = require('./types/releaseDates.js')
const Movie = require("./types/movie.js");
const Show = require("./types/show.js");
const Person = require("./types/person.js");
const Credits = require("./types/credits.js");
const ReleaseDates = require("./types/releaseDates.js");
module.exports = { Movie, Show, Person, Credits, ReleaseDates }
module.exports = { Movie, Show, Person, Credits, ReleaseDates };

View File

@@ -13,10 +13,11 @@ class Credits {
const { id, cast, crew } = response;
const allCast = cast.map(cast => {
if (cast["media_type"]) {
if (cast.media_type) {
if (cast.media_type === "movie") {
return CreditedMovie.convertFromTmdbResponse(cast);
} else if (cast.media_type === "tv") {
}
if (cast.media_type === "tv") {
return CreditedShow.convertFromTmdbResponse(cast);
}
}
@@ -31,10 +32,11 @@ class Credits {
});
const allCrew = crew.map(crew => {
if (cast["media_type"]) {
if (cast.media_type) {
if (cast.media_type === "movie") {
return CreditedMovie.convertFromTmdbResponse(cast);
} else if (cast.media_type === "tv") {
}
if (cast.media_type === "tv") {
return CreditedShow.convertFromTmdbResponse(cast);
}
}

View File

@@ -1,7 +1,20 @@
class Movie {
constructor(id, title, year=undefined, overview=undefined, poster=undefined, backdrop=undefined,
releaseDate=undefined, rating=undefined, genres=undefined, productionStatus=undefined,
tagline=undefined, runtime=undefined, imdb_id=undefined, popularity=undefined) {
constructor(
id,
title,
year = undefined,
overview = undefined,
poster = undefined,
backdrop = undefined,
releaseDate = undefined,
rating = undefined,
genres = undefined,
productionStatus = undefined,
tagline = undefined,
runtime = undefined,
imdb_id = undefined,
popularity = undefined
) {
this.id = id;
this.title = title;
this.year = year;
@@ -16,27 +29,66 @@ class Movie {
this.runtime = runtime;
this.imdb_id = imdb_id;
this.popularity = popularity;
this.type = 'movie';
this.type = "movie";
}
static convertFromTmdbResponse(response) {
const { id, title, release_date, overview, poster_path, backdrop_path, vote_average, genres, status,
tagline, runtime, imdb_id, popularity } = response;
const {
id,
title,
release_date,
overview,
poster_path,
backdrop_path,
vote_average,
genres,
status,
tagline,
runtime,
imdb_id,
popularity
} = response;
const releaseDate = new Date(release_date);
const year = releaseDate.getFullYear();
const genreNames = genres ? genres.map(g => g.name) : undefined
const genreNames = genres ? genres.map(g => g.name) : undefined;
return new Movie(id, title, year, overview, poster_path, backdrop_path, releaseDate, vote_average, genreNames, status,
tagline, runtime, imdb_id, popularity)
return new Movie(
id,
title,
year,
overview,
poster_path,
backdrop_path,
releaseDate,
vote_average,
genreNames,
status,
tagline,
runtime,
imdb_id,
popularity
);
}
static convertFromPlexResponse(response) {
// console.log('response', response)
const { title, year, rating, tagline, summary } = response;
const _ = undefined
const _ = undefined;
return new Movie(null, title, year, summary, _, _, _, rating, _, _, tagline)
return new Movie(
null,
title,
year,
summary,
_,
_,
_,
rating,
_,
_,
tagline
);
}
createJsonResponse() {
@@ -55,7 +107,7 @@ class Movie {
runtime: this.runtime,
imdb_id: this.imdb_id,
type: this.type
}
};
}
}

View File

@@ -1,4 +1,4 @@
class ReleaseDates {
class ReleaseDates {
constructor(id, releases) {
this.id = id;
this.releases = releases;
@@ -7,24 +7,35 @@ class ReleaseDates {
static convertFromTmdbResponse(response) {
const { id, results } = response;
const releases = results.map(countryRelease =>
new Release(
countryRelease.iso_3166_1,
countryRelease.release_dates.map(rd => new ReleaseDate(rd.certification, rd.iso_639_1, rd.release_date, rd.type, rd.note))
))
const releases = results.map(
countryRelease =>
new Release(
countryRelease.iso_3166_1,
countryRelease.release_dates.map(
rd =>
new ReleaseDate(
rd.certification,
rd.iso_639_1,
rd.release_date,
rd.type,
rd.note
)
)
)
);
return new ReleaseDates(id, releases)
return new ReleaseDates(id, releases);
}
createJsonResponse() {
return {
id: this.id,
results: this.releases.map(release => release.createJsonResponse())
}
};
}
}
class Release {
class Release {
constructor(country, releaseDates) {
this.country = country;
this.releaseDates = releaseDates;
@@ -33,8 +44,10 @@ class Release {
createJsonResponse() {
return {
country: this.country,
release_dates: this.releaseDates.map(releaseDate => releaseDate.createJsonResponse())
}
release_dates: this.releaseDates.map(releaseDate =>
releaseDate.createJsonResponse()
)
};
}
}
@@ -49,19 +62,18 @@ class ReleaseDate {
releaseTypeLookup(releaseTypeKey) {
const releaseTypeEnum = {
1: 'Premier',
2: 'Limited theatrical',
3: 'Theatrical',
4: 'Digital',
5: 'Physical',
6: 'TV'
}
1: "Premier",
2: "Limited theatrical",
3: "Theatrical",
4: "Digital",
5: "Physical",
6: "TV"
};
if (releaseTypeKey <= Object.keys(releaseTypeEnum).length) {
return releaseTypeEnum[releaseTypeKey]
} else {
// TODO log | Release type not defined, does this need updating?
return null
return releaseTypeEnum[releaseTypeKey];
}
// TODO log | Release type not defined, does this need updating?
return null;
}
createJsonResponse() {
@@ -71,7 +83,7 @@ class ReleaseDate {
release_date: this.releaseDate,
type: this.type,
note: this.note
}
};
}
}

View File

@@ -1,7 +1,18 @@
class Show {
constructor(id, title, year=undefined, overview=undefined, poster=undefined, backdrop=undefined,
seasons=undefined, episodes=undefined, rank=undefined, genres=undefined, status=undefined,
runtime=undefined) {
constructor(
id,
title,
year = undefined,
overview = undefined,
poster = undefined,
backdrop = undefined,
seasons = undefined,
episodes = undefined,
rank = undefined,
genres = undefined,
status = undefined,
runtime = undefined
) {
this.id = id;
this.title = title;
this.year = year;
@@ -14,18 +25,44 @@ class Show {
this.genres = genres;
this.productionStatus = status;
this.runtime = runtime;
this.type = 'show';
this.type = "show";
}
static convertFromTmdbResponse(response) {
const { id, name, first_air_date, overview, poster_path, backdrop_path, number_of_seasons, number_of_episodes,
rank, genres, status, episode_run_time, popularity } = response;
const {
id,
name,
first_air_date,
overview,
poster_path,
backdrop_path,
number_of_seasons,
number_of_episodes,
rank,
genres,
status,
episode_run_time,
popularity
} = response;
const year = new Date(first_air_date).getFullYear()
const genreNames = genres ? genres.map(g => g.name) : undefined
const year = new Date(first_air_date).getFullYear();
const genreNames = genres ? genres.map(g => g.name) : undefined;
return new Show(id, name, year, overview, poster_path, backdrop_path, number_of_seasons, number_of_episodes,
rank, genreNames, status, episode_run_time, popularity)
return new Show(
id,
name,
year,
overview,
poster_path,
backdrop_path,
number_of_seasons,
number_of_episodes,
rank,
genreNames,
status,
episode_run_time,
popularity
);
}
createJsonResponse() {
@@ -43,7 +80,7 @@ class Show {
production_status: this.productionStatus,
runtime: this.runtime,
type: this.type
}
};
}
}

View File

@@ -1,5 +1,5 @@
const User = require("./user");
const jwt = require("jsonwebtoken");
const User = require("./user");
class Token {
constructor(user, admin = false, settings = null) {
@@ -16,8 +16,8 @@ class Token {
toString(secret) {
const { user, admin, settings } = this;
let data = { username: user.username, settings };
if (admin) data["admin"] = admin;
const data = { username: user.username, settings };
if (admin) data.admin = admin;
return jwt.sign(data, secret, { expiresIn: "90d" });
}

View File

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

View File

@@ -59,7 +59,7 @@ router.get("/", (req, res) => {
app.use(Raven.errorHandler());
app.use((err, req, res, next) => {
res.statusCode = 500;
res.end(res.sentry + "\n");
res.end(`${res.sentry}\n`);
});
/**
@@ -68,6 +68,7 @@ app.use((err, req, res, next) => {
router.post("/v1/user", require("./controllers/user/register.js"));
router.post("/v1/user/login", require("./controllers/user/login.js"));
router.post("/v1/user/logout", require("./controllers/user/logout.js"));
router.get(
"/v1/user/settings",
mustBeAuthenticated,
@@ -88,6 +89,7 @@ router.get(
mustBeAuthenticated,
require("./controllers/user/requests.js")
);
router.post(
"/v1/user/link_plex",
mustBeAuthenticated,

View File

@@ -1,5 +1,6 @@
const configuration = require("../../../config/configuration").getInstance();
const TMDB = require("../../../tmdb/tmdb");
const tmdb = new TMDB(configuration.get("tmdb", "apiKey"));
// there should be a translate function from query params to
@@ -39,7 +40,8 @@ function fetchTmdbList(req, res, listname, type) {
.movieList(listname, page)
.then(listResponse => res.send(listResponse))
.catch(error => handleError(error, res));
} else if (type === "show") {
}
if (type === "show") {
return tmdb
.showList(listname, page)
.then(listResponse => res.send(listResponse))

View File

@@ -17,12 +17,9 @@ const movieCreditsController = (req, res) => {
} else {
// TODO log unhandled errors
console.log("caugth movie credits controller error", error);
res
.status(500)
.send({
message:
"An unexpected error occured while requesting movie credits"
});
res.status(500).send({
message: "An unexpected error occured while requesting movie credits"
});
}
});
};

View File

@@ -17,12 +17,9 @@ const movieReleaseDatesController = (req, res) => {
} else {
// TODO log unhandled errors : here our at tmdbReleaseError ?
console.log("caugth release dates controller error", error);
res
.status(500)
.send({
message:
"An unexpected error occured while requesting movie credits"
});
res.status(500).send({
message: "An unexpected error occured while requesting movie credits"
});
}
});
};

View File

@@ -1,5 +1,6 @@
const configuration = require("../../../config/configuration").getInstance();
const TMDB = require("../../../tmdb/tmdb");
const tmdb = new TMDB(configuration.get("tmdb", "apiKey"));
const personCreditsController = (req, res) => {

View File

@@ -1,5 +1,6 @@
const configuration = require("../../../config/configuration").getInstance();
const TMDB = require("../../../tmdb/tmdb");
const tmdb = new TMDB(configuration.get("tmdb", "apiKey"));
function handleError(error, res) {
@@ -31,7 +32,7 @@ async function personInfoController(req, res) {
? (credits = true)
: (credits = false);
let tmdbQueue = [tmdb.personInfo(personId)];
const tmdbQueue = [tmdb.personInfo(personId)];
if (credits) tmdbQueue.push(tmdb.personCredits(personId));
try {

View File

@@ -8,9 +8,9 @@
const PirateRepository = require("../../../pirate/pirateRepository");
function addMagnet(req, res) {
const magnet = req.body.magnet;
const name = req.body.name;
const tmdb_id = req.body.tmdb_id;
const { magnet } = req.body;
const { name } = req.body;
const { tmdb_id } = req.body;
PirateRepository.AddMagnet(magnet, name, tmdb_id)
.then(result => {

View File

@@ -1,12 +1,12 @@
/*
* @Author: KevinMidboe
* @Date: 2017-05-03 23:26:46
* @Last Modified by: KevinMidboe
* @Last Modified time: 2018-02-06 20:54:22
*/
* @Author: KevinMidboe
* @Date: 2017-05-03 23:26:46
* @Last Modified by: KevinMidboe
* @Last Modified time: 2018-02-06 20:54:22
*/
function hookDumpController(req, res) {
console.log(req);
console.log(req);
}
module.exports = hookDumpController;

View File

@@ -9,7 +9,7 @@ const requestRepository = new RequestRepository();
* @returns {Callback}
*/
function readRequestController(req, res) {
const mediaId = req.params.mediaId;
const { mediaId } = req.params;
const { type } = req.query;
requestRepository
.lookup(mediaId, type)

View File

@@ -1,5 +1,6 @@
const configuration = require("../../../config/configuration").getInstance();
const Plex = require("../../../plex/plex");
const plex = new Plex(configuration.get("plex", "ip"));
/**
@@ -16,12 +17,10 @@ function searchPlexController(req, res) {
if (movies.length > 0) {
res.send(movies);
} else {
res
.status(404)
.send({
success: false,
message: "Search query did not give any results from plex."
});
res.status(404).send({
success: false,
message: "Search query did not give any results from plex."
});
}
})
.catch(error => {

View File

@@ -19,12 +19,10 @@ function searchMediaController(req, res) {
if (media !== undefined || media.length > 0) {
res.send(media);
} else {
res
.status(404)
.send({
success: false,
message: "Search query did not return any results."
});
res.status(404).send({
success: false,
message: "Search query did not return any results."
});
}
})
.catch(error => {

View File

@@ -1,6 +1,7 @@
const configuration = require("../../../config/configuration").getInstance();
const RequestRepository = require("../../../request/request");
const TMDB = require("../../../tmdb/tmdb");
const tmdb = new TMDB(configuration.get("tmdb", "apiKey"));
const request = new RequestRepository();
@@ -26,7 +27,7 @@ function submitRequestController(req, res) {
const user_agent = req.headers["user-agent"];
const username = req.loggedInUser ? req.loggedInUser.username : null;
let mediaFunction = undefined;
let mediaFunction;
if (type === "movie") {
console.log("movie");

View File

@@ -10,8 +10,8 @@ const requestRepository = new RequestRepository();
*/
function updateRequested(req, res) {
const id = req.params.requestId;
const type = req.body.type;
const status = req.body.status;
const { type } = req.body;
const { status } = req.body;
requestRepository
.updateRequestedById(id, type, status)

View File

@@ -1,5 +1,6 @@
const configuration = require("../../../config/configuration").getInstance();
const Plex = require("../../../plex/plex");
const plex = new Plex(configuration.get("plex", "ip"));
/**

View File

@@ -1,4 +1,5 @@
const RequestRepository = require("../../../request/request");
const request = new RequestRepository();
/**
@@ -8,9 +9,9 @@ const request = new RequestRepository();
* @returns {Callback}
*/
function fetchAllRequests(req, res) {
let { page, filter, sort, query } = req.query;
const { page, filter, sort, query } = req.query;
let sort_by = sort;
let sort_direction = undefined;
let sort_direction;
if (sort !== undefined && sort.includes(":")) {
[sort_by, sort_direction] = sort.split(":");

View File

@@ -1,4 +1,5 @@
const RequestRepository = require("../../../request/request");
const request = new RequestRepository();
/**
@@ -8,7 +9,7 @@ const request = new RequestRepository();
* @returns {Callback}
*/
function fetchAllRequests(req, res) {
const id = req.params.id;
const { id } = req.params;
const { type } = req.query;
request

View File

@@ -1,6 +1,7 @@
const configuration = require("../../../config/configuration").getInstance();
const TMDB = require("../../../tmdb/tmdb");
const RequestRepository = require("../../../request/request");
const tmdb = new TMDB(configuration.get("tmdb", "apiKey"));
const request = new RequestRepository();
// const { sendSMS } = require("src/notifications/sms");
@@ -26,7 +27,7 @@ function requestTmdbIdController(req, res) {
const user_agent = req.headers["user-agent"];
const username = req.loggedInUser ? req.loggedInUser.username : null;
let mediaFunction = undefined;
let mediaFunction;
if (id === undefined || type === undefined) {
res.status(422).send({

View File

@@ -1,6 +1,7 @@
const configuration = require("../../../config/configuration").getInstance();
const TMDB = require("../../../tmdb/tmdb");
const SearchHistory = require("../../../searchHistory/searchHistory");
const tmdb = new TMDB(configuration.get("tmdb", "apiKey"));
const searchHistory = new SearchHistory();
@@ -13,7 +14,7 @@ const searchHistory = new SearchHistory();
function movieSearchController(req, res) {
const { query, page, adult } = req.query;
const username = req.loggedInUser ? req.loggedInUser.username : null;
const includeAdult = adult == "true" ? true : false;
const includeAdult = adult == "true";
if (username) {
searchHistory.create(username, query);

View File

@@ -1,11 +1,12 @@
const configuration = require("../../..//config/configuration").getInstance();
const configuration = require("../../../config/configuration").getInstance();
const TMDB = require("../../../tmdb/tmdb");
const SearchHistory = require("../../../searchHistory/searchHistory");
const tmdb = new TMDB(configuration.get("tmdb", "apiKey"));
const searchHistory = new SearchHistory();
function checkAndCreateJsonResponse(result) {
if (typeof result["createJsonResponse"] === "function") {
if (typeof result.createJsonResponse === "function") {
return result.createJsonResponse();
}
return result;

View File

@@ -1,6 +1,7 @@
const configuration = require("../../../config/configuration").getInstance();
const TMDB = require("../../../tmdb/tmdb");
const SearchHistory = require("../../../searchHistory/searchHistory");
const tmdb = new TMDB(configuration.get("tmdb", "apiKey"));
const searchHistory = new SearchHistory();
@@ -13,7 +14,7 @@ const searchHistory = new SearchHistory();
function personSearchController(req, res) {
const { query, page, adult } = req.query;
const username = req.loggedInUser ? req.loggedInUser.username : null;
const includeAdult = adult == "true" ? true : false;
const includeAdult = adult == "true";
if (username) {
searchHistory.create(username, query);

View File

@@ -1,6 +1,7 @@
const SearchHistory = require("../../../searchHistory/searchHistory");
const configuration = require("../../../config/configuration").getInstance();
const TMDB = require("../../../tmdb/tmdb");
const tmdb = new TMDB(configuration.get("tmdb", "apiKey"));
const searchHistory = new SearchHistory();
@@ -13,7 +14,7 @@ const searchHistory = new SearchHistory();
function showSearchController(req, res) {
const { query, page, adult } = req.query;
const username = req.loggedInUser ? req.loggedInUser.username : null;
const includeAdult = adult == "true" ? true : false;
const includeAdult = adult == "true";
if (username) {
searchHistory.create(username, query);

View File

@@ -1,5 +1,6 @@
const configuration = require("../../../config/configuration").getInstance();
const TMDB = require("../../../tmdb/tmdb");
const tmdb = new TMDB(configuration.get("tmdb", "apiKey"));
const showCreditsController = (req, res) => {
@@ -16,11 +17,9 @@ const showCreditsController = (req, res) => {
} else {
// TODO log unhandled errors
console.log("caugth show credits controller error", error);
res
.status(500)
.send({
message: "An unexpected error occured while requesting show credits"
});
res.status(500).send({
message: "An unexpected error occured while requesting show credits"
});
}
});
};

View File

@@ -1,6 +1,7 @@
const configuration = require("../../../config/configuration").getInstance();
const TMDB = require("../../../tmdb/tmdb");
const Plex = require("../../../plex/plex");
const tmdb = new TMDB(configuration.get("tmdb", "apiKey"));
const plex = new Plex(configuration.get("plex", "ip"));
@@ -35,7 +36,7 @@ async function showInfoController(req, res) {
? (check_existance = true)
: (check_existance = false);
let tmdbQueue = [tmdb.showInfo(showId)];
const tmdbQueue = [tmdb.showInfo(showId)];
if (credits) tmdbQueue.push(tmdb.showCredits(showId));
try {

View File

@@ -1,4 +1,5 @@
const UserRepository = require("../../../user/userRepository");
const userRepository = new UserRepository();
const fetch = require("node-fetch");
const FormData = require("form-data");

View File

@@ -27,7 +27,7 @@ const cookieOptions = {
*/
async function loginController(req, res) {
const user = new User(req.body.username);
const password = req.body.password;
const { password } = req.body;
try {
const [loggedIn, isAdmin, settings] = await Promise.all([
@@ -43,11 +43,7 @@ async function loginController(req, res) {
});
}
const token = new Token(
user,
isAdmin === 1 ? true : false,
settings
).toString(secret);
const token = new Token(user, isAdmin === 1, settings).toString(secret);
return res.cookie("authorization", token, cookieOptions).status(200).send({
success: true,

View File

@@ -24,7 +24,7 @@ const cookieOptions = {
*/
function registerController(req, res) {
const user = new User(req.body.username, req.body.email);
const password = req.body.password;
const { password } = req.body;
userSecurity
.createNewUser(user, password)

View File

@@ -1,4 +1,5 @@
const UserRepository = require("../../../user/userRepository");
const userRepository = new UserRepository();
/**
* Controller: Retrieves settings of a logged in user

View File

@@ -1,5 +1,6 @@
const configuration = require("../../../config/configuration").getInstance();
const Tautulli = require("../../../tautulli/tautulli");
const apiKey = configuration.get("tautulli", "apiKey");
const ip = configuration.get("tautulli", "ip");
const port = configuration.get("tautulli", "port");
@@ -10,12 +11,11 @@ function handleError(error, res) {
if (status && message) {
return res.status(status).send({ success: false, message });
} else {
console.log("caught view history controller error", error);
return res.status(500).send({
message: "An unexpected error occured while fetching view history"
});
}
console.log("caught view history controller error", error);
return res.status(500).send({
message: "An unexpected error occured while fetching view history"
});
}
function watchTimeStatsController(req, res) {

View File

@@ -1,29 +1,28 @@
const establishedDatabase = require("../../database/database");
const mustBeAdmin = (req, res, next) => {
let database = establishedDatabase;
const database = establishedDatabase;
if (req.loggedInUser === undefined) {
return res.status(401).send({
success: false,
message: "You must be logged in."
});
} else {
database
.get(
`SELECT admin FROM user WHERE user_name IS ?`,
req.loggedInUser.username
)
.then(isAdmin => {
console.log(isAdmin, req.loggedInUser);
if (isAdmin.admin == 0) {
return res.status(401).send({
success: false,
message: "You must be logged in as a admin."
});
}
});
}
database
.get(
`SELECT admin FROM user WHERE user_name IS ?`,
req.loggedInUser.username
)
.then(isAdmin => {
console.log(isAdmin, req.loggedInUser);
if (isAdmin.admin == 0) {
return res.status(401).send({
success: false,
message: "You must be logged in as a admin."
});
}
});
return next();
};

View File

@@ -1,35 +1,33 @@
const establishedDatabase = require("../../database/database");
const mustHaveAccountLinkedToPlex = (req, res, next) => {
let database = establishedDatabase;
const loggedInUser = req.loggedInUser;
const database = establishedDatabase;
const { loggedInUser } = req;
if (loggedInUser === undefined) {
return res.status(401).send({
success: false,
message: "You must have your account linked to a plex account."
});
} else {
database
.get(
`SELECT plex_userid FROM settings WHERE user_name IS ?`,
loggedInUser.username
)
.then(row => {
const plex_userid = row.plex_userid;
if (plex_userid === null || plex_userid === undefined) {
return res.status(403).send({
success: false,
message:
"No plex account user id found for your user. Please authenticate your plex account at /user/authenticate."
});
} else {
req.loggedInUser.plex_userid = plex_userid;
return next();
}
});
}
database
.get(
`SELECT plex_userid FROM settings WHERE user_name IS ?`,
loggedInUser.username
)
.then(row => {
const { plex_userid } = row;
if (plex_userid === null || plex_userid === undefined) {
return res.status(403).send({
success: false,
message:
"No plex account user id found for your user. Please authenticate your plex account at /user/authenticate."
});
}
req.loggedInUser.plex_userid = plex_userid;
return next();
});
};
module.exports = mustHaveAccountLinkedToPlex;