workaround for #334

pull/335/head
Drewster727 8 years ago
parent 292e078c13
commit 8e004cea2e

@ -1,100 +1,100 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace PlexRequests.Api.Models.Movie
{
public class CouchPotatoAdd
{
public Movie movie { get; set; }
public bool success { get; set; }
}
public class Rating
{
public List<string> imdb { get; set; }
}
public class Images
{
public List<object> disc_art { get; set; }
public List<string> poster { get; set; }
public List<string> backdrop { get; set; }
public List<object> extra_thumbs { get; set; }
public List<string> poster_original { get; set; }
public List<string> actors { get; set; }
public List<string> backdrop_original { get; set; }
public List<object> clear_art { get; set; }
public List<object> logo { get; set; }
public List<object> banner { get; set; }
public List<object> landscape { get; set; }
public List<object> extra_fanart { get; set; }
}
public class Info
{
public Rating rating { get; set; }
public List<string> genres { get; set; }
public int tmdb_id { get; set; }
public string plot { get; set; }
public string tagline { get; set; }
public Release_Date release_date { get; set; }
public int year { get; set; }
public string original_title { get; set; }
public List<string> actor_roles { get; set; }
public bool via_imdb { get; set; }
public Images images { get; set; }
public List<string> directors { get; set; }
public List<string> titles { get; set; }
public string imdb { get; set; }
public string mpaa { get; set; }
public bool via_tmdb { get; set; }
public List<string> actors { get; set; }
public List<string> writers { get; set; }
public int runtime { get; set; }
public string type { get; set; }
public string released { get; set; }
}
public class Release_Date
{
public int dvd { get; set; }
public int expires { get; set; }
public int theater { get; set; }
public bool bluray { get; set; }
}
public class Files
{
public List<string> image_poster { get; set; }
}
public class Identifiers
{
public string imdb { get; set; }
}
public class Movie
{
public string status { get; set; }
public Info info { get; set; }
public string _t { get; set; }
public List<object> releases { get; set; }
public string title { get; set; }
public string _rev { get; set; }
public string profile_id { get; set; }
public string _id { get; set; }
public List<object> tags { get; set; }
public int last_edit { get; set; }
public object category_id { get; set; }
public string type { get; set; }
public Files files { get; set; }
public Identifiers identifiers { get; set; }
}
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace PlexRequests.Api.Models.Movie
{
public class CouchPotatoAdd
{
public Movie movie { get; set; }
public bool success { get; set; }
}
public class Rating
{
public List<string> imdb { get; set; }
}
public class Images
{
public List<object> disc_art { get; set; }
public List<string> poster { get; set; }
public List<string> backdrop { get; set; }
public List<object> extra_thumbs { get; set; }
public List<string> poster_original { get; set; }
public List<string> actors { get; set; }
public List<string> backdrop_original { get; set; }
public List<object> clear_art { get; set; }
public List<object> logo { get; set; }
public List<object> banner { get; set; }
public List<object> landscape { get; set; }
public List<object> extra_fanart { get; set; }
}
public class Info
{
public Rating rating { get; set; }
public List<string> genres { get; set; }
public int tmdb_id { get; set; }
public string plot { get; set; }
public string tagline { get; set; }
public Release_Date release_date { get; set; }
public int year { get; set; }
public string original_title { get; set; }
public List<string> actor_roles { get; set; }
public bool via_imdb { get; set; }
public Images images { get; set; }
public List<string> directors { get; set; }
public List<string> titles { get; set; }
public string imdb { get; set; }
public string mpaa { get; set; }
public bool via_tmdb { get; set; }
public List<string> actors { get; set; }
public List<string> writers { get; set; }
public int runtime { get; set; }
public string type { get; set; }
public string released { get; set; }
}
public class Release_Date
{
public int dvd { get; set; }
public int expires { get; set; }
public int theater { get; set; }
public bool bluray { get; set; }
}
public class Files
{
public List<string> image_poster { get; set; }
}
public class Identifiers
{
public string imdb { get; set; }
}
public class Movie
{
public string status { get; set; }
public Info info { get; set; }
public string _t { get; set; }
public List<object> releases { get; set; }
public string title { get; set; }
public string _rev { get; set; }
public string profile_id { get; set; }
public string _id { get; set; }
public List<object> tags { get; set; }
public int last_edit { get; set; }
public object category_id { get; set; }
public string type { get; set; }
public Files files { get; set; }
public Identifiers identifiers { get; set; }
}
}

@ -1,164 +1,168 @@
#region Copyright
// /************************************************************************
// Copyright (c) 2016 Jamie Rees
// File: CouchPotatoApi.cs
// Created By: Jamie Rees
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
// ************************************************************************/
#endregion
using System;
using Newtonsoft.Json.Linq;
using NLog;
using PlexRequests.Api.Interfaces;
using PlexRequests.Api.Models.Movie;
using PlexRequests.Helpers.Exceptions;
using RestSharp;
namespace PlexRequests.Api
{
public class CouchPotatoApi : ICouchPotatoApi
{
public CouchPotatoApi()
{
Api = new ApiRequest();
}
private ApiRequest Api { get; set; }
private static Logger Log = LogManager.GetCurrentClassLogger();
public bool AddMovie(string imdbid, string apiKey, string title, Uri baseUrl, string profileId = default(string))
{
RestRequest request;
request = string.IsNullOrEmpty(profileId)
? new RestRequest {Resource = "/api/{apikey}/movie.add?title={title}&identifier={imdbid}"}
: new RestRequest { Resource = "/api/{apikey}/movie.add?title={title}&identifier={imdbid}&profile_id={profileId}" };
if (!string.IsNullOrEmpty(profileId))
{
request.AddUrlSegment("profileId", profileId);
}
request.AddUrlSegment("apikey", apiKey);
request.AddUrlSegment("imdbid", imdbid);
request.AddUrlSegment("title", title);
var obj = RetryHandler.Execute(() => Api.ExecuteJson<JObject> (request, baseUrl),new[] {
TimeSpan.FromSeconds (2),
TimeSpan.FromSeconds(5),
TimeSpan.FromSeconds(10)},
(exception, timespan) => Log.Error (exception, "Exception when calling AddMovie for CP, Retrying {0}", timespan));
Log.Trace("CP movie Add result count {0}", obj.Count);
if (obj.Count > 0)
{
try
{
Log.Trace("CP movie obj[\"success\"] = {0}", obj["success"]);
var result = (bool)obj["success"];
Log.Trace("CP movie Add result {0}", result);
return result;
}
catch (Exception e)
{
Log.Fatal(e);
return false;
}
}
return false;
}
/// <summary>
/// Gets the status.
/// </summary>
/// <param name="url">The URL.</param>
/// <param name="apiKey">The API key.</param>
/// <returns></returns>
public CouchPotatoStatus GetStatus(Uri url, string apiKey)
{
Log.Trace("Getting CP Status, ApiKey = {0}", apiKey);
var request = new RestRequest
{
Resource = "api/{apikey}/app.available/",
Method = Method.GET
};
request.AddUrlSegment("apikey", apiKey);
var obj = RetryHandler.Execute<CouchPotatoStatus>(() => Api.Execute<CouchPotatoStatus> (request, url),new TimeSpan[] {
TimeSpan.FromSeconds (2),
TimeSpan.FromSeconds(5),
TimeSpan.FromSeconds(10)},
(exception, timespan) => Log.Error (exception, "Exception when calling GetStatus for CP, Retrying {0}", timespan));
return obj;
}
public CouchPotatoProfiles GetProfiles(Uri url, string apiKey)
{
Log.Trace("Getting CP Profiles, ApiKey = {0}", apiKey);
var request = new RestRequest
{
Resource = "api/{apikey}/profile.list/",
Method = Method.GET
};
request.AddUrlSegment("apikey", apiKey);
var obj = RetryHandler.Execute<CouchPotatoProfiles>(() => Api.Execute<CouchPotatoProfiles> (request, url),null,
(exception, timespan) => Log.Error (exception, "Exception when calling GetProfiles for CP, Retrying {0}", timespan));
return obj;
}
public CouchPotatoMovies GetMovies(Uri baseUrl, string apiKey, string[] status)
{
var request = new RestRequest
{
Resource = "/api/{apikey}/movie.list?status={status}"
};
request.AddUrlSegment("apikey", apiKey);
request.AddUrlSegment("status", string.Join(",", status));
try
{
var obj = RetryHandler.Execute(() => Api.Execute<CouchPotatoMovies> (request, baseUrl),
new[] {
TimeSpan.FromSeconds (5),
TimeSpan.FromSeconds(10),
TimeSpan.FromSeconds(30)
},
(exception, timespan) => Log.Error (exception, "Exception when calling GetMovies for CP, Retrying {0}", timespan));
return obj;
}
catch (Exception e) // Request error is already logged in the ApiRequest class
{
Log.Error("Error when attempting to GetMovies.");
Log.Error (e);
return new CouchPotatoMovies();
}
}
}
#region Copyright
// /************************************************************************
// Copyright (c) 2016 Jamie Rees
// File: CouchPotatoApi.cs
// Created By: Jamie Rees
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
// ************************************************************************/
#endregion
using System;
using Newtonsoft.Json.Linq;
using NLog;
using PlexRequests.Api.Interfaces;
using PlexRequests.Api.Models.Movie;
using PlexRequests.Helpers.Exceptions;
using RestSharp;
namespace PlexRequests.Api
{
public class CouchPotatoApi : ICouchPotatoApi
{
public CouchPotatoApi()
{
Api = new ApiRequest();
}
private ApiRequest Api { get; set; }
private static Logger Log = LogManager.GetCurrentClassLogger();
public bool AddMovie(string imdbid, string apiKey, string title, Uri baseUrl, string profileId = default(string))
{
RestRequest request;
request = string.IsNullOrEmpty(profileId)
? new RestRequest {Resource = "/api/{apikey}/movie.add?title={title}&identifier={imdbid}"}
: new RestRequest { Resource = "/api/{apikey}/movie.add?title={title}&identifier={imdbid}&profile_id={profileId}" };
if (!string.IsNullOrEmpty(profileId))
{
request.AddUrlSegment("profileId", profileId);
}
request.AddUrlSegment("apikey", apiKey);
request.AddUrlSegment("imdbid", imdbid);
request.AddUrlSegment("title", title);
var obj = RetryHandler.Execute(() => Api.ExecuteJson<JObject> (request, baseUrl),new[] {
TimeSpan.FromSeconds (2),
TimeSpan.FromSeconds(5),
TimeSpan.FromSeconds(10)},
(exception, timespan) => Log.Error (exception, "Exception when calling AddMovie for CP, Retrying {0}", timespan));
Log.Trace("CP movie Add result count {0}", obj.Count);
if (obj.Count > 0)
{
try
{
Log.Trace("CP movie obj[\"success\"] = {0}", obj["success"]);
var result = (bool)obj["success"];
Log.Trace("CP movie Add result {0}", result);
return result;
}
catch (Exception e)
{
Log.Fatal(e);
return false;
}
}
return false;
}
/// <summary>
/// Gets the status.
/// </summary>
/// <param name="url">The URL.</param>
/// <param name="apiKey">The API key.</param>
/// <returns></returns>
public CouchPotatoStatus GetStatus(Uri url, string apiKey)
{
Log.Trace("Getting CP Status, ApiKey = {0}", apiKey);
var request = new RestRequest
{
Resource = "api/{apikey}/app.available/",
Method = Method.GET
};
request.AddUrlSegment("apikey", apiKey);
var obj = RetryHandler.Execute<CouchPotatoStatus>(() => Api.Execute<CouchPotatoStatus> (request, url),new TimeSpan[] {
TimeSpan.FromSeconds (2),
TimeSpan.FromSeconds(5),
TimeSpan.FromSeconds(10)},
(exception, timespan) => Log.Error (exception, "Exception when calling GetStatus for CP, Retrying {0}", timespan));
return obj;
}
public CouchPotatoProfiles GetProfiles(Uri url, string apiKey)
{
Log.Trace("Getting CP Profiles, ApiKey = {0}", apiKey);
var request = new RestRequest
{
Resource = "api/{apikey}/profile.list/",
Method = Method.GET
};
request.AddUrlSegment("apikey", apiKey);
var obj = RetryHandler.Execute<CouchPotatoProfiles>(() => Api.Execute<CouchPotatoProfiles> (request, url),null,
(exception, timespan) => Log.Error (exception, "Exception when calling GetProfiles for CP, Retrying {0}", timespan));
return obj;
}
public CouchPotatoMovies GetMovies(Uri baseUrl, string apiKey, string[] status)
{
var request = new RestRequest
{
Resource = "/api/{apikey}/movie.list?status={status}",
OnBeforeDeserialization = (x =>
{
x.Content = x.Content.Replace("[]", "{}");
})
};
request.AddUrlSegment("apikey", apiKey);
request.AddUrlSegment("status", string.Join(",", status));
try
{
var obj = RetryHandler.Execute(() => Api.Execute<CouchPotatoMovies> (request, baseUrl),
new[] {
TimeSpan.FromSeconds (5),
TimeSpan.FromSeconds(10),
TimeSpan.FromSeconds(30)
},
(exception, timespan) => Log.Error (exception, "Exception when calling GetMovies for CP, Retrying {0}", timespan));
return obj;
}
catch (Exception e) // Request error is already logged in the ApiRequest class
{
Log.Error("Error when attempting to GetMovies.");
Log.Error (e);
return new CouchPotatoMovies();
}
}
}
}

@ -1,245 +1,245 @@
#region Copyright
// /************************************************************************
// Copyright (c) 2016 Jamie Rees
// File: Setup.cs
// Created By: Jamie Rees
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
// ************************************************************************/
#endregion
using System;
using System.Text.RegularExpressions;
using Mono.Data.Sqlite;
using NLog;
using PlexRequests.Api;
using PlexRequests.Core.SettingModels;
using PlexRequests.Helpers;
using PlexRequests.Store;
using PlexRequests.Store.Repository;
using System.Threading.Tasks;
namespace PlexRequests.Core
{
public class Setup
{
private static Logger Log = LogManager.GetCurrentClassLogger();
private static DbConfiguration Db { get; set; }
public string SetupDb(string urlBase)
{
Db = new DbConfiguration(new SqliteFactory());
var created = Db.CheckDb();
TableCreation.CreateTables(Db.DbConnection());
if (created)
{
CreateDefaultSettingsPage(urlBase);
}
var version = CheckSchema();
if (version > 0)
{
if (version > 1700 && version <= 1799)
{
MigrateToVersion1700();
}
if (version > 1799 && version <= 1800)
{
MigrateToVersion1800();
}
}
return Db.DbConnection().ConnectionString;
}
public static string ConnectionString => Db.DbConnection().ConnectionString;
private int CheckSchema()
{
var productVersion = AssemblyHelper.GetProductVersion();
var trimStatus = new Regex("[^0-9]", RegexOptions.Compiled).Replace(productVersion, string.Empty).PadRight(4, '0');
var version = int.Parse(trimStatus);
var connection = Db.DbConnection();
var schema = connection.GetSchemaVersion();
if (schema == null)
{
connection.CreateSchema(version); // Set the default.
schema = connection.GetSchemaVersion();
}
if (version > schema.SchemaVersion)
{
Db.DbConnection().UpdateSchemaVersion(version);
schema = connection.GetSchemaVersion();
}
version = schema.SchemaVersion;
return version;
}
private void CreateDefaultSettingsPage(string baseUrl)
{
var defaultSettings = new PlexRequestSettings
{
RequireTvShowApproval = true,
RequireMovieApproval = true,
SearchForMovies = true,
SearchForTvShows = true,
WeeklyRequestLimit = 0,
BaseUrl = baseUrl ?? string.Empty,
CollectAnalyticData = true,
};
var s = new SettingsServiceV2<PlexRequestSettings>(new SettingsJsonRepository(new DbConfiguration(new SqliteFactory()), new MemoryCacheProvider()));
s.SaveSettings(defaultSettings);
}
public void CacheQualityProfiles()
{
var mc = new MemoryCacheProvider();
try
{
Task.Run(() => { CacheSonarrQualityProfiles(mc); });
Task.Run(() => { CacheCouchPotatoQualityProfiles(mc); });
// we don't need to cache sickrage profiles, those are static
// TODO: cache headphones profiles?
}
catch (Exception)
{
Log.Error("Failed to cache quality profiles on startup!");
}
}
private void CacheSonarrQualityProfiles(MemoryCacheProvider cacheProvider)
{
try
{
Log.Info("Executing GetSettings call to Sonarr for quality profiles");
var sonarrSettingsService = new SettingsServiceV2<SonarrSettings>(new SettingsJsonRepository(new DbConfiguration(new SqliteFactory()), new MemoryCacheProvider()));
var sonarrSettings = sonarrSettingsService.GetSettings();
if (sonarrSettings.Enabled)
{
Log.Info("Begin executing GetProfiles call to Sonarr for quality profiles");
SonarrApi sonarrApi = new SonarrApi();
var profiles = sonarrApi.GetProfiles(sonarrSettings.ApiKey, sonarrSettings.FullUri);
cacheProvider.Set(CacheKeys.SonarrQualityProfiles, profiles);
Log.Info("Finished executing GetProfiles call to Sonarr for quality profiles");
}
}
catch (Exception ex)
{
Log.Error(ex, "Failed to cache Sonarr quality profiles!");
}
}
private void CacheCouchPotatoQualityProfiles(MemoryCacheProvider cacheProvider)
{
try
{
Log.Info("Executing GetSettings call to CouchPotato for quality profiles");
var cpSettingsService = new SettingsServiceV2<CouchPotatoSettings>(new SettingsJsonRepository(new DbConfiguration(new SqliteFactory()), new MemoryCacheProvider()));
var cpSettings = cpSettingsService.GetSettings();
if (cpSettings.Enabled)
{
Log.Info("Begin executing GetProfiles call to CouchPotato for quality profiles");
CouchPotatoApi cpApi = new CouchPotatoApi();
var profiles = cpApi.GetProfiles(cpSettings.FullUri, cpSettings.ApiKey);
cacheProvider.Set(CacheKeys.CouchPotatoQualityProfiles, profiles);
Log.Info("Finished executing GetProfiles call to CouchPotato for quality profiles");
}
}
catch (Exception ex)
{
Log.Error(ex, "Failed to cache CouchPotato quality profiles!");
}
}
public void MigrateToVersion1700()
{
// Drop old tables
TableCreation.DropTable(Db.DbConnection(), "User");
TableCreation.DropTable(Db.DbConnection(), "Log");
}
/// <summary>
/// Migrates to version 1.8.
/// <para>This includes updating the admin account to have all roles.</para>
/// <para>Set the log level to Error</para>
/// <para>Enable Analytics by default</para>
/// </summary>
private void MigrateToVersion1800()
{
// Give admin all roles/claims
try
{
var userMapper = new UserMapper(new UserRepository<UsersModel>(Db, new MemoryCacheProvider()));
var users = userMapper.GetUsers();
foreach (var u in users)
{
var claims = new[] { UserClaims.User, UserClaims.Admin, UserClaims.PowerUser };
u.Claims = ByteConverterHelper.ReturnBytes(claims);
userMapper.EditUser(u);
}
}
catch (Exception e)
{
Log.Error(e);
}
// Set log level
try
{
var settingsService = new SettingsServiceV2<LogSettings>(new SettingsJsonRepository(Db, new MemoryCacheProvider()));
var logSettings = settingsService.GetSettings();
logSettings.Level = LogLevel.Error.Ordinal;
settingsService.SaveSettings(logSettings);
LoggingHelper.ReconfigureLogLevel(LogLevel.FromOrdinal(logSettings.Level));
}
catch (Exception e)
{
Log.Error(e);
}
// Enable analytics;
try
{
var prSettings = new SettingsServiceV2<PlexRequestSettings>(new SettingsJsonRepository(Db, new MemoryCacheProvider()));
var settings = prSettings.GetSettings();
settings.CollectAnalyticData = true;
var updated = prSettings.SaveSettings(settings);
}
catch (Exception e)
{
Log.Error(e);
}
}
}
}
#region Copyright
// /************************************************************************
// Copyright (c) 2016 Jamie Rees
// File: Setup.cs
// Created By: Jamie Rees
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
// ************************************************************************/
#endregion
using System;
using System.Text.RegularExpressions;
using Mono.Data.Sqlite;
using NLog;
using PlexRequests.Api;
using PlexRequests.Core.SettingModels;
using PlexRequests.Helpers;
using PlexRequests.Store;
using PlexRequests.Store.Repository;
using System.Threading.Tasks;
namespace PlexRequests.Core
{
public class Setup
{
private static Logger Log = LogManager.GetCurrentClassLogger();
private static DbConfiguration Db { get; set; }
public string SetupDb(string urlBase)
{
Db = new DbConfiguration(new SqliteFactory());
var created = Db.CheckDb();
TableCreation.CreateTables(Db.DbConnection());
if (created)
{
CreateDefaultSettingsPage(urlBase);
}
var version = CheckSchema();
if (version > 0)
{
if (version > 1700 && version <= 1799)
{
MigrateToVersion1700();
}
if (version > 1799 && version <= 1800)
{
MigrateToVersion1800();
}
}
return Db.DbConnection().ConnectionString;
}
public static string ConnectionString => Db.DbConnection().ConnectionString;
private int CheckSchema()
{
var productVersion = AssemblyHelper.GetProductVersion();
var trimStatus = new Regex("[^0-9]", RegexOptions.Compiled).Replace(productVersion, string.Empty).PadRight(4, '0');
var version = int.Parse(trimStatus);
var connection = Db.DbConnection();
var schema = connection.GetSchemaVersion();
if (schema == null)
{
connection.CreateSchema(version); // Set the default.
schema = connection.GetSchemaVersion();
}
if (version > schema.SchemaVersion)
{
Db.DbConnection().UpdateSchemaVersion(version);
schema = connection.GetSchemaVersion();
}
version = schema.SchemaVersion;
return version;
}
private void CreateDefaultSettingsPage(string baseUrl)
{
var defaultSettings = new PlexRequestSettings
{
RequireTvShowApproval = true,
RequireMovieApproval = true,
SearchForMovies = true,
SearchForTvShows = true,
WeeklyRequestLimit = 0,
BaseUrl = baseUrl ?? string.Empty,
CollectAnalyticData = true,
};
var s = new SettingsServiceV2<PlexRequestSettings>(new SettingsJsonRepository(new DbConfiguration(new SqliteFactory()), new MemoryCacheProvider()));
s.SaveSettings(defaultSettings);
}
public void CacheQualityProfiles()
{
var mc = new MemoryCacheProvider();
try
{
Task.Run(() => { CacheSonarrQualityProfiles(mc); });
Task.Run(() => { CacheCouchPotatoQualityProfiles(mc); });
// we don't need to cache sickrage profiles, those are static
// TODO: cache headphones profiles?
}
catch (Exception)
{
Log.Error("Failed to cache quality profiles on startup!");
}
}
private void CacheSonarrQualityProfiles(MemoryCacheProvider cacheProvider)
{
try
{
Log.Info("Executing GetSettings call to Sonarr for quality profiles");
var sonarrSettingsService = new SettingsServiceV2<SonarrSettings>(new SettingsJsonRepository(new DbConfiguration(new SqliteFactory()), new MemoryCacheProvider()));
var sonarrSettings = sonarrSettingsService.GetSettings();
if (sonarrSettings.Enabled)
{
Log.Info("Begin executing GetProfiles call to Sonarr for quality profiles");
SonarrApi sonarrApi = new SonarrApi();
var profiles = sonarrApi.GetProfiles(sonarrSettings.ApiKey, sonarrSettings.FullUri);
cacheProvider.Set(CacheKeys.SonarrQualityProfiles, profiles);
Log.Info("Finished executing GetProfiles call to Sonarr for quality profiles");
}
}
catch (Exception ex)
{
Log.Error(ex, "Failed to cache Sonarr quality profiles!");
}
}
private void CacheCouchPotatoQualityProfiles(MemoryCacheProvider cacheProvider)
{
try
{
Log.Info("Executing GetSettings call to CouchPotato for quality profiles");
var cpSettingsService = new SettingsServiceV2<CouchPotatoSettings>(new SettingsJsonRepository(new DbConfiguration(new SqliteFactory()), new MemoryCacheProvider()));
var cpSettings = cpSettingsService.GetSettings();
if (cpSettings.Enabled)
{
Log.Info("Begin executing GetProfiles call to CouchPotato for quality profiles");
CouchPotatoApi cpApi = new CouchPotatoApi();
var profiles = cpApi.GetProfiles(cpSettings.FullUri, cpSettings.ApiKey);
cacheProvider.Set(CacheKeys.CouchPotatoQualityProfiles, profiles);
Log.Info("Finished executing GetProfiles call to CouchPotato for quality profiles");
}
}
catch (Exception ex)
{
Log.Error(ex, "Failed to cache CouchPotato quality profiles!");
}
}
public void MigrateToVersion1700()
{
// Drop old tables
TableCreation.DropTable(Db.DbConnection(), "User");
TableCreation.DropTable(Db.DbConnection(), "Log");
}
/// <summary>
/// Migrates to version 1.8.
/// <para>This includes updating the admin account to have all roles.</para>
/// <para>Set the log level to Error</para>
/// <para>Enable Analytics by default</para>
/// </summary>
private void MigrateToVersion1800()
{
// Give admin all roles/claims
try
{
var userMapper = new UserMapper(new UserRepository<UsersModel>(Db, new MemoryCacheProvider()));
var users = userMapper.GetUsers();
foreach (var u in users)
{
var claims = new[] { UserClaims.User, UserClaims.Admin, UserClaims.PowerUser };
u.Claims = ByteConverterHelper.ReturnBytes(claims);
userMapper.EditUser(u);
}
}
catch (Exception e)
{
Log.Error(e);
}
// Set log level
try
{
var settingsService = new SettingsServiceV2<LogSettings>(new SettingsJsonRepository(Db, new MemoryCacheProvider()));
var logSettings = settingsService.GetSettings();
logSettings.Level = LogLevel.Error.Ordinal;
settingsService.SaveSettings(logSettings);
LoggingHelper.ReconfigureLogLevel(LogLevel.FromOrdinal(logSettings.Level));
}
catch (Exception e)
{
Log.Error(e);
}
// Enable analytics;
try
{
var prSettings = new SettingsServiceV2<PlexRequestSettings>(new SettingsJsonRepository(Db, new MemoryCacheProvider()));
var settings = prSettings.GetSettings();
settings.CollectAnalyticData = true;
var updated = prSettings.SaveSettings(settings);
}
catch (Exception e)
{
Log.Error(e);
}
}
}
}

File diff suppressed because it is too large Load Diff

@ -1,58 +1,58 @@
![](http://i.imgur.com/s4nswSA.png?1)
____
[![Gitter](https://badges.gitter.im/tidusjar/PlexRequest.NET.svg)](https://gitter.im/tidusjar/PlexRequests.Net?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge)
[![Build status](https://ci.appveyor.com/api/projects/status/hgj8j6lcea7j0yhn?svg=true)](https://ci.appveyor.com/project/tidusjar/requestplex)
[![Linux Status](https://travis-ci.org/tidusjar/PlexRequests.Net.svg)](https://travis-ci.org/tidusjar/PlexRequests.Net)
[![Average time to resolve an issue](http://isitmaintained.com/badge/resolution/tidusjar/plexrequests.net.svg)](http://isitmaintained.com/project/tidusjar/plexrequests.net "Average time to resolve an issue")
[![Percentage of issues still open](http://isitmaintained.com/badge/open/tidusjar/plexrequests.net.svg)](http://isitmaintained.com/project/tidusjar/plexrequests.net "Percentage of issues still open")
[![Github All Releases](https://img.shields.io/github/downloads/tidusjar/PlexRequests.net/total.svg)](https://github.com/tidusjar/PlexRequests.Net)
[![Stories in Progress](https://badge.waffle.io/tidusjar/PlexRequests.Net.svg?label=in progress&title=In Progress)](http://waffle.io/tidusjar/PlexRequests.Net)
This is based off [Plex Requests by lokenx](https://github.com/lokenx/plexrequests-meteor) so big props to that guy!
I wanted to write a similar application in .Net!
# Features
* Movie and TV Show searching, can't find something on Plex? Just request it!
* Notifications! Get notified via Email, Pushbullet and Pushover for new requests and issue reports!
* Send your TV Shows to either [Sonarr](https://sonarr.tv/) or [SickRage](http://www.sickrage.ca/)!
* Secure authentication so you don't have to worry about those script kiddies
* We check to see if the request is already in Plex, if it's already in Plex then why you requesting it?!
* We have allowed the ability for a user to add a custom note on a request
* It automatically update the status of requests when they are available on Plex
* Slick, responsive and mobile friendly UI
* Headphones integration!
* Ability to run with a reverse proxy!
# Preview ()
![Preview](http://i.imgur.com/DgwkIsW.gif)
#Installation
[Windows Guide!](http://www.htpcguides.com/install-plex-requests-net-windows-system-service/)
[Ubuntu Guide!](http://www.htpcguides.com/install-plex-requests-net-ubuntu-14-x/)
# FAQ
Do you have an issue or a question? if so check out our [FAQ!](https://github.com/tidusjar/PlexRequests.Net/wiki/FAQ)
# Docker
Looking for a Docker Image? Well [rogueosb](https://github.com/rogueosb/) has created a docker image for us, You can find it [here](https://github.com/rogueosb/docker-plexrequestsnet) :smile:
# Contributors
We are looking for any contributions to the project! Just pick up a task, if you have any questions ask and i'll get straight on it!
Please feed free to submit a pull request!
# Donation
If you feel like donating you can [here!](https://paypal.me/PlexRequestsNet)
## A massive thanks to everyone below for all their help!
[heartisall](https://github.com/heartisall), [Stuke00](https://github.com/Stuke00), [shiitake](https://github.com/shiitake), [Drewster727](https://github.com/Drewster727), Majawat, [EddiYo](https://github.com/EddiYo), [SaskiFX](https://github.com/SaskiFX), [zenjabba](https://github.com/zenjabba)
## Stats
[![Throughput Graph](https://graphs.waffle.io/tidusjar/PlexRequests.Net/throughput.svg)](https://waffle.io/tidusjar/PlexRequests.Net/metrics/throughput)
![](http://i.imgur.com/s4nswSA.png?1)
____
[![Gitter](https://badges.gitter.im/tidusjar/PlexRequest.NET.svg)](https://gitter.im/tidusjar/PlexRequests.Net?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge)
[![Build status](https://ci.appveyor.com/api/projects/status/hgj8j6lcea7j0yhn?svg=true)](https://ci.appveyor.com/project/tidusjar/requestplex)
[![Linux Status](https://travis-ci.org/tidusjar/PlexRequests.Net.svg)](https://travis-ci.org/tidusjar/PlexRequests.Net)
[![Average time to resolve an issue](http://isitmaintained.com/badge/resolution/tidusjar/plexrequests.net.svg)](http://isitmaintained.com/project/tidusjar/plexrequests.net "Average time to resolve an issue")
[![Percentage of issues still open](http://isitmaintained.com/badge/open/tidusjar/plexrequests.net.svg)](http://isitmaintained.com/project/tidusjar/plexrequests.net "Percentage of issues still open")
[![Github All Releases](https://img.shields.io/github/downloads/tidusjar/PlexRequests.net/total.svg)](https://github.com/tidusjar/PlexRequests.Net)
[![Stories in Progress](https://badge.waffle.io/tidusjar/PlexRequests.Net.svg?label=in progress&title=In Progress)](http://waffle.io/tidusjar/PlexRequests.Net)
This is based off [Plex Requests by lokenx](https://github.com/lokenx/plexrequests-meteor) so big props to that guy!
I wanted to write a similar application in .Net!
# Features
* Movie and TV Show searching, can't find something on Plex? Just request it!
* Notifications! Get notified via Email, Pushbullet and Pushover for new requests and issue reports!
* Send your TV Shows to either [Sonarr](https://sonarr.tv/) or [SickRage](http://www.sickrage.ca/)!
* Secure authentication so you don't have to worry about those script kiddies
* We check to see if the request is already in Plex, if it's already in Plex then why you requesting it?!
* We have allowed the ability for a user to add a custom note on a request
* It automatically update the status of requests when they are available on Plex
* Slick, responsive and mobile friendly UI
* Headphones integration!
* Ability to run with a reverse proxy!
# Preview ()
![Preview](http://i.imgur.com/DgwkIsW.gif)
#Installation
[Windows Guide!](http://www.htpcguides.com/install-plex-requests-net-windows-system-service/)
[Ubuntu Guide!](http://www.htpcguides.com/install-plex-requests-net-ubuntu-14-x/)
# FAQ
Do you have an issue or a question? if so check out our [FAQ!](https://github.com/tidusjar/PlexRequests.Net/wiki/FAQ)
# Docker
Looking for a Docker Image? Well [rogueosb](https://github.com/rogueosb/) has created a docker image for us, You can find it [here](https://github.com/rogueosb/docker-plexrequestsnet) :smile:
# Contributors
We are looking for any contributions to the project! Just pick up a task, if you have any questions ask and i'll get straight on it!
Please feed free to submit a pull request!
# Donation
If you feel like donating you can [here!](https://paypal.me/PlexRequestsNet)
## A massive thanks to everyone below for all their help!
[heartisall](https://github.com/heartisall), [Stuke00](https://github.com/Stuke00), [shiitake](https://github.com/shiitake), [Drewster727](https://github.com/Drewster727), Majawat, [EddiYo](https://github.com/EddiYo), [SaskiFX](https://github.com/SaskiFX), [zenjabba](https://github.com/zenjabba)
## Stats
[![Throughput Graph](https://graphs.waffle.io/tidusjar/PlexRequests.Net/throughput.svg)](https://waffle.io/tidusjar/PlexRequests.Net/metrics/throughput)

Loading…
Cancel
Save