1
0
Fork 0
mirror of https://github.com/Jackett/Jackett synced 2025-03-05 19:29:03 +00:00

Merge fixes from develop

This commit is contained in:
KZ 2015-07-25 09:35:25 +01:00
commit e460c0402a
22 changed files with 410 additions and 111 deletions

View file

@ -1,5 +1,6 @@
rmdir /s /q build
rmdir /s /q Output
cd src
Msbuild Jackett.sln /t:Clean,Build /p:Configuration=Release
cd ..
@ -9,6 +10,8 @@ copy /Y src\Jackett.Service\bin\Release\JackettService.exe build\JackettService.
copy /Y src\Jackett.Service\bin\Release\JackettService.exe.config build\JackettService.exe.config
copy /Y src\Jackett.Tray\bin\Release\JackettTray.exe build\JackettTray.exe
copy /Y src\Jackett.Tray\bin\Release\JackettTray.exe.config build\JackettTray.exe.config
copy /Y LICENSE build\LICENSE
copy /Y README.md build\README.md
cd build
del *.pdb
del *.xml

View file

@ -49,12 +49,13 @@ Name: "{commondesktop}\{#MyAppName}"; Filename: "{app}\{#MyAppExeName}"; Tasks:
Filename: "{app}\{#MyAppExeName}"; Description: "{cm:LaunchProgram,{#StringChange(MyAppName, '&', '&&')}}"; Flags: nowait postinstall skipifsilent
[Run]
Filename: "{app}\JackettConsole.exe"; Parameters: "/u"; Flags: waituntilterminated;
Filename: "{app}\JackettConsole.exe"; Parameters: "/r"; Flags: waituntilterminated;
Filename: "{app}\JackettConsole.exe"; Parameters: "/i"; Flags: waituntilterminated; Tasks: windowsService
Filename: "{app}\JackettConsole.exe"; Parameters: "/start"; Flags: waituntilterminated; Tasks: windowsService
Filename: "{app}\JackettConsole.exe"; Parameters: "--Uninstall"; Flags: waituntilterminated;
Filename: "{app}\JackettConsole.exe"; Parameters: "--ReserveUrls"; Flags: waituntilterminated;
Filename: "{app}\JackettConsole.exe"; Parameters: "--MigrateSettings"; Flags: waituntilterminated;
Filename: "{app}\JackettConsole.exe"; Parameters: "--Install"; Flags: waituntilterminated; Tasks: windowsService
Filename: "{app}\JackettConsole.exe"; Parameters: "--Start"; Flags: waituntilterminated; Tasks: windowsService
[UninstallRun]
Filename: "{app}\JackettConsole.exe"; Parameters: "/u"; Flags: waituntilterminated skipifdoesntexist
Filename: "{app}\JackettConsole.exe"; Parameters: "--Uninstall"; Flags: waituntilterminated skipifdoesntexist

View file

@ -0,0 +1,51 @@
using CommandLine;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Jackett.Console
{
public class ConsoleOptions
{
[Option('i', "Install", HelpText = "Install Jackett windows service (Must be admin)")]
public bool Install { get; set; }
[Option('r', "ReserveUrls", HelpText = "(Re)Register windows port reservations (Required for listening on all interfaces).")]
public bool ReserveUrls { get; set; }
[Option('u', "Uninstall", HelpText = "Uninstall Jackett windows service (Must be admin).")]
public bool Uninstall { get; set; }
[Option('l', "Logging", HelpText = "Log all requests/responses to Jackett")]
public bool Logging { get; set; }
[Option('t', "Tracing", HelpText = "Enable tracing")]
public bool Tracing { get; set; }
[Option('c', "UseCurlExec", HelpText = "Execute curl rather than libcurl for all outgoing requests.")]
public bool UseCurlExec { get; set; }
[Option('s', "Start", HelpText = "Start the Jacket Windows service (Must be admin)")]
public bool StartService { get; set; }
[Option('k', "Stop", HelpText = "Stop the Jacket Windows service (Must be admin)")]
public bool StopService { get; set; }
[Option('l', "ListenPublic", HelpText = "Listen publicly")]
public bool? ListenPublic { get; set; }
[Option('h', "Help", HelpText = "Show Help")]
public bool ShowHelp { get; set; }
[Option('v', "Version", HelpText = "Show Version")]
public bool ShowVersion { get; set; }
[Option('p', "Port", HelpText = "Web server port")]
public int Port { get; set; }
[Option('m', "MigrateSettings", HelpText = "Migrate settings manually (Must be admin on Windows)")]
public bool MigrateSettings { get; set; }
}
}

View file

@ -16,7 +16,7 @@
</NuGetPackageImportStamp>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' ">
<PlatformTarget>AnyCPU</PlatformTarget>
<PlatformTarget>x64</PlatformTarget>
<DebugSymbols>true</DebugSymbols>
<DebugType>full</DebugType>
<Optimize>false</Optimize>
@ -55,6 +55,10 @@
<Reference Include="Autofac.Integration.WebApi.Owin">
<HintPath>..\packages\Autofac.WebApi2.Owin.3.2.0\lib\net45\Autofac.Integration.WebApi.Owin.dll</HintPath>
</Reference>
<Reference Include="CommandLine, Version=1.9.71.2, Culture=neutral, PublicKeyToken=de6f01bd326f8c32, processorArchitecture=MSIL">
<HintPath>..\packages\CommandLineParser.1.9.71\lib\net45\CommandLine.dll</HintPath>
<Private>True</Private>
</Reference>
<Reference Include="Microsoft.AspNet.Identity.Core">
<HintPath>..\packages\Microsoft.AspNet.Identity.Core.2.2.1\lib\net45\Microsoft.AspNet.Identity.Core.dll</HintPath>
</Reference>
@ -127,6 +131,7 @@
<Reference Include="System.Xml" />
</ItemGroup>
<ItemGroup>
<Compile Include="ConsoleOptions.cs" />
<Compile Include="Program.cs" />
<Compile Include="Properties\AssemblyInfo.cs" />
</ItemGroup>

View file

@ -1,5 +1,9 @@
using Jackett;
using CommandLine;
using CommandLine.Text;
using Jackett;
using Jackett.Console;
using Jackett.Indexers;
using Jackett.Utils;
using System;
using System.Collections.Generic;
using System.Diagnostics;
@ -18,44 +22,152 @@ namespace JackettConsole
{
try
{
foreach (var arg in args)
var options = new ConsoleOptions();
if (!Parser.Default.ParseArguments(args, options) || options.ShowHelp == true)
{
switch (arg.ToLowerInvariant())
var text = HelpText.AutoBuild(options, (HelpText current) => HelpText.DefaultParsingErrorsHandler(options, current));
text.Copyright = " ";
text.Heading = "Jackett v" + Engine.ConfigService.GetVersion() + " options:";
Console.WriteLine(text);
Environment.ExitCode = 1;
return;
}
else
{
/* ====== Options ===== */
// Use curl
if (options.UseCurlExec)
Startup.CurlSafe = true;
// Logging
if (options.Logging)
Startup.LogRequests = true;
// Tracing
if (options.Tracing)
Startup.TracingEnabled = true;
// Log after the fact as using the logger will cause the options above to be used
if (options.UseCurlExec)
Engine.Logger.Info("Safe curl enabled.");
if (options.Logging)
Engine.Logger.Info("Logging enabled.");
if (options.Tracing)
Engine.Logger.Info("Tracing enabled.");
/* ====== Actions ===== */
// Install service
if (options.Install)
{
case "/i": // Install
Engine.ServiceConfig.Install();
return;
case "/r": // Reserve port/url & install
Engine.Server.ReserveUrls(doInstall: true);
return;
case "/c": // Change port
Engine.Server.ReserveUrls(doInstall: false);
return;
case "/u": // Uninstall
Engine.Server.ReserveUrls(doInstall: false);
Engine.ServiceConfig.Uninstall();
return;
case "/l": // Logging
Startup.LogRequests = true;
break;
case "/t": // Tracing
Startup.TracingEnabled = true;
break;
case "/curlsafe": // Curl safe mode
Startup.CurlSafe = true;
break;
case "/start": // Start Service
if (!Engine.ServiceConfig.ServiceRunning())
Engine.ServiceConfig.Install();
return;
}
// Uninstall service
if (options.Uninstall)
{
Engine.Server.ReserveUrls(doInstall: false);
Engine.ServiceConfig.Uninstall();
return;
}
// Reserve urls
if (options.ReserveUrls)
{
Engine.Server.ReserveUrls(doInstall: true);
return;
}
// Start Service
if (options.StartService)
{
if (!Engine.ServiceConfig.ServiceRunning())
{
Engine.ServiceConfig.Start();
}
return;
}
// Stop Service
if (options.StopService)
{
if (Engine.ServiceConfig.ServiceRunning())
{
Engine.ServiceConfig.Stop();
}
return;
}
// Migrate settings
if (options.MigrateSettings)
{
Engine.ConfigService.PerformMigration();
return;
}
// Show Version
if (options.ShowVersion)
{
Console.WriteLine("Jackett v" + Engine.ConfigService.GetVersion());
return;
}
/* ====== Overrides ===== */
// Override listen public
if(options.ListenPublic.HasValue)
{
if (Engine.Server.Config.AllowExternal != options.ListenPublic)
{
Engine.Logger.Info("Overriding external access to " + options.ListenPublic);
Engine.Server.Config.AllowExternal = options.ListenPublic.Value;
if (System.Environment.OSVersion.Platform != PlatformID.Unix)
{
Engine.ServiceConfig.Start();
if (ServerUtil.IsUserAdministrator())
{
Engine.Server.ReserveUrls(doInstall: true);
}
else
{
Engine.Logger.Error("Unable to switch to public listening without admin rights.");
Environment.ExitCode = 1;
return;
}
}
return;
case "/stop": // Stop Service
if (Engine.ServiceConfig.ServiceRunning())
Engine.Server.SaveConfig();
}
}
// Override port
if(options.Port != 0)
{
if (Engine.Server.Config.Port != options.Port)
{
Engine.Logger.Info("Overriding port to " + options.Port);
Engine.Server.Config.Port = options.Port;
if (System.Environment.OSVersion.Platform != PlatformID.Unix)
{
Engine.ServiceConfig.Stop();
if (ServerUtil.IsUserAdministrator())
{
Engine.Server.ReserveUrls(doInstall: true);
}
else
{
Engine.Logger.Error("Unable to switch ports when not running as administrator");
Environment.ExitCode = 1;
return;
}
}
return;
Engine.Server.SaveConfig();
}
}
}

View file

@ -4,6 +4,7 @@
<package id="Autofac.Owin" version="3.1.0" targetFramework="net452" />
<package id="Autofac.WebApi2" version="3.4.0" targetFramework="net452" />
<package id="Autofac.WebApi2.Owin" version="3.2.0" targetFramework="net452" />
<package id="CommandLineParser" version="1.9.71" targetFramework="net452" />
<package id="Microsoft.AspNet.Identity.Core" version="2.2.1" targetFramework="net452" />
<package id="Microsoft.AspNet.WebApi.Client" version="5.2.3" targetFramework="net452" />
<package id="Microsoft.AspNet.WebApi.Core" version="5.2.3" targetFramework="net452" />

View file

@ -141,7 +141,7 @@ namespace JackettTray
{
try
{
Engine.ProcessService.StartProcessAndLog(consolePath, "/stop", true);
Engine.ProcessService.StartProcessAndLog(consolePath, "--Stop", true);
}
catch
{
@ -159,7 +159,7 @@ namespace JackettTray
{
try
{
Engine.ProcessService.StartProcessAndLog(consolePath, "/start", true);
Engine.ProcessService.StartProcessAndLog(consolePath, "--Start", true);
}
catch
{

View file

@ -203,3 +203,7 @@ hr {
margin-top: 10px;
text-align: center;
}
#jackett-allowext {
width: 25px;
}

View file

@ -7,6 +7,7 @@ function loadJackettSettings() {
$("#api-key-input").val(data.config.api_key);
$("#app-version").html(data.app_version);
$("#jackett-port").val(data.config.port);
$("#jackett-allowext").attr('checked', data.config.external);
var password = data.config.password;
$("#jackett-adminpwd").val(password);
if (password != null && password != '') {
@ -17,20 +18,21 @@ function loadJackettSettings() {
$("#change-jackett-port").click(function () {
var jackett_port = $("#jackett-port").val();
var jsonObject = { port: jackett_port};
var jackett_external = $("#jackett-allowext").is(':checked');
var jsonObject = { port: jackett_port, external: jackett_external};
var jqxhr = $.post("/admin/set_port", JSON.stringify(jsonObject), function (data) {
if (data.result == "error") {
doNotify("Error: " + data.error, "danger", "glyphicon glyphicon-alert");
return;
} else {
doNotify("The port has been changed. Redirecting you to the new port.", "success", "glyphicon glyphicon-ok");
var jqxhr0 = $.post("admin/jackett_restart", null, function (data_restart) { });
window.setTimeout(function () {
url = window.location.href;
window.location.href = url.substr(0, url.lastIndexOf(":") + 1) + data.port;
if (data.external) {
window.location.href = url.substr(0, url.lastIndexOf(":") + 1) + data.port;
} else {
window.location.href = 'http://127.0.0.1:' + data.port;
}
}, 3000);
}

View file

@ -35,26 +35,33 @@
<span class="input-header">API Key: </span>
<input id="api-key-input" class="form-control input-right" type="text" value="" placeholder="API Key" readonly="">
</div>
<hr />
<h3>Configured Indexers</h3>
<div id="indexers"> </div>
<hr />
<h3>Jackett Configuration</h3>
<div class="input-area">
<span class="input-header">Admin Password: </span>
<input id="jackett-adminpwd" class="form-control input-right" type="password" value="" placeholder="Blank to disable">
<input id="jackett-adminpwd" class="form-control input-right" type="password" value="" placeholder="Blank to disable" />
<button id="change-jackett-password" class="btn btn-primary btn-sm">
Set Password <span class="glyphicon glyphicon-ok-wrench" aria-hidden="true"></span>
</button>
<a href="Dashboard?logout=true" id="logoutBtn" style="display:none" class="btn btn-danger btn-sm">
Logout
Logout
</a>
</div>
<div class="input-area">
<span class="input-header">Server port: </span>
<input id="jackett-port" class="form-control input-right" type="text" value="" placeholder="9117">
<button id="change-jackett-port" class="btn btn-primary btn-sm">
Change Port <span class="glyphicon glyphicon-ok-wrench" aria-hidden="true"></span>
Apply server settings <span class="glyphicon glyphicon-ok-wrench" aria-hidden="true"></span>
</button>
</div>
<hr />
<h3>Configured Indexers</h3>
<div id="indexers"> </div>
<div class="input-area">
<span class="input-header">External access: </span>
<input id="jackett-allowext" class="form-control input-right" type="checkbox" />
</div>
<hr />
<div id="footer">
Jackett Version <span id="app-version"></span>

Binary file not shown.

After

(image error) Size: 3.7 KiB

View file

@ -44,12 +44,21 @@ namespace Jackett.Controllers
if (!string.Equals(torznabQuery.ApiKey, serverService.Config.APIKey, StringComparison.InvariantCultureIgnoreCase))
{
logger.Warn(string.Format("A request from {0} was made with an incorrect API key.", Request.GetOwinContext().Request.RemoteIpAddress));
return Request.CreateResponse(HttpStatusCode.Forbidden, "Incorrect API key");
}
var releases = await indexer.PerformQuery(torznabQuery);
logger.Info(string.Format("Found {0} releases from {1}", releases.Length, indexer.DisplayName));
if (string.IsNullOrWhiteSpace(torznabQuery.SanitizedSearchTerm))
{
logger.Info(string.Format("Found {0} releases from {1}", releases.Length, indexer.DisplayName));
}
else
{
logger.Info(string.Format("Found {0} releases from {1} for: {2}", releases.Length, indexer.DisplayName, torznabQuery.SanitizedSearchTerm));
}
var severUrl = string.Format("{0}://{1}:{2}/", Request.RequestUri.Scheme, Request.RequestUri.Host, Request.RequestUri.Port);
var resultPage = new ResultPage(new ChannelInfo

View file

@ -260,6 +260,7 @@ namespace Jackett.Controllers
{
var cfg = new JObject();
cfg["port"] = serverService.Config.Port;
cfg["external"] = serverService.Config.AllowExternal;
cfg["api_key"] = serverService.Config.APIKey;
cfg["password"] = string.IsNullOrEmpty(serverService.Config.AdminPassword )? string.Empty:serverService.Config.AdminPassword.Substring(0,10);
@ -285,13 +286,15 @@ namespace Jackett.Controllers
public async Task<IHttpActionResult> SetConfig()
{
var originalPort = Engine.Server.Config.Port;
var originalAllowExternal = Engine.Server.Config.AllowExternal;
var jsonReply = new JObject();
try
{
var postData = await ReadPostDataJson();
int port = (int)postData["port"];
bool external = (bool)postData["external"];
if (port != Engine.Server.Config.Port)
if (port != Engine.Server.Config.Port || external != Engine.Server.Config.AllowExternal)
{
if (ServerUtil.RestrictedPorts.Contains(port))
{
@ -300,35 +303,48 @@ namespace Jackett.Controllers
return Json(jsonReply);
}
// Save port to the config so it can be picked up by the if needed when running as admin below.
Engine.Server.Config.AllowExternal = external;
Engine.Server.Config.Port = port;
Engine.Server.SaveConfig();
if (!ServerUtil.IsUserAdministrator())
// On Windows change the url reservations
if (System.Environment.OSVersion.Platform != PlatformID.Unix)
{
try {
processService.StartProcessAndLog(Application.ExecutablePath, "/r", true);
}
catch
if (!ServerUtil.IsUserAdministrator())
{
Engine.Server.Config.Port = originalPort;
Engine.Server.SaveConfig();
jsonReply["result"] = "error";
jsonReply["error"] = "Failed to acquire admin permissions to reserve the new port.";
return Json(jsonReply);
try
{
processService.StartProcessAndLog(Application.ExecutablePath, "--ReserveUrls", true);
}
catch
{
Engine.Server.Config.Port = originalPort;
Engine.Server.Config.AllowExternal = originalAllowExternal;
Engine.Server.SaveConfig();
jsonReply["result"] = "error";
jsonReply["error"] = "Failed to acquire admin permissions to reserve the new port.";
return Json(jsonReply);
}
}
else
{
serverService.ReserveUrls(true);
}
} else
{
serverService.ReserveUrls(true);
}
(new Thread(() => {
Thread.Sleep(500);
serverService.Start();
serverService.Stop();
Engine.BuildContainer();
Engine.Server.Initalize();
Engine.Server.Start();
})).Start();
}
jsonReply["result"] = "success";
jsonReply["port"] = port;
jsonReply["external"] = external;
}
catch (Exception ex)
{

View file

@ -2,6 +2,7 @@
using Jackett.Services;
using NLog;
using NLog.Config;
using NLog.LayoutRenderers;
using NLog.Targets;
using System;
using System.Collections.Generic;
@ -19,7 +20,7 @@ namespace Jackett
static Engine()
{
BuildContainer();
Logger.Info("Starting Jackett " + ConfigService.GetVersion());
}
public static void BuildContainer()
@ -107,8 +108,10 @@ namespace Jackett
private static void SetupLogging(ContainerBuilder builder)
{
var logConfig = new LoggingConfiguration();
// Add custom date time format renderer as the default is too long
ConfigurationItemFactory.Default.LayoutRenderers.RegisterDefinition("simpledatetime", typeof(SimpleDateTimeRenderer));
var logConfig = new LoggingConfiguration();
var logFile = new FileTarget();
logConfig.AddTarget("file", logFile);
logFile.Layout = "${longdate} ${level} ${message} ${exception:format=ToString}";
@ -121,9 +124,10 @@ namespace Jackett
var logFileRule = new LoggingRule("*", LogLevel.Info, logFile);
logConfig.LoggingRules.Add(logFileRule);
var logConsole = new ConsoleTarget();
var logConsole = new ColoredConsoleTarget();
logConfig.AddTarget("console", logConsole);
logConsole.Layout = "${longdate} ${level} ${message} ${exception:format=ToString}";
logConsole.Layout = "${simpledatetime} ${level} ${message} ${exception:format=ToString}";
var logConsoleRule = new LoggingRule("*", Startup.TracingEnabled ? LogLevel.Debug : LogLevel.Info, logConsole);
logConfig.LoggingRules.Add(logConsoleRule);
@ -131,4 +135,13 @@ namespace Jackett
builder.RegisterInstance<Logger>(LogManager.GetCurrentClassLogger()).SingleInstance();
}
}
[LayoutRenderer("simpledatetime")]
public class SimpleDateTimeRenderer : LayoutRenderer
{
protected override void Append(StringBuilder builder, LogEventInfo logEvent)
{
builder.Append(DateTime.Now.ToString("MM-dd HH:mm:ss"));
}
}
}

View file

@ -85,7 +85,7 @@ namespace Jackett.Indexers
else
{
var configSaveData = new JObject();
configSaveData["cookies"] = cookieHeader;
configSaveData["cookie_header"] = cookieHeader;
SaveConfig(configSaveData);
IsConfigured = true;
}
@ -93,7 +93,7 @@ namespace Jackett.Indexers
public void LoadFromSavedConfiguration(JToken jsonConfig)
{
cookieHeader = (string)jsonConfig["cookies"];
cookieHeader = (string)jsonConfig["cookie_header"];
IsConfigured = true;
}
@ -103,12 +103,27 @@ namespace Jackett.Indexers
var searchString = query.SanitizedSearchTerm + " " + query.GetEpisodeSearchString();
var episodeSearchUrl = SearchUrl + HttpUtility.UrlEncode(searchString);
var response = await webclient.GetString(new Utils.Clients.WebRequest()
WebClientStringResult response = null;
// Their web server is fairly flakey - try up to three times.
for (int i = 0; i < 3; i++)
{
Url = episodeSearchUrl,
Referer = SiteLink.ToString(),
Cookies = cookieHeader
});
try
{
response = await webclient.GetString(new Utils.Clients.WebRequest()
{
Url = episodeSearchUrl,
Referer = SiteLink.ToString(),
Cookies = cookieHeader
});
break;
}
catch (Exception e)
{
logger.Error("On attempt " + (i + 1) + " checking for results from IPTorrents: " + e.Message);
}
}
var results = response.Content;
try

View file

@ -52,21 +52,20 @@ namespace Jackett.Indexers
{
var config = new ConfigurationDataBasicLogin();
config.LoadValuesFromJson(configJson);
var pairs = new Dictionary<string, string> {
{ "username", config.Username.Value },
{ "password", config.Password.Value },
{ "login", "Log in" },
{ "keeplogged", "1" }
};
var loginResponse = await client.GetString(new Utils.Clients.WebRequest()
{
PostData = pairs,
Url = LoginUrl,
Type = RequestType.POST
});
if (loginResponse.Status == HttpStatusCode.Found)
{
cookieHeader = loginResponse.Cookies;
@ -88,7 +87,7 @@ namespace Jackett.Indexers
else
{
var configSaveData = new JObject();
configSaveData["cookies"] = cookieHeader;
configSaveData["cookie_header"] = cookieHeader;
SaveConfig(configSaveData);
IsConfigured = true;
}
@ -96,12 +95,8 @@ namespace Jackett.Indexers
public void LoadFromSavedConfiguration(JToken jsonConfig)
{
// The old config used an array - just fail to load it
if (!(jsonConfig["cookies"] is JArray))
{
cookieHeader = (string)jsonConfig["cookies"];
IsConfigured = true;
}
cookieHeader = (string)jsonConfig["cookie_header"];
IsConfigured = true;
}
private void FillReleaseInfoFromJson(ReleaseInfo release, JObject r)
@ -138,7 +133,7 @@ namespace Jackett.Indexers
break;
}
catch (Exception e){
logger.Error(e, "Error checking for results from MoreThanTv.");
logger.Error("On attempt " + (i+1) + " checking for results from MoreThanTv: " + e.Message );
}
}

View file

@ -272,6 +272,7 @@
<Content Include="Content\logos\animebytes.png">
<CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
</Content>
<Content Include="Content\logos\BakaBT.png" />
<Content Include="Content\logos\bb.png">
<CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
</Content>

View file

@ -24,14 +24,17 @@ namespace Jackett
if (Startup.CurlSafe)
{
builder.RegisterType<UnixSafeCurlWebClient>().As<IWebClient>();
Console.WriteLine("Using UnixSafeCurlWebClient");
}
else if(System.Environment.OSVersion.Platform == PlatformID.Unix)
{
builder.RegisterType<UnixLibCurlWebClient>().As<IWebClient>();
Console.WriteLine("Using UnixLibCurlWebClient");
}
else
{
builder.RegisterType<WindowsWebClient>().As<IWebClient>();
Console.WriteLine("Using WindowsWebClient");
}
// Register indexers

View file

@ -1,4 +1,5 @@
using Newtonsoft.Json.Linq;
using Jackett.Utils;
using Newtonsoft.Json.Linq;
using NLog;
using System;
using System.Collections.Generic;
@ -6,6 +7,8 @@ using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Security.AccessControl;
using System.Security.Principal;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
@ -22,27 +25,37 @@ namespace Jackett.Services
T GetConfig<T>();
void SaveConfig<T>(T config);
string ApplicationFolder();
void CreateOrMigrateSettings();
void PerformMigration();
}
public class ConfigurationService : IConfigurationService
{
private ISerializeService serializeService;
private Logger logger;
private IProcessService processService;
public ConfigurationService(ISerializeService s, Logger l)
public ConfigurationService(ISerializeService s, IProcessService p, Logger l)
{
serializeService = s;
logger = l;
processService = p;
CreateOrMigrateSettings();
}
private void CreateOrMigrateSettings()
public void CreateOrMigrateSettings()
{
try
{
if (!Directory.Exists(GetAppDataFolder()))
{
Directory.CreateDirectory(GetAppDataFolder());
var dir = Directory.CreateDirectory(GetAppDataFolder());
if (System.Environment.OSVersion.Platform != PlatformID.Unix)
{
var access = dir.GetAccessControl();
access.AddAccessRule(new FileSystemAccessRule(new SecurityIdentifier(WellKnownSidType.WorldSid, null), FileSystemRights.FullControl, InheritanceFlags.ObjectInherit | InheritanceFlags.ContainerInherit, PropagationFlags.None, AccessControlType.Allow));
Directory.SetAccessControl(GetAppDataFolder(), access);
}
}
logger.Debug("App config/log directory: " + GetAppDataFolder());
@ -52,30 +65,76 @@ namespace Jackett.Services
throw new Exception("Could not create settings directory. " + ex.Message);
}
try
if (System.Environment.OSVersion.Platform != PlatformID.Unix)
{
string oldDir = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), "Jackett");
if (Directory.Exists(oldDir))
try
{
foreach (var file in Directory.GetFiles(oldDir, "*", SearchOption.AllDirectories))
string oldDir = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), "Jackett");
if (Directory.Exists(oldDir))
{
var path = file.Replace(oldDir, "");
var destFolder = GetAppDataFolder() + path;
if (!Directory.Exists(Path.GetDirectoryName(destFolder)))
// On Windows we need admin permissions to migrate as they were made with admin permissions.
if (ServerUtil.IsUserAdministrator())
{
Directory.CreateDirectory(Path.GetDirectoryName(destFolder));
PerformMigration();
}
if (!File.Exists(destFolder))
else
{
File.Move(file, destFolder);
try
{
processService.StartProcessAndLog(Application.ExecutablePath, "--MigrateSettings", true);
}
catch
{
Engine.Logger.Error("Unable to migrate settings when not running as administrator.");
Environment.ExitCode = 1;
return;
}
}
}
Directory.Delete(oldDir, true);
else
{
PerformMigration();
}
}
catch (Exception ex)
{
logger.Error("ERROR could not migrate settings directory " + ex);
}
}
catch (Exception ex)
}
public void PerformMigration()
{
var oldDir = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), "Jackett");
if (Directory.Exists(oldDir))
{
logger.Error("ERROR could not migrate settings directory " + ex);
foreach (var file in Directory.GetFiles(oldDir, "*", SearchOption.AllDirectories))
{
var path = file.Replace(oldDir, "");
var destPath = GetAppDataFolder() + path;
var destFolder = Path.GetDirectoryName(destPath);
if (!Directory.Exists(destFolder))
{
var dir = Directory.CreateDirectory(destFolder);
var access = dir.GetAccessControl();
access.AddAccessRule(new FileSystemAccessRule(new SecurityIdentifier(WellKnownSidType.WorldSid, null), FileSystemRights.FullControl, InheritanceFlags.ObjectInherit | InheritanceFlags.ContainerInherit, PropagationFlags.None, AccessControlType.Allow));
Directory.SetAccessControl(destFolder, access);
}
if (!File.Exists(destPath))
{
File.Copy(file, destPath);
// The old files were created when running as admin so make sure they are editable by normal users / services.
if (System.Environment.OSVersion.Platform != PlatformID.Unix)
{
var access = File.GetAccessControl(destPath);
access.AddAccessRule(new FileSystemAccessRule(new SecurityIdentifier(WellKnownSidType.WorldSid, null), FileSystemRights.FullControl, InheritanceFlags.None, PropagationFlags.None, AccessControlType.Allow));
File.SetAccessControl(destPath, access);
}
}
}
Directory.Delete(oldDir, true);
}
}

View file

@ -44,7 +44,7 @@ namespace Jackett.Services
startInfo.RedirectStandardOutput = false;
startInfo.RedirectStandardInput = false;
}
logger.Debug("Running " + startInfo.FileName + " " + startInfo.Arguments);
var proc = Process.Start(startInfo);
if (!asAdmin)

View file

@ -103,6 +103,7 @@ namespace Jackett.Services
public void Initalize()
{
logger.Info("Starting Jackett " + configService.GetVersion());
CultureInfo.DefaultThreadCurrentCulture = new CultureInfo("en-US");
// Allow all SSL.. sucks I know but mono on linux is having problems without it..
@ -130,7 +131,7 @@ namespace Jackett.Services
if (doInstall)
{
logger.Debug("Reserving Urls");
config.GetListenAddresses(true).ToList().ForEach(u => RunNetSh(string.Format("http add urlacl {0} sddl=D:(A;;GX;;;S-1-1-0)", u)));
config.GetListenAddresses(config.AllowExternal).ToList().ForEach(u => RunNetSh(string.Format("http add urlacl {0} sddl=D:(A;;GX;;;S-1-1-0)", u)));
logger.Debug("Urls reserved");
}
}

View file

@ -72,7 +72,7 @@ namespace Jackett.Utils.Clients
string stdout = null;
await Task.Run(() =>
{
stdout = processService.StartProcessAndGetOutput(@"C:\Apps\curl.exe", args.ToString(), true);
stdout = processService.StartProcessAndGetOutput(System.Environment.OSVersion.Platform == PlatformID.Unix?"curl":"curl.exe", args.ToString(), true);
});
var outputData = File.ReadAllBytes(tempFile);
@ -126,6 +126,7 @@ namespace Jackett.Utils.Clients
dest++;
}
logger.Debug("WebClientByteResult returned " + result.Status);
return result;
}
}