Merge fixes from develop

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

View File

@@ -1,5 +1,6 @@
rmdir /s /q build rmdir /s /q build
rmdir /s /q Output
cd src cd src
Msbuild Jackett.sln /t:Clean,Build /p:Configuration=Release Msbuild Jackett.sln /t:Clean,Build /p:Configuration=Release
cd .. 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.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 build\JackettTray.exe
copy /Y src\Jackett.Tray\bin\Release\JackettTray.exe.config build\JackettTray.exe.config 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 cd build
del *.pdb del *.pdb
del *.xml 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 Filename: "{app}\{#MyAppExeName}"; Description: "{cm:LaunchProgram,{#StringChange(MyAppName, '&', '&&')}}"; Flags: nowait postinstall skipifsilent
[Run] [Run]
Filename: "{app}\JackettConsole.exe"; Parameters: "/u"; Flags: waituntilterminated; Filename: "{app}\JackettConsole.exe"; Parameters: "--Uninstall"; Flags: waituntilterminated;
Filename: "{app}\JackettConsole.exe"; Parameters: "/r"; Flags: waituntilterminated; Filename: "{app}\JackettConsole.exe"; Parameters: "--ReserveUrls"; Flags: waituntilterminated;
Filename: "{app}\JackettConsole.exe"; Parameters: "/i"; Flags: waituntilterminated; Tasks: windowsService Filename: "{app}\JackettConsole.exe"; Parameters: "--MigrateSettings"; Flags: waituntilterminated;
Filename: "{app}\JackettConsole.exe"; Parameters: "/start"; Flags: waituntilterminated; Tasks: windowsService Filename: "{app}\JackettConsole.exe"; Parameters: "--Install"; Flags: waituntilterminated; Tasks: windowsService
Filename: "{app}\JackettConsole.exe"; Parameters: "--Start"; Flags: waituntilterminated; Tasks: windowsService
[UninstallRun] [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> </NuGetPackageImportStamp>
</PropertyGroup> </PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' "> <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' ">
<PlatformTarget>AnyCPU</PlatformTarget> <PlatformTarget>x64</PlatformTarget>
<DebugSymbols>true</DebugSymbols> <DebugSymbols>true</DebugSymbols>
<DebugType>full</DebugType> <DebugType>full</DebugType>
<Optimize>false</Optimize> <Optimize>false</Optimize>
@@ -55,6 +55,10 @@
<Reference Include="Autofac.Integration.WebApi.Owin"> <Reference Include="Autofac.Integration.WebApi.Owin">
<HintPath>..\packages\Autofac.WebApi2.Owin.3.2.0\lib\net45\Autofac.Integration.WebApi.Owin.dll</HintPath> <HintPath>..\packages\Autofac.WebApi2.Owin.3.2.0\lib\net45\Autofac.Integration.WebApi.Owin.dll</HintPath>
</Reference> </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"> <Reference Include="Microsoft.AspNet.Identity.Core">
<HintPath>..\packages\Microsoft.AspNet.Identity.Core.2.2.1\lib\net45\Microsoft.AspNet.Identity.Core.dll</HintPath> <HintPath>..\packages\Microsoft.AspNet.Identity.Core.2.2.1\lib\net45\Microsoft.AspNet.Identity.Core.dll</HintPath>
</Reference> </Reference>
@@ -127,6 +131,7 @@
<Reference Include="System.Xml" /> <Reference Include="System.Xml" />
</ItemGroup> </ItemGroup>
<ItemGroup> <ItemGroup>
<Compile Include="ConsoleOptions.cs" />
<Compile Include="Program.cs" /> <Compile Include="Program.cs" />
<Compile Include="Properties\AssemblyInfo.cs" /> <Compile Include="Properties\AssemblyInfo.cs" />
</ItemGroup> </ItemGroup>

View File

@@ -1,5 +1,9 @@
using Jackett; using CommandLine;
using CommandLine.Text;
using Jackett;
using Jackett.Console;
using Jackett.Indexers; using Jackett.Indexers;
using Jackett.Utils;
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.Diagnostics; using System.Diagnostics;
@@ -18,44 +22,152 @@ namespace JackettConsole
{ {
try 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();
Engine.ServiceConfig.Install(); return;
return; }
case "/r": // Reserve port/url & install
Engine.Server.ReserveUrls(doInstall: true); // Uninstall service
return; if (options.Uninstall)
case "/c": // Change port {
Engine.Server.ReserveUrls(doInstall: false); Engine.Server.ReserveUrls(doInstall: false);
return; Engine.ServiceConfig.Uninstall();
case "/u": // Uninstall return;
Engine.Server.ReserveUrls(doInstall: false); }
Engine.ServiceConfig.Uninstall();
return; // Reserve urls
case "/l": // Logging if (options.ReserveUrls)
Startup.LogRequests = true; {
break; Engine.Server.ReserveUrls(doInstall: true);
case "/t": // Tracing return;
Startup.TracingEnabled = true; }
break;
case "/curlsafe": // Curl safe mode // Start Service
Startup.CurlSafe = true; if (options.StartService)
break; {
case "/start": // Start Service if (!Engine.ServiceConfig.ServiceRunning())
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 Engine.Server.SaveConfig();
if (Engine.ServiceConfig.ServiceRunning()) }
}
// 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.Owin" version="3.1.0" targetFramework="net452" />
<package id="Autofac.WebApi2" version="3.4.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="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.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.Client" version="5.2.3" targetFramework="net452" />
<package id="Microsoft.AspNet.WebApi.Core" 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 try
{ {
Engine.ProcessService.StartProcessAndLog(consolePath, "/stop", true); Engine.ProcessService.StartProcessAndLog(consolePath, "--Stop", true);
} }
catch catch
{ {
@@ -159,7 +159,7 @@ namespace JackettTray
{ {
try try
{ {
Engine.ProcessService.StartProcessAndLog(consolePath, "/start", true); Engine.ProcessService.StartProcessAndLog(consolePath, "--Start", true);
} }
catch catch
{ {

View File

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

View File

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

View File

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

Binary file not shown.

After

Width:  |  Height:  |  Size: 3.7 KiB

View File

@@ -44,12 +44,21 @@ namespace Jackett.Controllers
if (!string.Equals(torznabQuery.ApiKey, serverService.Config.APIKey, StringComparison.InvariantCultureIgnoreCase)) 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"); return Request.CreateResponse(HttpStatusCode.Forbidden, "Incorrect API key");
} }
var releases = await indexer.PerformQuery(torznabQuery); 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 severUrl = string.Format("{0}://{1}:{2}/", Request.RequestUri.Scheme, Request.RequestUri.Host, Request.RequestUri.Port);
var resultPage = new ResultPage(new ChannelInfo var resultPage = new ResultPage(new ChannelInfo

View File

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

View File

@@ -2,6 +2,7 @@
using Jackett.Services; using Jackett.Services;
using NLog; using NLog;
using NLog.Config; using NLog.Config;
using NLog.LayoutRenderers;
using NLog.Targets; using NLog.Targets;
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
@@ -19,7 +20,7 @@ namespace Jackett
static Engine() static Engine()
{ {
BuildContainer(); BuildContainer();
Logger.Info("Starting Jackett " + ConfigService.GetVersion());
} }
public static void BuildContainer() public static void BuildContainer()
@@ -107,8 +108,10 @@ namespace Jackett
private static void SetupLogging(ContainerBuilder builder) 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(); var logFile = new FileTarget();
logConfig.AddTarget("file", logFile); logConfig.AddTarget("file", logFile);
logFile.Layout = "${longdate} ${level} ${message} ${exception:format=ToString}"; logFile.Layout = "${longdate} ${level} ${message} ${exception:format=ToString}";
@@ -121,9 +124,10 @@ namespace Jackett
var logFileRule = new LoggingRule("*", LogLevel.Info, logFile); var logFileRule = new LoggingRule("*", LogLevel.Info, logFile);
logConfig.LoggingRules.Add(logFileRule); logConfig.LoggingRules.Add(logFileRule);
var logConsole = new ConsoleTarget(); var logConsole = new ColoredConsoleTarget();
logConfig.AddTarget("console", logConsole); 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); var logConsoleRule = new LoggingRule("*", Startup.TracingEnabled ? LogLevel.Debug : LogLevel.Info, logConsole);
logConfig.LoggingRules.Add(logConsoleRule); logConfig.LoggingRules.Add(logConsoleRule);
@@ -131,4 +135,13 @@ namespace Jackett
builder.RegisterInstance<Logger>(LogManager.GetCurrentClassLogger()).SingleInstance(); 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 else
{ {
var configSaveData = new JObject(); var configSaveData = new JObject();
configSaveData["cookies"] = cookieHeader; configSaveData["cookie_header"] = cookieHeader;
SaveConfig(configSaveData); SaveConfig(configSaveData);
IsConfigured = true; IsConfigured = true;
} }
@@ -93,7 +93,7 @@ namespace Jackett.Indexers
public void LoadFromSavedConfiguration(JToken jsonConfig) public void LoadFromSavedConfiguration(JToken jsonConfig)
{ {
cookieHeader = (string)jsonConfig["cookies"]; cookieHeader = (string)jsonConfig["cookie_header"];
IsConfigured = true; IsConfigured = true;
} }
@@ -103,12 +103,27 @@ namespace Jackett.Indexers
var searchString = query.SanitizedSearchTerm + " " + query.GetEpisodeSearchString(); var searchString = query.SanitizedSearchTerm + " " + query.GetEpisodeSearchString();
var episodeSearchUrl = SearchUrl + HttpUtility.UrlEncode(searchString); 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, try
Referer = SiteLink.ToString(), {
Cookies = cookieHeader 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; var results = response.Content;
try try

View File

@@ -52,7 +52,6 @@ namespace Jackett.Indexers
{ {
var config = new ConfigurationDataBasicLogin(); var config = new ConfigurationDataBasicLogin();
config.LoadValuesFromJson(configJson); config.LoadValuesFromJson(configJson);
var pairs = new Dictionary<string, string> { var pairs = new Dictionary<string, string> {
{ "username", config.Username.Value }, { "username", config.Username.Value },
{ "password", config.Password.Value }, { "password", config.Password.Value },
@@ -88,7 +87,7 @@ namespace Jackett.Indexers
else else
{ {
var configSaveData = new JObject(); var configSaveData = new JObject();
configSaveData["cookies"] = cookieHeader; configSaveData["cookie_header"] = cookieHeader;
SaveConfig(configSaveData); SaveConfig(configSaveData);
IsConfigured = true; IsConfigured = true;
} }
@@ -96,12 +95,8 @@ namespace Jackett.Indexers
public void LoadFromSavedConfiguration(JToken jsonConfig) public void LoadFromSavedConfiguration(JToken jsonConfig)
{ {
// The old config used an array - just fail to load it cookieHeader = (string)jsonConfig["cookie_header"];
if (!(jsonConfig["cookies"] is JArray)) IsConfigured = true;
{
cookieHeader = (string)jsonConfig["cookies"];
IsConfigured = true;
}
} }
private void FillReleaseInfoFromJson(ReleaseInfo release, JObject r) private void FillReleaseInfoFromJson(ReleaseInfo release, JObject r)
@@ -138,7 +133,7 @@ namespace Jackett.Indexers
break; break;
} }
catch (Exception e){ 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"> <Content Include="Content\logos\animebytes.png">
<CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory> <CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
</Content> </Content>
<Content Include="Content\logos\BakaBT.png" />
<Content Include="Content\logos\bb.png"> <Content Include="Content\logos\bb.png">
<CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory> <CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
</Content> </Content>

View File

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

View File

@@ -1,4 +1,5 @@
using Newtonsoft.Json.Linq; using Jackett.Utils;
using Newtonsoft.Json.Linq;
using NLog; using NLog;
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
@@ -6,6 +7,8 @@ using System.Diagnostics;
using System.IO; using System.IO;
using System.Linq; using System.Linq;
using System.Reflection; using System.Reflection;
using System.Security.AccessControl;
using System.Security.Principal;
using System.Text; using System.Text;
using System.Threading.Tasks; using System.Threading.Tasks;
using System.Windows.Forms; using System.Windows.Forms;
@@ -22,27 +25,37 @@ namespace Jackett.Services
T GetConfig<T>(); T GetConfig<T>();
void SaveConfig<T>(T config); void SaveConfig<T>(T config);
string ApplicationFolder(); string ApplicationFolder();
void CreateOrMigrateSettings();
void PerformMigration();
} }
public class ConfigurationService : IConfigurationService public class ConfigurationService : IConfigurationService
{ {
private ISerializeService serializeService; private ISerializeService serializeService;
private Logger logger; private Logger logger;
private IProcessService processService;
public ConfigurationService(ISerializeService s, Logger l) public ConfigurationService(ISerializeService s, IProcessService p, Logger l)
{ {
serializeService = s; serializeService = s;
logger = l; logger = l;
processService = p;
CreateOrMigrateSettings(); CreateOrMigrateSettings();
} }
private void CreateOrMigrateSettings() public void CreateOrMigrateSettings()
{ {
try try
{ {
if (!Directory.Exists(GetAppDataFolder())) 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()); logger.Debug("App config/log directory: " + GetAppDataFolder());
@@ -52,30 +65,76 @@ namespace Jackett.Services
throw new Exception("Could not create settings directory. " + ex.Message); 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"); try
if (Directory.Exists(oldDir))
{ {
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; // On Windows we need admin permissions to migrate as they were made with admin permissions.
if (!Directory.Exists(Path.GetDirectoryName(destFolder))) 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.RedirectStandardOutput = false;
startInfo.RedirectStandardInput = false; startInfo.RedirectStandardInput = false;
} }
logger.Debug("Running " + startInfo.FileName + " " + startInfo.Arguments);
var proc = Process.Start(startInfo); var proc = Process.Start(startInfo);
if (!asAdmin) if (!asAdmin)

View File

@@ -103,6 +103,7 @@ namespace Jackett.Services
public void Initalize() public void Initalize()
{ {
logger.Info("Starting Jackett " + configService.GetVersion());
CultureInfo.DefaultThreadCurrentCulture = new CultureInfo("en-US"); CultureInfo.DefaultThreadCurrentCulture = new CultureInfo("en-US");
// Allow all SSL.. sucks I know but mono on linux is having problems without it.. // Allow all SSL.. sucks I know but mono on linux is having problems without it..
@@ -130,7 +131,7 @@ namespace Jackett.Services
if (doInstall) if (doInstall)
{ {
logger.Debug("Reserving Urls"); 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"); logger.Debug("Urls reserved");
} }
} }

View File

@@ -72,7 +72,7 @@ namespace Jackett.Utils.Clients
string stdout = null; string stdout = null;
await Task.Run(() => 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); var outputData = File.ReadAllBytes(tempFile);
@@ -126,6 +126,7 @@ namespace Jackett.Utils.Clients
dest++; dest++;
} }
logger.Debug("WebClientByteResult returned " + result.Status);
return result; return result;
} }
} }