mirror of
https://github.com/Radarr/Radarr.git
synced 2026-03-05 13:21:25 -05:00
Compare commits
50 Commits
v5.23.1.99
...
v0.2.0.150
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
b088a2220a | ||
|
|
e29e962bd5 | ||
|
|
62173c5258 | ||
|
|
e3bb4d9b59 | ||
|
|
e973701f1c | ||
|
|
62efca5084 | ||
|
|
f638278f4e | ||
|
|
69811b1291 | ||
|
|
802e5ac151 | ||
|
|
09fe1bfc96 | ||
|
|
1dd0df58ca | ||
|
|
747f4c87d3 | ||
|
|
ac2b9516e1 | ||
|
|
1f72e1de74 | ||
|
|
6b743439eb | ||
|
|
b254ee548d | ||
|
|
d8e0fa6ac2 | ||
|
|
bdb4f490b9 | ||
|
|
588771f3ee | ||
|
|
f0ef6c3601 | ||
|
|
01b0365884 | ||
|
|
e715905ea1 | ||
|
|
5d4ec1272d | ||
|
|
2d40914482 | ||
|
|
420e5fd730 | ||
|
|
b95c2e5c8b | ||
|
|
7ddc8d416c | ||
|
|
6160bbf113 | ||
|
|
a2f666445f | ||
|
|
92d6e81236 | ||
|
|
227101d59e | ||
|
|
080d0a9b04 | ||
|
|
1b58ae7d47 | ||
|
|
a5e2e5777c | ||
|
|
ddc2b42923 | ||
|
|
3ac3737de9 | ||
|
|
01ad015b14 | ||
|
|
3d57d5aba7 | ||
|
|
d65fe3a530 | ||
|
|
e100759e71 | ||
|
|
df068e9f0a | ||
|
|
c27f08738a | ||
|
|
61629a527c | ||
|
|
5291f42905 | ||
|
|
0ce5857094 | ||
|
|
443078a7e4 | ||
|
|
dbdda0da13 | ||
|
|
b5e1b83de3 | ||
|
|
8e43f5c4ae | ||
|
|
e6d3954e79 |
@@ -154,9 +154,9 @@ workflows:
|
||||
- unit_tests:
|
||||
requires:
|
||||
- build
|
||||
#- integration_tests:
|
||||
# requires:
|
||||
# - build
|
||||
- integration_tests:
|
||||
requires:
|
||||
- build
|
||||
- publish_artifacts:
|
||||
requires:
|
||||
- build
|
||||
|
||||
32
.gitignore
vendored
32
.gitignore
vendored
@@ -11,6 +11,7 @@ src/**/[Oo]bj/
|
||||
*.user
|
||||
*.sln.docstates
|
||||
.vs/
|
||||
.vscode/
|
||||
|
||||
# Build results
|
||||
*_i.c
|
||||
@@ -45,6 +46,10 @@ _dotCover*
|
||||
# DevExpress CodeRush
|
||||
src/.cr/
|
||||
|
||||
# Emacs
|
||||
*~
|
||||
\#*\#
|
||||
|
||||
# NCrunch
|
||||
*.ncrunch*
|
||||
.*crunch*.local.xml
|
||||
@@ -80,7 +85,6 @@ TestResults
|
||||
[Tt]est[Rr]esult*
|
||||
*.Cache
|
||||
ClientBin
|
||||
[Ss]tyle[Cc]op.*
|
||||
~$*
|
||||
*.dbmdl
|
||||
Generated_Code #added for RIA/Silverlight projects
|
||||
@@ -102,40 +106,44 @@ _NCrunch_*
|
||||
_TeamCity*
|
||||
|
||||
# Radarr
|
||||
Backups/
|
||||
logs/
|
||||
#MediaCover/
|
||||
UpdateLogs/
|
||||
xdg/
|
||||
config.xml
|
||||
logs.db*
|
||||
nzbdrone.db*
|
||||
nzbdrone.pid
|
||||
nzbdrone.log*txt
|
||||
UpdateLogs/
|
||||
*workspace.xml
|
||||
*.test-cache
|
||||
*.userprefs
|
||||
*/test-results/*
|
||||
src/UI/.idea/*
|
||||
*log.txt
|
||||
node_modules/
|
||||
_output*
|
||||
_artifacts
|
||||
_rawPackage/
|
||||
_dotTrace*
|
||||
_tests/
|
||||
*.Result.xml
|
||||
coverage*.xml
|
||||
coverage*.json
|
||||
setup/Output/
|
||||
*.~is
|
||||
|
||||
UI.Phantom/
|
||||
|
||||
# VS outout folders
|
||||
bin
|
||||
obj
|
||||
output/*
|
||||
|
||||
# .NET Core
|
||||
project.lock.json
|
||||
project.fragment.lock.json
|
||||
artifacts/
|
||||
**/Properties/launchSettings.json
|
||||
|
||||
# Packages
|
||||
Radarr_*/
|
||||
Radarr_*.zip
|
||||
Radarr_*.gz
|
||||
gecko.zip
|
||||
geckodriver.exe
|
||||
|
||||
# macOS metadata files
|
||||
._*
|
||||
@@ -163,6 +171,8 @@ packages.config.md5sum
|
||||
**/.idea/**/tasks.xml
|
||||
**/.idea/shelf/*
|
||||
**/.idea/dictionaries
|
||||
**/.idea/.idea.Radarr.Posix
|
||||
**/.idea/.idea.Radarr.Windows
|
||||
|
||||
# Sensitive or high-churn files
|
||||
**/.idea/**/dataSources/
|
||||
|
||||
9900
package-lock.json
generated
9900
package-lock.json
generated
File diff suppressed because it is too large
Load Diff
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "Radarr",
|
||||
"version": "2.0.0",
|
||||
"name": "radarr",
|
||||
"version": "1.0.0",
|
||||
"description": "Radarr",
|
||||
"main": "main.js",
|
||||
"scripts": {
|
||||
|
||||
@@ -1,648 +0,0 @@
|
||||
using System;
|
||||
using System.Collections.Concurrent;
|
||||
using System.Configuration;
|
||||
using System.Diagnostics;
|
||||
using System.IO;
|
||||
using System.Linq;
|
||||
using System.Security;
|
||||
using System.Text;
|
||||
using System.Text.RegularExpressions;
|
||||
using System.Threading;
|
||||
|
||||
namespace LogentriesCore
|
||||
{
|
||||
public class AsyncLogger
|
||||
{
|
||||
#region Constants
|
||||
|
||||
// Current version number.
|
||||
protected const String Version = "2.6.0";
|
||||
|
||||
// Size of the internal event queue.
|
||||
protected const int QueueSize = 32768;
|
||||
|
||||
// Minimal delay between attempts to reconnect in milliseconds.
|
||||
protected const int MinDelay = 100;
|
||||
|
||||
// Maximal delay between attempts to reconnect in milliseconds.
|
||||
protected const int MaxDelay = 10000;
|
||||
|
||||
// Appender signature - used for debugging messages.
|
||||
protected const String LeSignature = "LE: ";
|
||||
|
||||
// Legacy Logentries configuration names.
|
||||
protected const String LegacyConfigTokenName = "LOGENTRIES_TOKEN";
|
||||
protected const String LegacyConfigAccountKeyName = "LOGENTRIES_ACCOUNT_KEY";
|
||||
protected const String LegacyConfigLocationName = "LOGENTRIES_LOCATION";
|
||||
|
||||
// New Logentries configuration names.
|
||||
protected const String ConfigTokenName = "Logentries.Token";
|
||||
protected const String ConfigAccountKeyName = "Logentries.AccountKey";
|
||||
protected const String ConfigLocationName = "Logentries.Location";
|
||||
|
||||
// Error message displayed when invalid token is detected.
|
||||
protected const String InvalidTokenMessage = "\n\nIt appears your LOGENTRIES_TOKEN value is invalid or missing.\n\n";
|
||||
|
||||
// Error message displayed when invalid account_key or location parameters are detected.
|
||||
protected const String InvalidHttpPutCredentialsMessage = "\n\nIt appears your LOGENTRIES_ACCOUNT_KEY or LOGENTRIES_LOCATION values are invalid or missing.\n\n";
|
||||
|
||||
// Error message deisplayed when queue overflow occurs.
|
||||
protected const String QueueOverflowMessage = "\n\nLogentries buffer queue overflow. Message dropped.\n\n";
|
||||
|
||||
// Newline char to trim from message for formatting.
|
||||
protected static char[] TrimChars = { '\r', '\n' };
|
||||
|
||||
/** Non-Unix and Unix Newline */
|
||||
protected static string[] posix_newline = { "\r\n", "\n" };
|
||||
|
||||
/** Unicode line separator character */
|
||||
protected static string line_separator = "\u2028";
|
||||
|
||||
// Restricted symbols that should not appear in host name.
|
||||
// See http://support.microsoft.com/kb/228275/en-us for details.
|
||||
private static Regex ForbiddenHostNameChars = new Regex(@"[/\\\[\]\""\:\;\|\<\>\+\=\,\?\* _]{1,}", RegexOptions.Compiled);
|
||||
|
||||
/** Regex used to validate GUID in .NET3.5 */
|
||||
private static Regex isGuid = new Regex(@"^(\{){0,1}[0-9a-fA-F]{8}\-[0-9a-fA-F]{4}\-[0-9a-fA-F]{4}\-[0-9a-fA-F]{4}\-[0-9a-fA-F]{12}(\}){0,1}$", RegexOptions.Compiled);
|
||||
|
||||
#endregion
|
||||
|
||||
#region Singletons
|
||||
|
||||
// UTF-8 output character set.
|
||||
protected static readonly UTF8Encoding UTF8 = new UTF8Encoding();
|
||||
|
||||
// ASCII character set used by HTTP.
|
||||
protected static readonly ASCIIEncoding ASCII = new ASCIIEncoding();
|
||||
|
||||
//static list of all the queues the le appender might be managing.
|
||||
private static ConcurrentBag<BlockingCollection<string>> _allQueues = new ConcurrentBag<BlockingCollection<string>>();
|
||||
|
||||
/// <summary>
|
||||
/// Determines if the queue is empty after waiting the specified waitTime.
|
||||
/// Returns true or false if the underlying queues are empty.
|
||||
/// </summary>
|
||||
/// <param name="waitTime">The length of time the method should block before giving up waiting for it to empty.</param>
|
||||
/// <returns>True if the queue is empty, false if there are still items waiting to be written.</returns>
|
||||
public static bool AreAllQueuesEmpty(TimeSpan waitTime)
|
||||
{
|
||||
var start = DateTime.UtcNow;
|
||||
var then = DateTime.UtcNow;
|
||||
|
||||
while (start.Add(waitTime) > then)
|
||||
{
|
||||
if (_allQueues.All(x => x.Count == 0))
|
||||
return true;
|
||||
|
||||
Thread.Sleep(100);
|
||||
then = DateTime.UtcNow;
|
||||
}
|
||||
|
||||
return _allQueues.All(x => x.Count == 0);
|
||||
}
|
||||
#endregion
|
||||
|
||||
public AsyncLogger()
|
||||
{
|
||||
Queue = new BlockingCollection<string>(QueueSize);
|
||||
_allQueues.Add(Queue);
|
||||
|
||||
WorkerThread = new Thread(Run);
|
||||
WorkerThread.Name = "Logentries Log4net Appender";
|
||||
WorkerThread.IsBackground = true;
|
||||
}
|
||||
|
||||
#region Configuration properties
|
||||
|
||||
private String m_Token = "";
|
||||
private String m_AccountKey = "";
|
||||
private String m_Location = "";
|
||||
private bool m_ImmediateFlush = false;
|
||||
private bool m_Debug = false;
|
||||
private bool m_UseHttpPut = false;
|
||||
private bool m_UseSsl = false;
|
||||
|
||||
// Properties for defining location of DataHub instance if one is used.
|
||||
private bool m_UseDataHub = false; // By default Logentries service is used instead of DataHub instance.
|
||||
private String m_DataHubAddr = "";
|
||||
private int m_DataHubPort = 0;
|
||||
|
||||
// Properties to define host name of user's machine and define user-specified log ID.
|
||||
private bool m_UseHostName = false; // Defines whether to prefix log message with HostName or not.
|
||||
private String m_HostName = ""; // User-defined or auto-defined host name (if not set in config. file)
|
||||
private String m_LogID = ""; // User-defined log ID to be prefixed to the log message.
|
||||
|
||||
// Sets DataHub usage flag.
|
||||
public void setIsUsingDataHub(bool useDataHub)
|
||||
{
|
||||
m_UseDataHub = useDataHub;
|
||||
}
|
||||
|
||||
public bool getIsUsingDataHab()
|
||||
{
|
||||
return m_UseDataHub;
|
||||
}
|
||||
|
||||
// Sets DataHub instance address.
|
||||
public void setDataHubAddr(String dataHubAddr)
|
||||
{
|
||||
m_DataHubAddr = dataHubAddr;
|
||||
}
|
||||
|
||||
public String getDataHubAddr()
|
||||
{
|
||||
return m_DataHubAddr;
|
||||
}
|
||||
|
||||
// Sets the port on which DataHub instance is waiting for log messages.
|
||||
public void setDataHubPort(int port)
|
||||
{
|
||||
m_DataHubPort = port;
|
||||
}
|
||||
|
||||
public int getDataHubPort()
|
||||
{
|
||||
return m_DataHubPort;
|
||||
}
|
||||
|
||||
public void setToken(String token)
|
||||
{
|
||||
m_Token = token;
|
||||
}
|
||||
|
||||
public String getToken()
|
||||
{
|
||||
return m_Token;
|
||||
}
|
||||
|
||||
public void setAccountKey(String accountKey)
|
||||
{
|
||||
m_AccountKey = accountKey;
|
||||
}
|
||||
|
||||
public string getAccountKey()
|
||||
{
|
||||
return m_AccountKey;
|
||||
}
|
||||
|
||||
public void setLocation(String location)
|
||||
{
|
||||
m_Location = location;
|
||||
}
|
||||
|
||||
public String getLocation()
|
||||
{
|
||||
return m_Location;
|
||||
}
|
||||
|
||||
public void setImmediateFlush(bool immediateFlush)
|
||||
{
|
||||
m_ImmediateFlush = immediateFlush;
|
||||
}
|
||||
|
||||
public bool getImmediateFlush()
|
||||
{
|
||||
return m_ImmediateFlush;
|
||||
}
|
||||
|
||||
public void setDebug(bool debug)
|
||||
{
|
||||
m_Debug = debug;
|
||||
}
|
||||
|
||||
public bool getDebug()
|
||||
{
|
||||
return m_Debug;
|
||||
}
|
||||
|
||||
public void setUseHttpPut(bool useHttpPut)
|
||||
{
|
||||
m_UseHttpPut = useHttpPut;
|
||||
}
|
||||
|
||||
public bool getUseHttpPut()
|
||||
{
|
||||
return m_UseHttpPut;
|
||||
}
|
||||
|
||||
public void setUseSsl(bool useSsl)
|
||||
{
|
||||
m_UseSsl = useSsl;
|
||||
}
|
||||
|
||||
public bool getUseSsl()
|
||||
{
|
||||
return m_UseSsl;
|
||||
}
|
||||
|
||||
public void setUseHostName(bool useHostName)
|
||||
{
|
||||
m_UseHostName = useHostName;
|
||||
}
|
||||
|
||||
public bool getUseHostName()
|
||||
{
|
||||
return m_UseHostName;
|
||||
}
|
||||
|
||||
public void setHostName(String hostName)
|
||||
{
|
||||
m_HostName = hostName;
|
||||
}
|
||||
|
||||
public String getHostName()
|
||||
{
|
||||
return m_HostName;
|
||||
}
|
||||
|
||||
public void setLogID(String logID)
|
||||
{
|
||||
m_LogID = logID;
|
||||
}
|
||||
|
||||
public String getLogID()
|
||||
{
|
||||
return m_LogID;
|
||||
}
|
||||
|
||||
#endregion
|
||||
|
||||
protected readonly BlockingCollection<string> Queue;
|
||||
protected readonly Thread WorkerThread;
|
||||
protected readonly Random Random = new Random();
|
||||
|
||||
private LeClient LeClient = null;
|
||||
protected bool IsRunning = false;
|
||||
|
||||
#region Protected methods
|
||||
|
||||
protected virtual void Run()
|
||||
{
|
||||
try
|
||||
{
|
||||
// Open connection.
|
||||
ReopenConnection();
|
||||
|
||||
string logMessagePrefix = String.Empty;
|
||||
|
||||
if (m_UseHostName)
|
||||
{
|
||||
// If LogHostName is set to "true", but HostName is not defined -
|
||||
// try to get host name from Environment.
|
||||
if (m_HostName == String.Empty)
|
||||
{
|
||||
try
|
||||
{
|
||||
WriteDebugMessages("HostName parameter is not defined - trying to get it from System.Environment.MachineName");
|
||||
m_HostName = "HostName=" + System.Environment.MachineName + " ";
|
||||
}
|
||||
catch (InvalidOperationException)
|
||||
{
|
||||
// Cannot get host name automatically, so assume that HostName is not used
|
||||
// and log message is sent without it.
|
||||
m_UseHostName = false;
|
||||
WriteDebugMessages("Failed to get HostName parameter using System.Environment.MachineName. Log messages will not be prefixed by HostName");
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
if (!CheckIfHostNameValid(m_HostName))
|
||||
{
|
||||
// If user-defined host name is incorrect - we cannot use it
|
||||
// and log message is sent without it.
|
||||
m_UseHostName = false;
|
||||
WriteDebugMessages("HostName parameter contains prohibited characters. Log messages will not be prefixed by HostName");
|
||||
}
|
||||
else
|
||||
{
|
||||
m_HostName = "HostName=" + m_HostName + " ";
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (m_LogID != String.Empty)
|
||||
{
|
||||
logMessagePrefix = m_LogID + " ";
|
||||
}
|
||||
|
||||
if (m_UseHostName)
|
||||
{
|
||||
logMessagePrefix += m_HostName;
|
||||
}
|
||||
|
||||
// Flag that is set if logMessagePrefix is empty.
|
||||
bool isPrefixEmpty = (logMessagePrefix == String.Empty);
|
||||
|
||||
// Send data in queue.
|
||||
while (true)
|
||||
{
|
||||
// Take data from queue.
|
||||
var line = Queue.Take();
|
||||
|
||||
// Replace newline chars with line separator to format multi-line events nicely.
|
||||
foreach (String newline in posix_newline)
|
||||
{
|
||||
line = line.Replace(newline, line_separator);
|
||||
}
|
||||
|
||||
// If m_UseDataHub == true (logs are sent to DataHub instance) then m_Token is not
|
||||
// appended to the message.
|
||||
string finalLine = ((!m_UseHttpPut && !m_UseDataHub) ? this.m_Token + line : line) + '\n';
|
||||
|
||||
// Add prefixes: LogID and HostName if they are defined.
|
||||
if (!isPrefixEmpty)
|
||||
{
|
||||
finalLine = logMessagePrefix + finalLine;
|
||||
}
|
||||
|
||||
byte[] data = UTF8.GetBytes(finalLine);
|
||||
|
||||
// Send data, reconnect if needed.
|
||||
while (true)
|
||||
{
|
||||
try
|
||||
{
|
||||
this.LeClient.Write(data, 0, data.Length);
|
||||
|
||||
if (m_ImmediateFlush)
|
||||
this.LeClient.Flush();
|
||||
}
|
||||
catch (IOException)
|
||||
{
|
||||
// Reopen the lost connection.
|
||||
ReopenConnection();
|
||||
continue;
|
||||
}
|
||||
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
catch (ThreadInterruptedException ex)
|
||||
{
|
||||
WriteDebugMessages("Logentries asynchronous socket client was interrupted.", ex);
|
||||
}
|
||||
}
|
||||
|
||||
protected virtual void OpenConnection()
|
||||
{
|
||||
try
|
||||
{
|
||||
if (LeClient == null)
|
||||
{
|
||||
// Create LeClient instance providing all needed parameters. If DataHub-related properties
|
||||
// have not been overridden by log4net or NLog configurators, then DataHub is not used,
|
||||
// because m_UseDataHub == false by default.
|
||||
LeClient = new LeClient(m_UseHttpPut, m_UseSsl, m_UseDataHub, m_DataHubAddr, m_DataHubPort);
|
||||
}
|
||||
|
||||
LeClient.Connect();
|
||||
|
||||
if (m_UseHttpPut)
|
||||
{
|
||||
var header = String.Format("PUT /{0}/hosts/{1}/?realtime=1 HTTP/1.1\r\n\r\n", m_AccountKey, m_Location);
|
||||
LeClient.Write(ASCII.GetBytes(header), 0, header.Length);
|
||||
}
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
throw new IOException("An error occurred while opening the connection.", ex);
|
||||
}
|
||||
}
|
||||
|
||||
protected virtual void ReopenConnection()
|
||||
{
|
||||
CloseConnection();
|
||||
|
||||
var rootDelay = MinDelay;
|
||||
while (true)
|
||||
{
|
||||
try
|
||||
{
|
||||
OpenConnection();
|
||||
|
||||
return;
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
if (m_Debug)
|
||||
{
|
||||
WriteDebugMessages("Unable to connect to Logentries API.", ex);
|
||||
}
|
||||
}
|
||||
|
||||
rootDelay *= 2;
|
||||
if (rootDelay > MaxDelay)
|
||||
rootDelay = MaxDelay;
|
||||
|
||||
var waitFor = rootDelay + Random.Next(rootDelay);
|
||||
|
||||
try
|
||||
{
|
||||
Thread.Sleep(waitFor);
|
||||
}
|
||||
catch
|
||||
{
|
||||
throw new ThreadInterruptedException();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
protected virtual void CloseConnection()
|
||||
{
|
||||
if (LeClient != null)
|
||||
LeClient.Close();
|
||||
}
|
||||
|
||||
public static bool IsNullOrWhiteSpace(String value)
|
||||
{
|
||||
if (value == null) return true;
|
||||
|
||||
for (int i = 0; i < value.Length; i++)
|
||||
{
|
||||
if (!Char.IsWhiteSpace(value[i])) return false;
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
private string retrieveSetting(String name)
|
||||
{
|
||||
string value;
|
||||
|
||||
|
||||
value = ConfigurationManager.AppSettings[name];
|
||||
|
||||
if (IsNullOrWhiteSpace(value))
|
||||
{
|
||||
try
|
||||
{
|
||||
value = Environment.GetEnvironmentVariable(name);
|
||||
}
|
||||
catch (SecurityException)
|
||||
{
|
||||
}
|
||||
}
|
||||
|
||||
return value;
|
||||
}
|
||||
|
||||
/*
|
||||
* Use CloudConfigurationManager with .NET4.0 and fallback to System.Configuration for previous frameworks.
|
||||
*
|
||||
* NOTE: This is not entirely clear with regards to the above comment, but this block of code uses a compiler directive NET4_0
|
||||
* which is not set by default anywhere, so most uses of this code will default back to the "pre-.Net4.0" code branch, even
|
||||
* if you are using .Net4.0 or .Net4.5.
|
||||
*
|
||||
* The second issue is that there are two appsetting keys for each setting - the "legacy" key, such as "LOGENTRIES_TOKEN"
|
||||
* and the "non-legacy" key, such as "Logentries.Token". Again, I'm not sure of the reasons behind this, so the code below checks
|
||||
* both the legacy and non-legacy keys, defaulting to the legacy keys if they are found.
|
||||
*
|
||||
* It probably should be investigated whether the fallback to ConfigurationManager is needed at all, as CloudConfigurationManager
|
||||
* will retrieve settings from appSettings in a non-Azure environment.
|
||||
*/
|
||||
protected virtual bool LoadCredentials()
|
||||
{
|
||||
if (!m_UseHttpPut)
|
||||
{
|
||||
if (GetIsValidGuid(m_Token))
|
||||
return true;
|
||||
|
||||
var configToken = retrieveSetting(LegacyConfigTokenName) ?? retrieveSetting(ConfigTokenName);
|
||||
|
||||
if (!String.IsNullOrEmpty(configToken) && GetIsValidGuid(configToken))
|
||||
{
|
||||
m_Token = configToken;
|
||||
return true;
|
||||
}
|
||||
|
||||
WriteDebugMessages(InvalidTokenMessage);
|
||||
return false;
|
||||
}
|
||||
|
||||
if (m_AccountKey != "" && GetIsValidGuid(m_AccountKey) && m_Location != "")
|
||||
return true;
|
||||
|
||||
var configAccountKey = ConfigurationManager.AppSettings[LegacyConfigAccountKeyName] ?? ConfigurationManager.AppSettings[ConfigAccountKeyName];
|
||||
if (!String.IsNullOrEmpty(configAccountKey) && GetIsValidGuid(configAccountKey))
|
||||
{
|
||||
m_AccountKey = configAccountKey;
|
||||
|
||||
var configLocation = ConfigurationManager.AppSettings[LegacyConfigLocationName] ?? ConfigurationManager.AppSettings[ConfigLocationName];
|
||||
if (!String.IsNullOrEmpty(configLocation))
|
||||
{
|
||||
m_Location = configLocation;
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
WriteDebugMessages(InvalidHttpPutCredentialsMessage);
|
||||
return false;
|
||||
}
|
||||
|
||||
private bool CheckIfHostNameValid(String hostName)
|
||||
{
|
||||
return !ForbiddenHostNameChars.IsMatch(hostName); // Returns false if reg.ex. matches any of forbidden chars.
|
||||
}
|
||||
|
||||
static bool IsGuid(string candidate, out Guid output)
|
||||
{
|
||||
bool isValid = false;
|
||||
output = Guid.Empty;
|
||||
|
||||
if (isGuid.IsMatch(candidate))
|
||||
{
|
||||
output = new Guid(candidate);
|
||||
isValid = true;
|
||||
}
|
||||
return isValid;
|
||||
}
|
||||
|
||||
protected virtual bool GetIsValidGuid(string guidString)
|
||||
{
|
||||
if (String.IsNullOrEmpty(guidString))
|
||||
return false;
|
||||
|
||||
System.Guid newGuid = System.Guid.NewGuid();
|
||||
return IsGuid(guidString, out newGuid);
|
||||
}
|
||||
|
||||
protected virtual void WriteDebugMessages(string message, Exception ex)
|
||||
{
|
||||
if (!m_Debug)
|
||||
return;
|
||||
|
||||
message = LeSignature + message;
|
||||
string[] messages = { message, ex.ToString() };
|
||||
foreach (var msg in messages)
|
||||
{
|
||||
// Use below line instead when compiling with log4net1.2.10.
|
||||
//LogLog.Debug(msg);
|
||||
|
||||
//LogLog.Debug(typeof(LogentriesAppender), msg);
|
||||
|
||||
Debug.WriteLine(message);
|
||||
}
|
||||
}
|
||||
|
||||
protected virtual void WriteDebugMessages(string message)
|
||||
{
|
||||
if (!m_Debug)
|
||||
return;
|
||||
|
||||
message = LeSignature + message;
|
||||
|
||||
// Use below line instead when compiling with log4net1.2.10.
|
||||
//LogLog.Debug(message);
|
||||
|
||||
//LogLog.Debug(typeof(LogentriesAppender), message);
|
||||
Debug.WriteLine(message);
|
||||
}
|
||||
|
||||
#endregion
|
||||
|
||||
#region publicMethods
|
||||
|
||||
public virtual void AddLine(string line)
|
||||
{
|
||||
if (!IsRunning)
|
||||
{
|
||||
// We need to load user credentials only
|
||||
// if the configuration does not state that DataHub is used;
|
||||
// credentials needed only if logs are sent to LE service directly.
|
||||
bool credentialsLoaded = false;
|
||||
if(!m_UseDataHub)
|
||||
{
|
||||
credentialsLoaded = LoadCredentials();
|
||||
}
|
||||
|
||||
// If in DataHub mode credentials are ignored.
|
||||
if (credentialsLoaded || m_UseDataHub)
|
||||
{
|
||||
WriteDebugMessages("Starting Logentries asynchronous socket client.");
|
||||
WorkerThread.Start();
|
||||
IsRunning = true;
|
||||
}
|
||||
}
|
||||
|
||||
WriteDebugMessages("Queueing: " + line);
|
||||
|
||||
String trimmedEvent = line.TrimEnd(TrimChars);
|
||||
|
||||
// Try to append data to queue.
|
||||
if (!Queue.TryAdd(trimmedEvent))
|
||||
{
|
||||
Queue.Take();
|
||||
if (!Queue.TryAdd(trimmedEvent))
|
||||
WriteDebugMessages(QueueOverflowMessage);
|
||||
}
|
||||
}
|
||||
|
||||
public void interruptWorker()
|
||||
{
|
||||
WorkerThread.Interrupt();
|
||||
}
|
||||
|
||||
#endregion
|
||||
}
|
||||
}
|
||||
@@ -1,103 +0,0 @@
|
||||
using System;
|
||||
using System.IO;
|
||||
using System.Net.Security;
|
||||
using System.Net.Sockets;
|
||||
|
||||
namespace LogentriesCore
|
||||
{
|
||||
class LeClient
|
||||
{
|
||||
// Logentries API server address.
|
||||
protected const String LeApiUrl = "api.logentries.com";
|
||||
|
||||
// Port number for token logging on Logentries API server.
|
||||
protected const int LeApiTokenPort = 10000;
|
||||
|
||||
// Port number for TLS encrypted token logging on Logentries API server
|
||||
protected const int LeApiTokenTlsPort = 20000;
|
||||
|
||||
// Port number for HTTP PUT logging on Logentries API server.
|
||||
protected const int LeApiHttpPort = 80;
|
||||
|
||||
// Port number for SSL HTTP PUT logging on Logentries API server.
|
||||
protected const int LeApiHttpsPort = 443;
|
||||
|
||||
// Creates LeClient instance. If do not define useServerUrl and/or useOverrideProt during call
|
||||
// LeClient will be configured to work with api.logentries.com server; otherwise - with
|
||||
// defined server on defined port.
|
||||
public LeClient(bool useHttpPut, bool useSsl, bool useDataHub, String serverAddr, int port)
|
||||
{
|
||||
|
||||
// Override port number and server address to send logs to DataHub instance.
|
||||
if (useDataHub)
|
||||
{
|
||||
m_UseSsl = false; // DataHub does not support receiving log messages over SSL for now.
|
||||
m_TcpPort = port;
|
||||
m_ServerAddr = serverAddr;
|
||||
}
|
||||
else
|
||||
{
|
||||
m_UseSsl = useSsl;
|
||||
|
||||
if (!m_UseSsl)
|
||||
m_TcpPort = useHttpPut ? LeApiHttpPort : LeApiTokenPort;
|
||||
else
|
||||
m_TcpPort = useHttpPut ? LeApiHttpsPort : LeApiTokenTlsPort;
|
||||
}
|
||||
}
|
||||
|
||||
private bool m_UseSsl = false;
|
||||
private int m_TcpPort;
|
||||
private TcpClient m_Client = null;
|
||||
private Stream m_Stream = null;
|
||||
private SslStream m_SslStream = null;
|
||||
private String m_ServerAddr = LeApiUrl; // By default m_ServerAddr points to api.logentries.com if useDataHub is not set to true.
|
||||
|
||||
private Stream ActiveStream
|
||||
{
|
||||
get
|
||||
{
|
||||
return m_UseSsl ? m_SslStream : m_Stream;
|
||||
}
|
||||
}
|
||||
|
||||
public void Connect()
|
||||
{
|
||||
m_Client = new TcpClient(m_ServerAddr, m_TcpPort);
|
||||
m_Client.NoDelay = true;
|
||||
|
||||
m_Stream = m_Client.GetStream();
|
||||
|
||||
if (m_UseSsl)
|
||||
{
|
||||
m_SslStream = new SslStream(m_Stream);
|
||||
m_SslStream.AuthenticateAsClient(m_ServerAddr);
|
||||
|
||||
}
|
||||
}
|
||||
|
||||
public void Write(byte[] buffer, int offset, int count)
|
||||
{
|
||||
ActiveStream.Write(buffer, offset, count);
|
||||
}
|
||||
|
||||
public void Flush()
|
||||
{
|
||||
ActiveStream.Flush();
|
||||
}
|
||||
|
||||
public void Close()
|
||||
{
|
||||
if (m_Client != null)
|
||||
{
|
||||
try
|
||||
{
|
||||
m_Client.Close();
|
||||
}
|
||||
catch
|
||||
{
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,83 +0,0 @@
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<Project ToolsVersion="4.0" DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
|
||||
<PropertyGroup>
|
||||
<Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration>
|
||||
<Platform Condition=" '$(Platform)' == '' ">AnyCPU</Platform>
|
||||
<ProductVersion>8.0.30703</ProductVersion>
|
||||
<SchemaVersion>2.0</SchemaVersion>
|
||||
<ProjectGuid>{90D6E9FC-7B88-4E1B-B018-8FA742274558}</ProjectGuid>
|
||||
<OutputType>Library</OutputType>
|
||||
<AppDesignerFolder>Properties</AppDesignerFolder>
|
||||
<RootNamespace>LogentriesCore</RootNamespace>
|
||||
<AssemblyName>LogentriesCore</AssemblyName>
|
||||
<TargetFrameworkVersion>v4.0</TargetFrameworkVersion>
|
||||
<FileAlignment>512</FileAlignment>
|
||||
<SolutionDir Condition="$(SolutionDir) == '' Or $(SolutionDir) == '*Undefined*'">..\</SolutionDir>
|
||||
<RestorePackages>true</RestorePackages>
|
||||
</PropertyGroup>
|
||||
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' ">
|
||||
<DebugSymbols>true</DebugSymbols>
|
||||
<DebugType>full</DebugType>
|
||||
<Optimize>false</Optimize>
|
||||
<OutputPath>bin\Debug\</OutputPath>
|
||||
<DefineConstants>DEBUG;TRACE</DefineConstants>
|
||||
<ErrorReport>prompt</ErrorReport>
|
||||
<WarningLevel>4</WarningLevel>
|
||||
</PropertyGroup>
|
||||
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' ">
|
||||
<DebugType>pdbonly</DebugType>
|
||||
<Optimize>true</Optimize>
|
||||
<OutputPath>bin\Release\</OutputPath>
|
||||
<DefineConstants>TRACE</DefineConstants>
|
||||
<ErrorReport>prompt</ErrorReport>
|
||||
<WarningLevel>4</WarningLevel>
|
||||
</PropertyGroup>
|
||||
<PropertyGroup Condition="'$(Configuration)|$(Platform)' == 'Debug|x86'">
|
||||
<DebugSymbols>true</DebugSymbols>
|
||||
<OutputPath>bin\x86\Debug\</OutputPath>
|
||||
<DefineConstants>DEBUG;TRACE</DefineConstants>
|
||||
<DebugType>full</DebugType>
|
||||
<PlatformTarget>x86</PlatformTarget>
|
||||
<ErrorReport>prompt</ErrorReport>
|
||||
<CodeAnalysisRuleSet>MinimumRecommendedRules.ruleset</CodeAnalysisRuleSet>
|
||||
</PropertyGroup>
|
||||
<PropertyGroup Condition="'$(Configuration)|$(Platform)' == 'Release|x86'">
|
||||
<OutputPath>bin\x86\Release\</OutputPath>
|
||||
<DefineConstants>TRACE</DefineConstants>
|
||||
<Optimize>true</Optimize>
|
||||
<DebugType>pdbonly</DebugType>
|
||||
<PlatformTarget>x86</PlatformTarget>
|
||||
<ErrorReport>prompt</ErrorReport>
|
||||
<CodeAnalysisRuleSet>MinimumRecommendedRules.ruleset</CodeAnalysisRuleSet>
|
||||
</PropertyGroup>
|
||||
<ItemGroup>
|
||||
<Reference Include="System" />
|
||||
<Reference Include="System.configuration" />
|
||||
<Reference Include="System.Core" />
|
||||
<Reference Include="System.Xml.Linq" />
|
||||
<Reference Include="System.Data.DataSetExtensions" />
|
||||
<Reference Include="Microsoft.CSharp" />
|
||||
<Reference Include="System.Data" />
|
||||
<Reference Include="System.Xml" />
|
||||
</ItemGroup>
|
||||
<ItemGroup>
|
||||
<Compile Include="AsyncLogger.cs" />
|
||||
<Compile Include="LeClient.cs" />
|
||||
<Compile Include="Properties\AssemblyInfo.cs" />
|
||||
</ItemGroup>
|
||||
<ItemGroup>
|
||||
<None Include="packages.config" />
|
||||
</ItemGroup>
|
||||
<Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" />
|
||||
<PropertyGroup>
|
||||
<PostBuildEvent>
|
||||
</PostBuildEvent>
|
||||
</PropertyGroup>
|
||||
<!-- To modify your build process, add your task inside one of the targets below and uncomment it.
|
||||
Other similar extension points exist, see Microsoft.Common.targets.
|
||||
<Target Name="BeforeBuild">
|
||||
</Target>
|
||||
<Target Name="AfterBuild">
|
||||
</Target>
|
||||
-->
|
||||
</Project>
|
||||
@@ -1,35 +0,0 @@
|
||||
using System.Reflection;
|
||||
using System.Runtime.InteropServices;
|
||||
|
||||
// General Information about an assembly is controlled through the following
|
||||
// set of attributes. Change these attribute values to modify the information
|
||||
// associated with an assembly.
|
||||
[assembly: AssemblyTitle("LogentriesCore")]
|
||||
[assembly: AssemblyDescription("")]
|
||||
[assembly: AssemblyConfiguration("")]
|
||||
[assembly: AssemblyCompany("")]
|
||||
[assembly: AssemblyProduct("LogentriesCore")]
|
||||
[assembly: AssemblyCopyright("Copyright © 2013")]
|
||||
[assembly: AssemblyTrademark("")]
|
||||
[assembly: AssemblyCulture("")]
|
||||
|
||||
// Setting ComVisible to false makes the types in this assembly not visible
|
||||
// to COM components. If you need to access a type in this assembly from
|
||||
// COM, set the ComVisible attribute to true on that type.
|
||||
[assembly: ComVisible(false)]
|
||||
|
||||
// The following GUID is for the ID of the typelib if this project is exposed to COM
|
||||
[assembly: Guid("14055980-6937-4745-9449-dabf47c1d892")]
|
||||
|
||||
// Version information for an assembly consists of the following four values:
|
||||
//
|
||||
// Major Version
|
||||
// Minor Version
|
||||
// Build Number
|
||||
// Revision
|
||||
//
|
||||
// You can specify all the values or you can default the Build and Revision Numbers
|
||||
// by using the '*' as shown below:
|
||||
// [assembly: AssemblyVersion("1.0.*")]
|
||||
[assembly: AssemblyVersion("2.6.0.0")]
|
||||
[assembly: AssemblyFileVersion("2.6.0.0")]
|
||||
@@ -1,4 +0,0 @@
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<packages>
|
||||
<package id="Microsoft.WindowsAzure.ConfigurationManager" version="2.0.1.0" targetFramework="net40" />
|
||||
</packages>
|
||||
@@ -1,100 +0,0 @@
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<Project ToolsVersion="4.0" DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
|
||||
<PropertyGroup>
|
||||
<Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration>
|
||||
<Platform Condition=" '$(Platform)' == '' ">AnyCPU</Platform>
|
||||
<ProductVersion>8.0.30703</ProductVersion>
|
||||
<SchemaVersion>2.0</SchemaVersion>
|
||||
<ProjectGuid>{9DC31DE3-79FF-47A8-96B4-6BA18F6BB1CB}</ProjectGuid>
|
||||
<OutputType>Library</OutputType>
|
||||
<AppDesignerFolder>Properties</AppDesignerFolder>
|
||||
<RootNamespace>LogentriesNLog</RootNamespace>
|
||||
<AssemblyName>LogentriesNLog</AssemblyName>
|
||||
<TargetFrameworkVersion>v4.0</TargetFrameworkVersion>
|
||||
<FileAlignment>512</FileAlignment>
|
||||
<SolutionDir Condition="$(SolutionDir) == '' Or $(SolutionDir) == '*Undefined*'">..\</SolutionDir>
|
||||
<RestorePackages>true</RestorePackages>
|
||||
</PropertyGroup>
|
||||
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' ">
|
||||
<DebugSymbols>true</DebugSymbols>
|
||||
<DebugType>full</DebugType>
|
||||
<Optimize>false</Optimize>
|
||||
<OutputPath>bin\Debug\</OutputPath>
|
||||
<DefineConstants>DEBUG;TRACE</DefineConstants>
|
||||
<ErrorReport>prompt</ErrorReport>
|
||||
<WarningLevel>4</WarningLevel>
|
||||
</PropertyGroup>
|
||||
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' ">
|
||||
<DebugType>pdbonly</DebugType>
|
||||
<Optimize>true</Optimize>
|
||||
<OutputPath>bin\Release\</OutputPath>
|
||||
<DefineConstants>TRACE</DefineConstants>
|
||||
<ErrorReport>prompt</ErrorReport>
|
||||
<WarningLevel>4</WarningLevel>
|
||||
</PropertyGroup>
|
||||
<PropertyGroup Condition="'$(Configuration)|$(Platform)' == 'Debug|x86'">
|
||||
<DebugSymbols>true</DebugSymbols>
|
||||
<OutputPath>bin\x86\Debug\</OutputPath>
|
||||
<DefineConstants>DEBUG;TRACE</DefineConstants>
|
||||
<DebugType>full</DebugType>
|
||||
<PlatformTarget>x86</PlatformTarget>
|
||||
<ErrorReport>prompt</ErrorReport>
|
||||
<CodeAnalysisRuleSet>MinimumRecommendedRules.ruleset</CodeAnalysisRuleSet>
|
||||
</PropertyGroup>
|
||||
<PropertyGroup Condition="'$(Configuration)|$(Platform)' == 'Release|x86'">
|
||||
<OutputPath>bin\x86\Release\</OutputPath>
|
||||
<DefineConstants>TRACE</DefineConstants>
|
||||
<Optimize>true</Optimize>
|
||||
<DebugType>pdbonly</DebugType>
|
||||
<PlatformTarget>x86</PlatformTarget>
|
||||
<ErrorReport>prompt</ErrorReport>
|
||||
<CodeAnalysisRuleSet>MinimumRecommendedRules.ruleset</CodeAnalysisRuleSet>
|
||||
</PropertyGroup>
|
||||
<ItemGroup>
|
||||
<Reference Include="NLog, Version=4.0.0.0, Culture=neutral, PublicKeyToken=5120e14c03d0593c, processorArchitecture=MSIL">
|
||||
<HintPath>..\packages\NLog.4.5.0-rc06\lib\net40-client\NLog.dll</HintPath>
|
||||
</Reference>
|
||||
<Reference Include="System" />
|
||||
<Reference Include="System.Configuration" />
|
||||
<Reference Include="System.Core" />
|
||||
<Reference Include="System.Runtime.Serialization" />
|
||||
<Reference Include="System.ServiceModel" />
|
||||
<Reference Include="System.Transactions" />
|
||||
<Reference Include="System.Xml.Linq" />
|
||||
<Reference Include="System.Data.DataSetExtensions" />
|
||||
<Reference Include="Microsoft.CSharp" />
|
||||
<Reference Include="System.Data" />
|
||||
<Reference Include="System.Xml" />
|
||||
</ItemGroup>
|
||||
<ItemGroup>
|
||||
<Compile Include="fastJSON\Getters.cs" />
|
||||
<Compile Include="fastJSON\JSON.cs" />
|
||||
<Compile Include="fastJSON\JsonParser.cs" />
|
||||
<Compile Include="fastJSON\JsonSerializer.cs" />
|
||||
<Compile Include="fastJSON\SafeDictionary.cs" />
|
||||
<Compile Include="LogentriesTarget.cs" />
|
||||
<Compile Include="Properties\AssemblyInfo.cs" />
|
||||
</ItemGroup>
|
||||
<ItemGroup>
|
||||
<ProjectReference Include="..\LogentriesCore\LogentriesCore.csproj">
|
||||
<Project>{90D6E9FC-7B88-4E1B-B018-8FA742274558}</Project>
|
||||
<Name>LogentriesCore</Name>
|
||||
</ProjectReference>
|
||||
</ItemGroup>
|
||||
<ItemGroup>
|
||||
<None Include="fastJSON\license.txt" />
|
||||
<None Include="packages.config" />
|
||||
</ItemGroup>
|
||||
<Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" />
|
||||
<PropertyGroup>
|
||||
<PostBuildEvent>
|
||||
</PostBuildEvent>
|
||||
</PropertyGroup>
|
||||
<!-- To modify your build process, add your task inside one of the targets below and uncomment it.
|
||||
Other similar extension points exist, see Microsoft.Common.targets.
|
||||
<Target Name="BeforeBuild">
|
||||
</Target>
|
||||
<Target Name="AfterBuild">
|
||||
</Target>
|
||||
-->
|
||||
</Project>
|
||||
@@ -1,150 +0,0 @@
|
||||
using System;
|
||||
using LogentriesCore;
|
||||
using LogentriesNLog.fastJSON;
|
||||
using NLog;
|
||||
using NLog.Targets;
|
||||
|
||||
namespace LogentriesNLog
|
||||
{
|
||||
[Target("Logentries")]
|
||||
public sealed class LogentriesTarget : TargetWithLayout
|
||||
{
|
||||
private AsyncLogger logentriesAsync;
|
||||
|
||||
public LogentriesTarget()
|
||||
{
|
||||
logentriesAsync = new AsyncLogger();
|
||||
logentriesAsync.setImmediateFlush(true);
|
||||
}
|
||||
|
||||
|
||||
/** Debug flag. */
|
||||
public bool Debug
|
||||
{
|
||||
get { return logentriesAsync.getDebug(); }
|
||||
set { logentriesAsync.setDebug(value); }
|
||||
}
|
||||
|
||||
/** Is using DataHub parameter flag. - ste to true if it is needed to send messages to DataHub instance. */
|
||||
public bool IsUsingDataHub
|
||||
{
|
||||
get { return logentriesAsync.getIsUsingDataHab(); }
|
||||
set { logentriesAsync.setIsUsingDataHub(value); }
|
||||
}
|
||||
|
||||
/** DataHub server address */
|
||||
public String DataHubAddr
|
||||
{
|
||||
get { return logentriesAsync.getDataHubAddr(); }
|
||||
set { logentriesAsync.setDataHubAddr(value); }
|
||||
}
|
||||
|
||||
/** DataHub server port */
|
||||
public int DataHubPort
|
||||
{
|
||||
get { return logentriesAsync.getDataHubPort(); }
|
||||
set { logentriesAsync.setDataHubPort(value); }
|
||||
}
|
||||
|
||||
/** Option to set Token programmatically or in Appender Definition */
|
||||
public string Token
|
||||
{
|
||||
get { return logentriesAsync.getToken(); }
|
||||
set { logentriesAsync.setToken(value); }
|
||||
}
|
||||
|
||||
/** HTTP PUT Flag */
|
||||
public bool HttpPut
|
||||
{
|
||||
get { return logentriesAsync.getUseHttpPut(); }
|
||||
set { logentriesAsync.setUseHttpPut(value); }
|
||||
}
|
||||
|
||||
/** SSL/TLS parameter flag */
|
||||
public bool Ssl
|
||||
{
|
||||
get { return logentriesAsync.getUseSsl(); }
|
||||
set { logentriesAsync.setUseSsl(value); }
|
||||
}
|
||||
|
||||
/** ACCOUNT_KEY parameter for HTTP PUT logging */
|
||||
public String Key
|
||||
{
|
||||
get { return logentriesAsync.getAccountKey(); }
|
||||
set { logentriesAsync.setAccountKey(value); }
|
||||
}
|
||||
|
||||
/** LOCATION parameter for HTTP PUT logging */
|
||||
public String Location
|
||||
{
|
||||
get { return logentriesAsync.getLocation(); }
|
||||
set { logentriesAsync.setLocation(value); }
|
||||
}
|
||||
|
||||
/* LogHostname - switch that defines whether add host name to the log message */
|
||||
public bool LogHostname
|
||||
{
|
||||
get { return logentriesAsync.getUseHostName(); }
|
||||
set { logentriesAsync.setUseHostName(value); }
|
||||
}
|
||||
|
||||
/* HostName - user-defined host name. If empty the library will try to obtain it automatically */
|
||||
public String HostName
|
||||
{
|
||||
get { return logentriesAsync.getHostName(); }
|
||||
set { logentriesAsync.setHostName(value); }
|
||||
}
|
||||
|
||||
/* User-defined log message ID */
|
||||
public String LogID
|
||||
{
|
||||
get { return logentriesAsync.getLogID(); }
|
||||
set { logentriesAsync.setLogID(value); }
|
||||
}
|
||||
|
||||
public bool KeepConnection { get; set; }
|
||||
|
||||
protected override void Write(LogEventInfo logEvent)
|
||||
{
|
||||
//Render message content
|
||||
var log = new Log
|
||||
{
|
||||
Level = logEvent.Level.ToString(),
|
||||
Logger = logEvent.LoggerName,
|
||||
Message = logEvent.FormattedMessage,
|
||||
Time = logEvent.TimeStamp,
|
||||
};
|
||||
|
||||
//NLog can pass null references of Exception
|
||||
if (logEvent.Exception != null)
|
||||
{
|
||||
log.Exception = logEvent.Exception.ToString();
|
||||
log.ExceptionType = logEvent.Exception.GetType().ToString();
|
||||
}
|
||||
|
||||
logentriesAsync.AddLine(JSON.Instance.ToJSON(log));
|
||||
}
|
||||
|
||||
protected override void CloseTarget()
|
||||
{
|
||||
base.CloseTarget();
|
||||
|
||||
logentriesAsync.interruptWorker();
|
||||
}
|
||||
}
|
||||
|
||||
public class Log
|
||||
{
|
||||
public string Message { get; set; }
|
||||
|
||||
public DateTime Time { get; set; }
|
||||
|
||||
public string Logger { get; set; }
|
||||
|
||||
public string Exception { get; set; }
|
||||
|
||||
public string ExceptionType { get; set; }
|
||||
|
||||
public String Level { get; set; }
|
||||
}
|
||||
}
|
||||
@@ -1,35 +0,0 @@
|
||||
using System.Reflection;
|
||||
using System.Runtime.InteropServices;
|
||||
|
||||
// General Information about an assembly is controlled through the following
|
||||
// set of attributes. Change these attribute values to modify the information
|
||||
// associated with an assembly.
|
||||
[assembly: AssemblyTitle("LogentriesNLog")]
|
||||
[assembly: AssemblyDescription("")]
|
||||
[assembly: AssemblyConfiguration("")]
|
||||
[assembly: AssemblyCompany("")]
|
||||
[assembly: AssemblyProduct("LogentriesNLog")]
|
||||
[assembly: AssemblyCopyright("Copyright © 2013")]
|
||||
[assembly: AssemblyTrademark("")]
|
||||
[assembly: AssemblyCulture("")]
|
||||
|
||||
// Setting ComVisible to false makes the types in this assembly not visible
|
||||
// to COM components. If you need to access a type in this assembly from
|
||||
// COM, set the ComVisible attribute to true on that type.
|
||||
[assembly: ComVisible(false)]
|
||||
|
||||
// The following GUID is for the ID of the typelib if this project is exposed to COM
|
||||
[assembly: Guid("7e04ff2d-ea59-4b62-969d-72bd3e37c684")]
|
||||
|
||||
// Version information for an assembly consists of the following four values:
|
||||
//
|
||||
// Major Version
|
||||
// Minor Version
|
||||
// Build Number
|
||||
// Revision
|
||||
//
|
||||
// You can specify all the values or you can default the Build and Revision Numbers
|
||||
// by using the '*' as shown below:
|
||||
// [assembly: AssemblyVersion("1.0.*")]
|
||||
[assembly: AssemblyVersion("2.4.0.0")]
|
||||
[assembly: AssemblyFileVersion("2.4.0.0")]
|
||||
@@ -1,21 +0,0 @@
|
||||
//http://fastjson.codeplex.com/
|
||||
//http://fastjson.codeplex.com/license
|
||||
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
|
||||
namespace LogentriesNLog.fastJSON
|
||||
{
|
||||
internal class Getters
|
||||
{
|
||||
public string Name;
|
||||
public JSON.GenericGetter Getter;
|
||||
public Type propertyType;
|
||||
}
|
||||
|
||||
internal class DatasetSchema
|
||||
{
|
||||
public List<string> Info { get; set; }
|
||||
public string Name { get; set; }
|
||||
}
|
||||
}
|
||||
@@ -1,821 +0,0 @@
|
||||
//http://fastjson.codeplex.com/
|
||||
//http://fastjson.codeplex.com/license
|
||||
|
||||
using System;
|
||||
using System.Collections;
|
||||
using System.Collections.Generic;
|
||||
using System.Data;
|
||||
using System.Globalization;
|
||||
using System.IO;
|
||||
using System.Reflection;
|
||||
using System.Reflection.Emit;
|
||||
using System.Xml.Serialization;
|
||||
|
||||
namespace LogentriesNLog.fastJSON
|
||||
{
|
||||
|
||||
internal class JSON
|
||||
{
|
||||
public readonly static JSON Instance = new JSON();
|
||||
|
||||
private JSON()
|
||||
{
|
||||
UseSerializerExtension = false;
|
||||
SerializeNullValues = false;
|
||||
UseOptimizedDatasetSchema = false;
|
||||
UsingGlobalTypes = false;
|
||||
UseUTCDateTime = true;
|
||||
}
|
||||
public bool UseOptimizedDatasetSchema = true;
|
||||
public bool UseFastGuid = true;
|
||||
public bool UseSerializerExtension = true;
|
||||
public bool IndentOutput = false;
|
||||
public bool SerializeNullValues = true;
|
||||
public bool UseUTCDateTime = false;
|
||||
public bool ShowReadOnlyProperties = false;
|
||||
public bool UsingGlobalTypes = true;
|
||||
|
||||
public string ToJSON(object obj)
|
||||
{
|
||||
return ToJSON(obj, UseSerializerExtension, UseFastGuid, UseOptimizedDatasetSchema, SerializeNullValues);
|
||||
}
|
||||
|
||||
|
||||
public string ToJSON(object obj,
|
||||
bool enableSerializerExtensions,
|
||||
bool enableFastGuid,
|
||||
bool enableOptimizedDatasetSchema,
|
||||
bool serializeNullValues)
|
||||
{
|
||||
return new JSONSerializer(enableOptimizedDatasetSchema, enableFastGuid, enableSerializerExtensions, serializeNullValues, IndentOutput).ConvertToJSON(obj);
|
||||
}
|
||||
|
||||
|
||||
public T ToObject<T>(string json)
|
||||
{
|
||||
return (T)ToObject(json, typeof(T));
|
||||
}
|
||||
|
||||
|
||||
public object ToObject(string json, Type type)
|
||||
{
|
||||
var ht = new JsonParser(json).Decode() as Dictionary<string, object>;
|
||||
if (ht == null) return null;
|
||||
return ParseDictionary(ht, null, type);
|
||||
}
|
||||
|
||||
#if CUSTOMTYPE
|
||||
internal SafeDictionary<Type, Serialize> _customSerializer = new SafeDictionary<Type, Serialize>();
|
||||
internal SafeDictionary<Type, Deserialize> _customDeserializer = new SafeDictionary<Type, Deserialize>();
|
||||
|
||||
public void RegisterCustomType(Type type, Serialize serializer, Deserialize deserializer)
|
||||
{
|
||||
if (type != null && serializer != null && deserializer != null)
|
||||
{
|
||||
_customSerializer.Add(type, serializer);
|
||||
_customDeserializer.Add(type, deserializer);
|
||||
// reset property cache
|
||||
_propertycache = new SafeDictionary<string, SafeDictionary<string, myPropInfo>>();
|
||||
}
|
||||
}
|
||||
|
||||
internal bool IsTypeRegistered(Type t)
|
||||
{
|
||||
Serialize s;
|
||||
return _customSerializer.TryGetValue(t, out s);
|
||||
}
|
||||
#endif
|
||||
|
||||
#region [ PROPERTY GET SET CACHE ]
|
||||
|
||||
readonly SafeDictionary<Type, string> _tyname = new SafeDictionary<Type, string>();
|
||||
internal string GetTypeAssemblyName(Type t)
|
||||
{
|
||||
string val = "";
|
||||
if (_tyname.TryGetValue(t, out val))
|
||||
return val;
|
||||
string s = t.AssemblyQualifiedName;
|
||||
_tyname.Add(t, s);
|
||||
return s;
|
||||
}
|
||||
|
||||
readonly SafeDictionary<string, Type> _typecache = new SafeDictionary<string, Type>();
|
||||
private Type GetTypeFromCache(string typename)
|
||||
{
|
||||
Type val = null;
|
||||
if (_typecache.TryGetValue(typename, out val))
|
||||
return val;
|
||||
Type t = Type.GetType(typename);
|
||||
_typecache.Add(typename, t);
|
||||
return t;
|
||||
}
|
||||
|
||||
readonly SafeDictionary<Type, CreateObject> _constrcache = new SafeDictionary<Type, CreateObject>();
|
||||
private delegate object CreateObject();
|
||||
private object FastCreateInstance(Type objtype)
|
||||
{
|
||||
try
|
||||
{
|
||||
CreateObject c = null;
|
||||
if (_constrcache.TryGetValue(objtype, out c))
|
||||
{
|
||||
return c();
|
||||
}
|
||||
DynamicMethod dynMethod = new DynamicMethod("_", objtype, null, true);
|
||||
ILGenerator ilGen = dynMethod.GetILGenerator();
|
||||
|
||||
ilGen.Emit(OpCodes.Newobj, objtype.GetConstructor(Type.EmptyTypes));
|
||||
ilGen.Emit(OpCodes.Ret);
|
||||
c = (CreateObject)dynMethod.CreateDelegate(typeof(CreateObject));
|
||||
_constrcache.Add(objtype, c);
|
||||
return c();
|
||||
}
|
||||
catch (Exception exc)
|
||||
{
|
||||
throw new Exception(string.Format("Failed to fast create instance for type '{0}' from assemebly '{1}'",
|
||||
objtype.FullName, objtype.AssemblyQualifiedName), exc);
|
||||
}
|
||||
}
|
||||
|
||||
private struct myPropInfo
|
||||
{
|
||||
public bool filled;
|
||||
public Type pt;
|
||||
public Type bt;
|
||||
public Type changeType;
|
||||
public bool isDictionary;
|
||||
public bool isValueType;
|
||||
public bool isGenericType;
|
||||
public bool isArray;
|
||||
public bool isByteArray;
|
||||
public bool isGuid;
|
||||
#if !SILVERLIGHT
|
||||
public bool isDataSet;
|
||||
public bool isDataTable;
|
||||
public bool isHashtable;
|
||||
#endif
|
||||
public GenericSetter setter;
|
||||
public bool isEnum;
|
||||
public bool isDateTime;
|
||||
public Type[] GenericTypes;
|
||||
public bool isInt;
|
||||
public bool isLong;
|
||||
public bool isString;
|
||||
public bool isBool;
|
||||
public bool isClass;
|
||||
public GenericGetter getter;
|
||||
public bool isStringDictionary;
|
||||
public string Name;
|
||||
#if CUSTOMTYPE
|
||||
public bool isCustomType;
|
||||
#endif
|
||||
public bool CanWrite;
|
||||
}
|
||||
|
||||
readonly SafeDictionary<string, SafeDictionary<string, myPropInfo>> _propertycache = new SafeDictionary<string, SafeDictionary<string, myPropInfo>>();
|
||||
private SafeDictionary<string, myPropInfo> Getproperties(Type type, string typename)
|
||||
{
|
||||
SafeDictionary<string, myPropInfo> sd = null;
|
||||
if (_propertycache.TryGetValue(typename, out sd))
|
||||
{
|
||||
return sd;
|
||||
}
|
||||
sd = new SafeDictionary<string, myPropInfo>();
|
||||
var pr = type.GetProperties(BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Instance);
|
||||
foreach (var p in pr)
|
||||
{
|
||||
myPropInfo d = CreateMyProp(p.PropertyType, p.Name);
|
||||
d.CanWrite = p.CanWrite;
|
||||
d.setter = CreateSetMethod(p);
|
||||
d.getter = CreateGetMethod(p);
|
||||
sd.Add(p.Name, d);
|
||||
}
|
||||
|
||||
_propertycache.Add(typename, sd);
|
||||
return sd;
|
||||
}
|
||||
|
||||
private myPropInfo CreateMyProp(Type t, string name)
|
||||
{
|
||||
myPropInfo d = new myPropInfo();
|
||||
d.filled = true;
|
||||
d.CanWrite = true;
|
||||
d.pt = t;
|
||||
d.Name = name;
|
||||
d.isDictionary = t.Name.Contains("Dictionary");
|
||||
if (d.isDictionary)
|
||||
d.GenericTypes = t.GetGenericArguments();
|
||||
d.isValueType = t.IsValueType;
|
||||
d.isGenericType = t.IsGenericType;
|
||||
d.isArray = t.IsArray;
|
||||
if (d.isArray)
|
||||
d.bt = t.GetElementType();
|
||||
if (d.isGenericType)
|
||||
d.bt = t.GetGenericArguments()[0];
|
||||
d.isByteArray = t == typeof(byte[]);
|
||||
d.isGuid = (t == typeof(Guid) || t == typeof(Guid?));
|
||||
#if !SILVERLIGHT
|
||||
d.isHashtable = t == typeof(Hashtable);
|
||||
d.isDataSet = t == typeof(DataSet);
|
||||
d.isDataTable = t == typeof(DataTable);
|
||||
#endif
|
||||
|
||||
d.changeType = GetChangeType(t);
|
||||
d.isEnum = t.IsEnum;
|
||||
d.isDateTime = t == typeof(DateTime) || t == typeof(DateTime?);
|
||||
d.isInt = t == typeof(int) || t == typeof(int?);
|
||||
d.isLong = t == typeof(long) || t == typeof(long?);
|
||||
d.isString = t == typeof(string);
|
||||
d.isBool = t == typeof(bool) || t == typeof(bool?);
|
||||
d.isClass = t.IsClass;
|
||||
|
||||
if (d.isDictionary && d.GenericTypes.Length > 0 && d.GenericTypes[0] == typeof(string))
|
||||
d.isStringDictionary = true;
|
||||
|
||||
#if CUSTOMTYPE
|
||||
if (IsTypeRegistered(t))
|
||||
d.isCustomType = true;
|
||||
#endif
|
||||
return d;
|
||||
}
|
||||
|
||||
private delegate void GenericSetter(object target, object value);
|
||||
|
||||
private static GenericSetter CreateSetMethod(PropertyInfo propertyInfo)
|
||||
{
|
||||
MethodInfo setMethod = propertyInfo.GetSetMethod(nonPublic: true);
|
||||
if (setMethod == null)
|
||||
return null;
|
||||
|
||||
var arguments = new Type[2];
|
||||
arguments[0] = arguments[1] = typeof(object);
|
||||
|
||||
DynamicMethod setter = new DynamicMethod("_", typeof(void), arguments, true);
|
||||
ILGenerator il = setter.GetILGenerator();
|
||||
il.Emit(OpCodes.Ldarg_0);
|
||||
il.Emit(OpCodes.Castclass, propertyInfo.DeclaringType);
|
||||
il.Emit(OpCodes.Ldarg_1);
|
||||
|
||||
if (propertyInfo.PropertyType.IsClass)
|
||||
il.Emit(OpCodes.Castclass, propertyInfo.PropertyType);
|
||||
else
|
||||
il.Emit(OpCodes.Unbox_Any, propertyInfo.PropertyType);
|
||||
|
||||
il.EmitCall(OpCodes.Callvirt, setMethod, null);
|
||||
il.Emit(OpCodes.Ret);
|
||||
|
||||
return (GenericSetter)setter.CreateDelegate(typeof(GenericSetter));
|
||||
}
|
||||
|
||||
internal delegate object GenericGetter(object obj);
|
||||
|
||||
|
||||
private GenericGetter CreateGetMethod(PropertyInfo propertyInfo)
|
||||
{
|
||||
MethodInfo getMethod = propertyInfo.GetGetMethod();
|
||||
if (getMethod == null)
|
||||
return null;
|
||||
|
||||
var arguments = new Type[1];
|
||||
arguments[0] = typeof(object);
|
||||
|
||||
DynamicMethod getter = new DynamicMethod("_", typeof(object), arguments, true);
|
||||
ILGenerator il = getter.GetILGenerator();
|
||||
il.Emit(OpCodes.Ldarg_0);
|
||||
il.Emit(OpCodes.Castclass, propertyInfo.DeclaringType);
|
||||
il.EmitCall(OpCodes.Callvirt, getMethod, null);
|
||||
|
||||
if (!propertyInfo.PropertyType.IsClass)
|
||||
il.Emit(OpCodes.Box, propertyInfo.PropertyType);
|
||||
|
||||
il.Emit(OpCodes.Ret);
|
||||
|
||||
return (GenericGetter)getter.CreateDelegate(typeof(GenericGetter));
|
||||
}
|
||||
|
||||
readonly SafeDictionary<Type, List<Getters>> _getterscache = new SafeDictionary<Type, List<Getters>>();
|
||||
internal List<Getters> GetGetters(Type type)
|
||||
{
|
||||
List<Getters> val = null;
|
||||
if (_getterscache.TryGetValue(type, out val))
|
||||
return val;
|
||||
|
||||
var props = type.GetProperties(BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Instance);
|
||||
var getters = new List<Getters>();
|
||||
foreach (var p in props)
|
||||
{
|
||||
if (!p.CanWrite && ShowReadOnlyProperties == false) continue;
|
||||
|
||||
var att = p.GetCustomAttributes(typeof(XmlIgnoreAttribute), false);
|
||||
if (att != null && att.Length > 0)
|
||||
continue;
|
||||
|
||||
GenericGetter g = CreateGetMethod(p);
|
||||
if (g != null)
|
||||
{
|
||||
Getters gg = new Getters();
|
||||
gg.Name = p.Name;
|
||||
gg.Getter = g;
|
||||
gg.propertyType = p.PropertyType;
|
||||
getters.Add(gg);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
_getterscache.Add(type, getters);
|
||||
return getters;
|
||||
}
|
||||
|
||||
private object ChangeType(object value, Type conversionType)
|
||||
{
|
||||
if (conversionType == typeof(int))
|
||||
return (int)CreateLong((string)value);
|
||||
|
||||
if (conversionType == typeof(long))
|
||||
return CreateLong((string)value);
|
||||
|
||||
if (conversionType == typeof(string))
|
||||
return value;
|
||||
|
||||
if (conversionType == typeof(Guid))
|
||||
return CreateGuid((string)value);
|
||||
|
||||
if (conversionType.IsEnum)
|
||||
return CreateEnum(conversionType, (string)value);
|
||||
|
||||
return Convert.ChangeType(value, conversionType, CultureInfo.InvariantCulture);
|
||||
}
|
||||
#endregion
|
||||
|
||||
|
||||
private object ParseDictionary(Dictionary<string, object> d, Dictionary<string, object> globaltypes, Type type)
|
||||
{
|
||||
object tn = "";
|
||||
if (d.TryGetValue("$types", out tn))
|
||||
{
|
||||
UsingGlobalTypes = true;
|
||||
globaltypes = new Dictionary<string, object>();
|
||||
foreach (var kv in (Dictionary<string, object>)tn)
|
||||
{
|
||||
globaltypes.Add((string)kv.Value, kv.Key);
|
||||
}
|
||||
}
|
||||
|
||||
bool found = d.TryGetValue("$type", out tn);
|
||||
#if !SILVERLIGHT
|
||||
if (found == false && type == typeof(Object))
|
||||
{
|
||||
return CreateDataset(d, globaltypes);
|
||||
}
|
||||
#endif
|
||||
if (found)
|
||||
{
|
||||
if (UsingGlobalTypes)
|
||||
{
|
||||
object tname = "";
|
||||
if (globaltypes.TryGetValue((string)tn, out tname))
|
||||
tn = tname;
|
||||
}
|
||||
type = GetTypeFromCache((string)tn);
|
||||
}
|
||||
|
||||
if (type == null)
|
||||
throw new Exception("Cannot determine type");
|
||||
|
||||
string typename = type.FullName;
|
||||
object o = FastCreateInstance(type);
|
||||
var props = Getproperties(type, typename);
|
||||
foreach (var name in d.Keys)
|
||||
{
|
||||
if (name == "$map")
|
||||
{
|
||||
ProcessMap(o, props, (Dictionary<string, object>)d[name]);
|
||||
continue;
|
||||
}
|
||||
myPropInfo pi;
|
||||
if (props.TryGetValue(name, out pi) == false)
|
||||
continue;
|
||||
if (pi.filled)
|
||||
{
|
||||
object v = d[name];
|
||||
|
||||
if (v != null)
|
||||
{
|
||||
object oset = null;
|
||||
|
||||
if (pi.isInt)
|
||||
oset = (int)CreateLong((string)v);
|
||||
#if CUSTOMTYPE
|
||||
else if (pi.isCustomType)
|
||||
oset = CreateCustom((string)v, pi.pt);
|
||||
#endif
|
||||
else if (pi.isLong)
|
||||
oset = CreateLong((string)v);
|
||||
|
||||
else if (pi.isString)
|
||||
oset = v;
|
||||
|
||||
else if (pi.isBool)
|
||||
oset = (bool)v;
|
||||
|
||||
else if (pi.isGenericType && pi.isValueType == false && pi.isDictionary == false)
|
||||
#if SILVERLIGHT
|
||||
oset = CreateGenericList((List<object>)v, pi.pt, pi.bt, globaltypes);
|
||||
#else
|
||||
oset = CreateGenericList((ArrayList)v, pi.pt, pi.bt, globaltypes);
|
||||
#endif
|
||||
else if (pi.isByteArray)
|
||||
oset = Convert.FromBase64String((string)v);
|
||||
|
||||
else if (pi.isArray && pi.isValueType == false)
|
||||
#if SILVERLIGHT
|
||||
oset = CreateArray((List<object>)v, pi.pt, pi.bt, globaltypes);
|
||||
#else
|
||||
oset = CreateArray((ArrayList)v, pi.pt, pi.bt, globaltypes);
|
||||
#endif
|
||||
else if (pi.isGuid)
|
||||
oset = CreateGuid((string)v);
|
||||
#if !SILVERLIGHT
|
||||
else if (pi.isDataSet)
|
||||
oset = CreateDataset((Dictionary<string, object>)v, globaltypes);
|
||||
|
||||
else if (pi.isDataTable)
|
||||
oset = CreateDataTable((Dictionary<string, object>)v, globaltypes);
|
||||
#endif
|
||||
|
||||
else if (pi.isStringDictionary)
|
||||
oset = CreateStringKeyDictionary((Dictionary<string, object>)v, pi.pt, pi.GenericTypes, globaltypes);
|
||||
|
||||
#if !SILVERLIGHT
|
||||
else if (pi.isDictionary || pi.isHashtable)
|
||||
oset = CreateDictionary((ArrayList)v, pi.pt, pi.GenericTypes, globaltypes);
|
||||
#else
|
||||
else if (pi.isDictionary)
|
||||
oset = CreateDictionary((List<object>)v, pi.pt, pi.GenericTypes, globaltypes);
|
||||
#endif
|
||||
|
||||
else if (pi.isEnum)
|
||||
oset = CreateEnum(pi.pt, (string)v);
|
||||
|
||||
else if (pi.isDateTime)
|
||||
oset = CreateDateTime((string)v);
|
||||
|
||||
else if (pi.isClass && v is Dictionary<string, object>)
|
||||
oset = ParseDictionary((Dictionary<string, object>)v, globaltypes, pi.pt);
|
||||
|
||||
else if (pi.isValueType)
|
||||
oset = ChangeType(v, pi.changeType);
|
||||
|
||||
#if SILVERLIGHT
|
||||
else if (v is List<object>)
|
||||
oset = CreateArray((List<object>)v, pi.pt, typeof(object), globaltypes);
|
||||
#else
|
||||
else if (v is ArrayList)
|
||||
oset = CreateArray((ArrayList)v, pi.pt, typeof(object), globaltypes);
|
||||
#endif
|
||||
else
|
||||
oset = v;
|
||||
|
||||
if (pi.CanWrite)
|
||||
pi.setter(o, oset);
|
||||
}
|
||||
}
|
||||
}
|
||||
return o;
|
||||
}
|
||||
|
||||
#if CUSTOMTYPE
|
||||
private object CreateCustom(string v, Type type)
|
||||
{
|
||||
Deserialize d;
|
||||
_customDeserializer.TryGetValue(type, out d);
|
||||
return d(v);
|
||||
}
|
||||
#endif
|
||||
|
||||
private void ProcessMap(object obj, SafeDictionary<string, myPropInfo> props, Dictionary<string, object> dic)
|
||||
{
|
||||
foreach (var kv in dic)
|
||||
{
|
||||
myPropInfo p = props[kv.Key];
|
||||
object o = p.getter(obj);
|
||||
Type t = Type.GetType((string)kv.Value);
|
||||
if (t == typeof(Guid))
|
||||
p.setter(obj, CreateGuid((string)o));
|
||||
}
|
||||
}
|
||||
|
||||
private long CreateLong(string s)
|
||||
{
|
||||
long num = 0;
|
||||
bool neg = false;
|
||||
foreach (var cc in s)
|
||||
{
|
||||
if (cc == '-')
|
||||
neg = true;
|
||||
else if (cc == '+')
|
||||
neg = false;
|
||||
else
|
||||
{
|
||||
num *= 10;
|
||||
num += (cc - '0');
|
||||
}
|
||||
}
|
||||
|
||||
return neg ? -num : num;
|
||||
}
|
||||
|
||||
private object CreateEnum(Type pt, string v)
|
||||
{
|
||||
// TODO : optimize create enum
|
||||
#if !SILVERLIGHT
|
||||
return Enum.Parse(pt, v);
|
||||
#else
|
||||
return Enum.Parse(pt, v, true);
|
||||
#endif
|
||||
}
|
||||
|
||||
private Guid CreateGuid(string s)
|
||||
{
|
||||
if (s.Length > 30)
|
||||
return new Guid(s);
|
||||
return new Guid(Convert.FromBase64String(s));
|
||||
}
|
||||
|
||||
private DateTime CreateDateTime(string value)
|
||||
{
|
||||
bool utc = false;
|
||||
// 0123456789012345678
|
||||
// datetime format = yyyy-MM-dd HH:mm:ss
|
||||
int year = (int)CreateLong(value.Substring(0, 4));
|
||||
int month = (int)CreateLong(value.Substring(5, 2));
|
||||
int day = (int)CreateLong(value.Substring(8, 2));
|
||||
int hour = (int)CreateLong(value.Substring(11, 2));
|
||||
int min = (int)CreateLong(value.Substring(14, 2));
|
||||
int sec = (int)CreateLong(value.Substring(17, 2));
|
||||
|
||||
if (value.EndsWith("Z"))
|
||||
utc = true;
|
||||
|
||||
if (UseUTCDateTime == false && utc == false)
|
||||
return new DateTime(year, month, day, hour, min, sec);
|
||||
return new DateTime(year, month, day, hour, min, sec, DateTimeKind.Utc).ToLocalTime();
|
||||
}
|
||||
|
||||
#if SILVERLIGHT
|
||||
private object CreateArray(List<object> data, Type pt, Type bt, Dictionary<string, object> globalTypes)
|
||||
{
|
||||
Array col = Array.CreateInstance(bt, data.Count);
|
||||
// create an array of objects
|
||||
for (int i = 0; i < data.Count; i++)// each (object ob in data)
|
||||
{
|
||||
object ob = data[i];
|
||||
if (ob is IDictionary)
|
||||
col.SetValue(ParseDictionary((Dictionary<string, object>)ob, globalTypes, bt), i);
|
||||
else
|
||||
col.SetValue(ChangeType(ob, bt), i);
|
||||
}
|
||||
|
||||
return col;
|
||||
}
|
||||
#else
|
||||
private object CreateArray(ArrayList data, Type pt, Type bt, Dictionary<string, object> globalTypes)
|
||||
{
|
||||
ArrayList col = new ArrayList();
|
||||
// create an array of objects
|
||||
foreach (var ob in data)
|
||||
{
|
||||
if (ob is IDictionary)
|
||||
col.Add(ParseDictionary((Dictionary<string, object>)ob, globalTypes, bt));
|
||||
else
|
||||
col.Add(ChangeType(ob, bt));
|
||||
}
|
||||
return col.ToArray(bt);
|
||||
}
|
||||
#endif
|
||||
|
||||
|
||||
#if SILVERLIGHT
|
||||
private object CreateGenericList(List<object> data, Type pt, Type bt, Dictionary<string, object> globalTypes)
|
||||
#else
|
||||
private object CreateGenericList(ArrayList data, Type pt, Type bt, Dictionary<string, object> globalTypes)
|
||||
#endif
|
||||
{
|
||||
IList col = (IList)FastCreateInstance(pt);
|
||||
// create an array of objects
|
||||
foreach (var ob in data)
|
||||
{
|
||||
if (ob is IDictionary)
|
||||
col.Add(ParseDictionary((Dictionary<string, object>)ob, globalTypes, bt));
|
||||
#if SILVERLIGHT
|
||||
else if (ob is List<object>)
|
||||
col.Add(((List<object>)ob).ToArray());
|
||||
#else
|
||||
else if (ob is ArrayList)
|
||||
col.Add(((ArrayList)ob).ToArray());
|
||||
#endif
|
||||
else
|
||||
col.Add(ChangeType(ob, bt));
|
||||
}
|
||||
return col;
|
||||
}
|
||||
|
||||
private object CreateStringKeyDictionary(Dictionary<string, object> reader, Type pt, Type[] types, Dictionary<string, object> globalTypes)
|
||||
{
|
||||
var col = (IDictionary)FastCreateInstance(pt);
|
||||
Type t1 = null;
|
||||
Type t2 = null;
|
||||
if (types != null)
|
||||
{
|
||||
t1 = types[0];
|
||||
t2 = types[1];
|
||||
}
|
||||
|
||||
foreach (var values in reader)
|
||||
{
|
||||
var key = values.Key;//ChangeType(values.Key, t1);
|
||||
object val = null;
|
||||
if (values.Value is Dictionary<string, object>)
|
||||
val = ParseDictionary((Dictionary<string, object>)values.Value, globalTypes, t2);
|
||||
else
|
||||
val = ChangeType(values.Value, t2);
|
||||
col.Add(key, val);
|
||||
}
|
||||
|
||||
return col;
|
||||
}
|
||||
|
||||
#if SILVERLIGHT
|
||||
private object CreateDictionary(List<object> reader, Type pt, Type[] types, Dictionary<string, object> globalTypes)
|
||||
#else
|
||||
private object CreateDictionary(ArrayList reader, Type pt, Type[] types, Dictionary<string, object> globalTypes)
|
||||
#endif
|
||||
{
|
||||
IDictionary col = (IDictionary)FastCreateInstance(pt);
|
||||
Type t1 = null;
|
||||
Type t2 = null;
|
||||
if (types != null)
|
||||
{
|
||||
t1 = types[0];
|
||||
t2 = types[1];
|
||||
}
|
||||
|
||||
foreach (Dictionary<string, object> values in reader)
|
||||
{
|
||||
object key = values["k"];
|
||||
object val = values["v"];
|
||||
|
||||
if (key is Dictionary<string, object>)
|
||||
key = ParseDictionary((Dictionary<string, object>)key, globalTypes, t1);
|
||||
else
|
||||
key = ChangeType(key, t1);
|
||||
|
||||
if (val is Dictionary<string, object>)
|
||||
val = ParseDictionary((Dictionary<string, object>)val, globalTypes, t2);
|
||||
else
|
||||
val = ChangeType(val, t2);
|
||||
|
||||
col.Add(key, val);
|
||||
}
|
||||
|
||||
return col;
|
||||
}
|
||||
|
||||
private Type GetChangeType(Type conversionType)
|
||||
{
|
||||
if (conversionType.IsGenericType && conversionType.GetGenericTypeDefinition().Equals(typeof(Nullable<>)))
|
||||
return conversionType.GetGenericArguments()[0];
|
||||
|
||||
return conversionType;
|
||||
}
|
||||
#if !SILVERLIGHT
|
||||
private DataSet CreateDataset(Dictionary<string, object> reader, Dictionary<string, object> globalTypes)
|
||||
{
|
||||
DataSet ds = new DataSet();
|
||||
ds.EnforceConstraints = false;
|
||||
ds.BeginInit();
|
||||
|
||||
// read dataset schema here
|
||||
ReadSchema(reader, ds, globalTypes);
|
||||
|
||||
foreach (var pair in reader)
|
||||
{
|
||||
if (pair.Key == "$type" || pair.Key == "$schema") continue;
|
||||
|
||||
ArrayList rows = (ArrayList)pair.Value;
|
||||
if (rows == null) continue;
|
||||
|
||||
DataTable dt = ds.Tables[pair.Key];
|
||||
ReadDataTable(rows, dt);
|
||||
}
|
||||
|
||||
ds.EndInit();
|
||||
|
||||
return ds;
|
||||
}
|
||||
|
||||
private void ReadSchema(Dictionary<string, object> reader, DataSet ds, Dictionary<string, object> globalTypes)
|
||||
{
|
||||
var schema = reader["$schema"];
|
||||
|
||||
if (schema is string)
|
||||
{
|
||||
TextReader tr = new StringReader((string)schema);
|
||||
ds.ReadXmlSchema(tr);
|
||||
}
|
||||
else
|
||||
{
|
||||
DatasetSchema ms = (DatasetSchema)ParseDictionary((Dictionary<string, object>)schema, globalTypes, typeof(DatasetSchema));
|
||||
ds.DataSetName = ms.Name;
|
||||
for (int i = 0; i < ms.Info.Count; i += 3)
|
||||
{
|
||||
if (ds.Tables.Contains(ms.Info[i]) == false)
|
||||
ds.Tables.Add(ms.Info[i]);
|
||||
ds.Tables[ms.Info[i]].Columns.Add(ms.Info[i + 1], Type.GetType(ms.Info[i + 2]));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private void ReadDataTable(ArrayList rows, DataTable dt)
|
||||
{
|
||||
dt.BeginInit();
|
||||
dt.BeginLoadData();
|
||||
var guidcols = new List<int>();
|
||||
var datecol = new List<int>();
|
||||
|
||||
foreach (DataColumn c in dt.Columns)
|
||||
{
|
||||
if (c.DataType == typeof(Guid) || c.DataType == typeof(Guid?))
|
||||
guidcols.Add(c.Ordinal);
|
||||
if (UseUTCDateTime && (c.DataType == typeof(DateTime) || c.DataType == typeof(DateTime?)))
|
||||
datecol.Add(c.Ordinal);
|
||||
}
|
||||
|
||||
foreach (ArrayList row in rows)
|
||||
{
|
||||
var v = new object[row.Count];
|
||||
row.CopyTo(v, 0);
|
||||
foreach (var i in guidcols)
|
||||
{
|
||||
string s = (string)v[i];
|
||||
if (s != null && s.Length < 36)
|
||||
v[i] = new Guid(Convert.FromBase64String(s));
|
||||
}
|
||||
if (UseUTCDateTime)
|
||||
{
|
||||
foreach (var i in datecol)
|
||||
{
|
||||
string s = (string)v[i];
|
||||
if (s != null)
|
||||
v[i] = CreateDateTime(s);
|
||||
}
|
||||
}
|
||||
dt.Rows.Add(v);
|
||||
}
|
||||
|
||||
dt.EndLoadData();
|
||||
dt.EndInit();
|
||||
}
|
||||
|
||||
DataTable CreateDataTable(Dictionary<string, object> reader, Dictionary<string, object> globalTypes)
|
||||
{
|
||||
var dt = new DataTable();
|
||||
|
||||
// read dataset schema here
|
||||
var schema = reader["$schema"];
|
||||
|
||||
if (schema is string)
|
||||
{
|
||||
TextReader tr = new StringReader((string)schema);
|
||||
dt.ReadXmlSchema(tr);
|
||||
}
|
||||
else
|
||||
{
|
||||
var ms = (DatasetSchema)ParseDictionary((Dictionary<string, object>)schema, globalTypes, typeof(DatasetSchema));
|
||||
dt.TableName = ms.Info[0];
|
||||
for (int i = 0; i < ms.Info.Count; i += 3)
|
||||
{
|
||||
dt.Columns.Add(ms.Info[i + 1], Type.GetType(ms.Info[i + 2]));
|
||||
}
|
||||
}
|
||||
|
||||
foreach (var pair in reader)
|
||||
{
|
||||
if (pair.Key == "$type" || pair.Key == "$schema")
|
||||
continue;
|
||||
|
||||
var rows = (ArrayList)pair.Value;
|
||||
if (rows == null)
|
||||
continue;
|
||||
|
||||
if (!dt.TableName.Equals(pair.Key, StringComparison.InvariantCultureIgnoreCase))
|
||||
continue;
|
||||
|
||||
ReadDataTable(rows, dt);
|
||||
}
|
||||
|
||||
return dt;
|
||||
}
|
||||
#endif
|
||||
}
|
||||
}
|
||||
@@ -1,409 +0,0 @@
|
||||
//http://fastjson.codeplex.com/
|
||||
//http://fastjson.codeplex.com/license
|
||||
|
||||
using System;
|
||||
using System.Collections;
|
||||
using System.Collections.Generic;
|
||||
using System.Text;
|
||||
|
||||
namespace LogentriesNLog.fastJSON
|
||||
{
|
||||
/// <summary>
|
||||
/// This class encodes and decodes JSON strings.
|
||||
/// Spec. details, see http://www.json.org/
|
||||
///
|
||||
/// JSON uses Arrays and Objects. These correspond here to the datatypes ArrayList and Hashtable.
|
||||
/// All numbers are parsed to doubles.
|
||||
/// </summary>
|
||||
internal class JsonParser
|
||||
{
|
||||
enum Token
|
||||
{
|
||||
None = -1, // Used to denote no Lookahead available
|
||||
Curly_Open,
|
||||
Curly_Close,
|
||||
Squared_Open,
|
||||
Squared_Close,
|
||||
Colon,
|
||||
Comma,
|
||||
String,
|
||||
Number,
|
||||
True,
|
||||
False,
|
||||
Null
|
||||
}
|
||||
|
||||
readonly char[] json;
|
||||
readonly StringBuilder s = new StringBuilder();
|
||||
Token lookAheadToken = Token.None;
|
||||
int index;
|
||||
|
||||
internal JsonParser(string json)
|
||||
{
|
||||
this.json = json.ToCharArray();
|
||||
}
|
||||
|
||||
public object Decode()
|
||||
{
|
||||
return ParseValue();
|
||||
}
|
||||
|
||||
private Dictionary<string, object> ParseObject()
|
||||
{
|
||||
var table = new Dictionary<string, object>();
|
||||
|
||||
ConsumeToken(); // {
|
||||
|
||||
while (true)
|
||||
{
|
||||
switch (LookAhead())
|
||||
{
|
||||
|
||||
case Token.Comma:
|
||||
ConsumeToken();
|
||||
break;
|
||||
|
||||
case Token.Curly_Close:
|
||||
ConsumeToken();
|
||||
return table;
|
||||
|
||||
default:
|
||||
{
|
||||
|
||||
// name
|
||||
string name = ParseString();
|
||||
|
||||
// :
|
||||
if (NextToken() != Token.Colon)
|
||||
{
|
||||
throw new Exception("Expected colon at index " + index);
|
||||
}
|
||||
|
||||
// value
|
||||
object value = ParseValue();
|
||||
|
||||
table[name] = value;
|
||||
}
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#if SILVERLIGHT
|
||||
private List<object> ParseArray()
|
||||
{
|
||||
List<object> array = new List<object>();
|
||||
#else
|
||||
private ArrayList ParseArray()
|
||||
{
|
||||
ArrayList array = new ArrayList();
|
||||
#endif
|
||||
ConsumeToken(); // [
|
||||
|
||||
while (true)
|
||||
{
|
||||
switch (LookAhead())
|
||||
{
|
||||
|
||||
case Token.Comma:
|
||||
ConsumeToken();
|
||||
break;
|
||||
|
||||
case Token.Squared_Close:
|
||||
ConsumeToken();
|
||||
return array;
|
||||
|
||||
default:
|
||||
{
|
||||
array.Add(ParseValue());
|
||||
}
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private object ParseValue()
|
||||
{
|
||||
switch (LookAhead())
|
||||
{
|
||||
case Token.Number:
|
||||
return ParseNumber();
|
||||
|
||||
case Token.String:
|
||||
return ParseString();
|
||||
|
||||
case Token.Curly_Open:
|
||||
return ParseObject();
|
||||
|
||||
case Token.Squared_Open:
|
||||
return ParseArray();
|
||||
|
||||
case Token.True:
|
||||
ConsumeToken();
|
||||
return true;
|
||||
|
||||
case Token.False:
|
||||
ConsumeToken();
|
||||
return false;
|
||||
|
||||
case Token.Null:
|
||||
ConsumeToken();
|
||||
return null;
|
||||
}
|
||||
|
||||
throw new Exception("Unrecognized token at index" + index);
|
||||
}
|
||||
|
||||
private string ParseString()
|
||||
{
|
||||
ConsumeToken(); // "
|
||||
|
||||
s.Length = 0;
|
||||
|
||||
int runIndex = -1;
|
||||
|
||||
while (index < json.Length)
|
||||
{
|
||||
var c = json[index++];
|
||||
|
||||
if (c == '"')
|
||||
{
|
||||
if (runIndex != -1)
|
||||
{
|
||||
if (s.Length == 0)
|
||||
return new string(json, runIndex, index - runIndex - 1);
|
||||
|
||||
s.Append(json, runIndex, index - runIndex - 1);
|
||||
}
|
||||
return s.ToString();
|
||||
}
|
||||
|
||||
if (c != '\\')
|
||||
{
|
||||
if (runIndex == -1)
|
||||
runIndex = index - 1;
|
||||
|
||||
continue;
|
||||
}
|
||||
|
||||
if (index == json.Length) break;
|
||||
|
||||
if (runIndex != -1)
|
||||
{
|
||||
s.Append(json, runIndex, index - runIndex - 1);
|
||||
runIndex = -1;
|
||||
}
|
||||
|
||||
switch (json[index++])
|
||||
{
|
||||
case '"':
|
||||
s.Append('"');
|
||||
break;
|
||||
|
||||
case '\\':
|
||||
s.Append('\\');
|
||||
break;
|
||||
|
||||
case '/':
|
||||
s.Append('/');
|
||||
break;
|
||||
|
||||
case 'b':
|
||||
s.Append('\b');
|
||||
break;
|
||||
|
||||
case 'f':
|
||||
s.Append('\f');
|
||||
break;
|
||||
|
||||
case 'n':
|
||||
s.Append('\n');
|
||||
break;
|
||||
|
||||
case 'r':
|
||||
s.Append('\r');
|
||||
break;
|
||||
|
||||
case 't':
|
||||
s.Append('\t');
|
||||
break;
|
||||
|
||||
case 'u':
|
||||
{
|
||||
int remainingLength = json.Length - index;
|
||||
if (remainingLength < 4) break;
|
||||
|
||||
// parse the 32 bit hex into an integer codepoint
|
||||
uint codePoint = ParseUnicode(json[index], json[index + 1], json[index + 2], json[index + 3]);
|
||||
s.Append((char)codePoint);
|
||||
|
||||
// skip 4 chars
|
||||
index += 4;
|
||||
}
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
throw new Exception("Unexpectedly reached end of string");
|
||||
}
|
||||
|
||||
private uint ParseSingleChar(char c1, uint multipliyer)
|
||||
{
|
||||
uint p1 = 0;
|
||||
if (c1 >= '0' && c1 <= '9')
|
||||
p1 = (uint)(c1 - '0') * multipliyer;
|
||||
else if (c1 >= 'A' && c1 <= 'F')
|
||||
p1 = (uint)((c1 - 'A') + 10) * multipliyer;
|
||||
else if (c1 >= 'a' && c1 <= 'f')
|
||||
p1 = (uint)((c1 - 'a') + 10) * multipliyer;
|
||||
return p1;
|
||||
}
|
||||
|
||||
private uint ParseUnicode(char c1, char c2, char c3, char c4)
|
||||
{
|
||||
uint p1 = ParseSingleChar(c1, 0x1000);
|
||||
uint p2 = ParseSingleChar(c2, 0x100);
|
||||
uint p3 = ParseSingleChar(c3, 0x10);
|
||||
uint p4 = ParseSingleChar(c4, 1);
|
||||
|
||||
return p1 + p2 + p3 + p4;
|
||||
}
|
||||
|
||||
private string ParseNumber()
|
||||
{
|
||||
ConsumeToken();
|
||||
|
||||
// Need to start back one place because the first digit is also a token and would have been consumed
|
||||
var startIndex = index - 1;
|
||||
|
||||
do
|
||||
{
|
||||
var c = json[index];
|
||||
|
||||
if ((c >= '0' && c <= '9') || c == '.' || c == '-' || c == '+' || c == 'e' || c == 'E')
|
||||
{
|
||||
if (++index == json.Length) throw new Exception("Unexpected end of string whilst parsing number");
|
||||
continue;
|
||||
}
|
||||
|
||||
break;
|
||||
} while (true);
|
||||
|
||||
return new string(json, startIndex, index - startIndex);
|
||||
}
|
||||
|
||||
private Token LookAhead()
|
||||
{
|
||||
if (lookAheadToken != Token.None) return lookAheadToken;
|
||||
|
||||
return lookAheadToken = NextTokenCore();
|
||||
}
|
||||
|
||||
private void ConsumeToken()
|
||||
{
|
||||
lookAheadToken = Token.None;
|
||||
}
|
||||
|
||||
private Token NextToken()
|
||||
{
|
||||
var result = lookAheadToken != Token.None ? lookAheadToken : NextTokenCore();
|
||||
|
||||
lookAheadToken = Token.None;
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
private Token NextTokenCore()
|
||||
{
|
||||
char c;
|
||||
|
||||
// Skip past whitespace
|
||||
do
|
||||
{
|
||||
c = json[index];
|
||||
|
||||
if (c > ' ') break;
|
||||
if (c != ' ' && c != '\t' && c != '\n' && c != '\r') break;
|
||||
|
||||
} while (++index < json.Length);
|
||||
|
||||
if (index == json.Length)
|
||||
{
|
||||
throw new Exception("Reached end of string unexpectedly");
|
||||
}
|
||||
|
||||
c = json[index];
|
||||
|
||||
index++;
|
||||
|
||||
//if (c >= '0' && c <= '9')
|
||||
// return Token.Number;
|
||||
|
||||
switch (c)
|
||||
{
|
||||
case '{':
|
||||
return Token.Curly_Open;
|
||||
|
||||
case '}':
|
||||
return Token.Curly_Close;
|
||||
|
||||
case '[':
|
||||
return Token.Squared_Open;
|
||||
|
||||
case ']':
|
||||
return Token.Squared_Close;
|
||||
|
||||
case ',':
|
||||
return Token.Comma;
|
||||
|
||||
case '"':
|
||||
return Token.String;
|
||||
|
||||
case '0': case '1': case '2': case '3': case '4':
|
||||
case '5': case '6': case '7': case '8': case '9':
|
||||
case '-': case '+': case '.':
|
||||
return Token.Number;
|
||||
|
||||
case ':':
|
||||
return Token.Colon;
|
||||
|
||||
case 'f':
|
||||
if (json.Length - index >= 4 &&
|
||||
json[index + 0] == 'a' &&
|
||||
json[index + 1] == 'l' &&
|
||||
json[index + 2] == 's' &&
|
||||
json[index + 3] == 'e')
|
||||
{
|
||||
index += 4;
|
||||
return Token.False;
|
||||
}
|
||||
break;
|
||||
|
||||
case 't':
|
||||
if (json.Length - index >= 3 &&
|
||||
json[index + 0] == 'r' &&
|
||||
json[index + 1] == 'u' &&
|
||||
json[index + 2] == 'e')
|
||||
{
|
||||
index += 3;
|
||||
return Token.True;
|
||||
}
|
||||
break;
|
||||
|
||||
case 'n':
|
||||
if (json.Length - index >= 3 &&
|
||||
json[index + 0] == 'u' &&
|
||||
json[index + 1] == 'l' &&
|
||||
json[index + 2] == 'l')
|
||||
{
|
||||
index += 3;
|
||||
return Token.Null;
|
||||
}
|
||||
break;
|
||||
|
||||
}
|
||||
|
||||
throw new Exception("Could not find token at index " + --index);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,521 +0,0 @@
|
||||
//http://fastjson.codeplex.com/
|
||||
//http://fastjson.codeplex.com/license
|
||||
|
||||
using System;
|
||||
using System.Collections;
|
||||
using System.Collections.Generic;
|
||||
using System.Data;
|
||||
using System.Globalization;
|
||||
using System.IO;
|
||||
using System.Text;
|
||||
|
||||
namespace LogentriesNLog.fastJSON
|
||||
{
|
||||
internal class JSONSerializer
|
||||
{
|
||||
private readonly StringBuilder _output = new StringBuilder();
|
||||
readonly bool useMinimalDataSetSchema;
|
||||
readonly bool fastguid = true;
|
||||
readonly bool useExtension = true;
|
||||
readonly bool serializeNulls = true;
|
||||
readonly int _MAX_DEPTH = 10;
|
||||
readonly bool _Indent;
|
||||
readonly bool _useGlobalTypes = true;
|
||||
int _current_depth;
|
||||
private readonly Dictionary<string, int> _globalTypes = new Dictionary<string, int>();
|
||||
|
||||
internal JSONSerializer(bool UseMinimalDataSetSchema, bool UseFastGuid, bool UseExtensions, bool SerializeNulls, bool IndentOutput)
|
||||
{
|
||||
useMinimalDataSetSchema = UseMinimalDataSetSchema;
|
||||
fastguid = UseFastGuid;
|
||||
useExtension = UseExtensions;
|
||||
_Indent = IndentOutput;
|
||||
serializeNulls = SerializeNulls;
|
||||
if (useExtension == false)
|
||||
_useGlobalTypes = false;
|
||||
}
|
||||
|
||||
internal string ConvertToJSON(object obj)
|
||||
{
|
||||
WriteValue(obj);
|
||||
|
||||
string str = "";
|
||||
if (_useGlobalTypes)
|
||||
{
|
||||
StringBuilder sb = new StringBuilder();
|
||||
sb.Append("{\"$types\":{");
|
||||
bool pendingSeparator = false;
|
||||
foreach (var kv in _globalTypes)
|
||||
{
|
||||
if (pendingSeparator) sb.Append(',');
|
||||
pendingSeparator = true;
|
||||
sb.Append("\"");
|
||||
sb.Append(kv.Key);
|
||||
sb.Append("\":\"");
|
||||
sb.Append(kv.Value);
|
||||
sb.Append("\"");
|
||||
}
|
||||
sb.Append("},");
|
||||
str = sb + _output.ToString();
|
||||
}
|
||||
else
|
||||
str = _output.ToString();
|
||||
|
||||
return str;
|
||||
}
|
||||
|
||||
private void WriteValue(object obj)
|
||||
{
|
||||
if (obj == null || obj is DBNull)
|
||||
_output.Append("null");
|
||||
|
||||
else if (obj is string || obj is char)
|
||||
WriteString((string)obj);
|
||||
|
||||
else if (obj is Guid)
|
||||
WriteGuid((Guid)obj);
|
||||
|
||||
else if (obj is bool)
|
||||
_output.Append(((bool)obj) ? "true" : "false"); // conform to standard
|
||||
|
||||
else if (
|
||||
obj is int || obj is long || obj is double ||
|
||||
obj is decimal || obj is float ||
|
||||
obj is byte || obj is short ||
|
||||
obj is sbyte || obj is ushort ||
|
||||
obj is uint || obj is ulong
|
||||
)
|
||||
_output.Append(((IConvertible)obj).ToString(NumberFormatInfo.InvariantInfo));
|
||||
|
||||
else if (obj is DateTime)
|
||||
WriteDateTime((DateTime)obj);
|
||||
|
||||
else if (obj is IDictionary && obj.GetType().IsGenericType && obj.GetType().GetGenericArguments()[0] == typeof(string))
|
||||
WriteStringDictionary((IDictionary)obj);
|
||||
|
||||
else if (obj is IDictionary)
|
||||
WriteDictionary((IDictionary)obj);
|
||||
#if !SILVERLIGHT
|
||||
else if (obj is DataSet)
|
||||
WriteDataset((DataSet)obj);
|
||||
|
||||
else if (obj is DataTable)
|
||||
WriteDataTable((DataTable)obj);
|
||||
#endif
|
||||
else if (obj is byte[])
|
||||
WriteBytes((byte[])obj);
|
||||
|
||||
else if (obj is Array || obj is IList || obj is ICollection)
|
||||
WriteArray((IEnumerable)obj);
|
||||
|
||||
else if (obj is Enum)
|
||||
WriteEnum((Enum)obj);
|
||||
|
||||
#if CUSTOMTYPE
|
||||
else if (JSON.Instance.IsTypeRegistered(obj.GetType()))
|
||||
WriteCustom(obj);
|
||||
#endif
|
||||
else
|
||||
WriteObject(obj);
|
||||
}
|
||||
|
||||
#if CUSTOMTYPE
|
||||
private void WriteCustom(object obj)
|
||||
{
|
||||
Serialize s;
|
||||
JSON.Instance._customSerializer.TryGetValue(obj.GetType(), out s);
|
||||
WriteStringFast(s(obj));
|
||||
}
|
||||
#endif
|
||||
|
||||
private void WriteEnum(Enum e)
|
||||
{
|
||||
// TODO : optimize enum write
|
||||
WriteStringFast(e.ToString());
|
||||
}
|
||||
|
||||
private void WriteGuid(Guid g)
|
||||
{
|
||||
if (fastguid == false)
|
||||
WriteStringFast(g.ToString());
|
||||
else
|
||||
WriteBytes(g.ToByteArray());
|
||||
}
|
||||
|
||||
private void WriteBytes(byte[] bytes)
|
||||
{
|
||||
#if !SILVERLIGHT
|
||||
WriteStringFast(Convert.ToBase64String(bytes, 0, bytes.Length, Base64FormattingOptions.None));
|
||||
#else
|
||||
WriteStringFast(Convert.ToBase64String(bytes, 0, bytes.Length));
|
||||
#endif
|
||||
}
|
||||
|
||||
private void WriteDateTime(DateTime dateTime)
|
||||
{
|
||||
// datetime format standard : yyyy-MM-dd HH:mm:ss
|
||||
DateTime dt = dateTime;
|
||||
if (JSON.Instance.UseUTCDateTime)
|
||||
dt = dateTime.ToUniversalTime();
|
||||
|
||||
_output.Append("\"");
|
||||
_output.Append(dt.Year.ToString("0000", NumberFormatInfo.InvariantInfo));
|
||||
_output.Append("-");
|
||||
_output.Append(dt.Month.ToString("00", NumberFormatInfo.InvariantInfo));
|
||||
_output.Append("-");
|
||||
_output.Append(dt.Day.ToString("00", NumberFormatInfo.InvariantInfo));
|
||||
_output.Append(" ");
|
||||
_output.Append(dt.Hour.ToString("00", NumberFormatInfo.InvariantInfo));
|
||||
_output.Append(":");
|
||||
_output.Append(dt.Minute.ToString("00", NumberFormatInfo.InvariantInfo));
|
||||
_output.Append(":");
|
||||
_output.Append(dt.Second.ToString("00", NumberFormatInfo.InvariantInfo));
|
||||
_output.Append(".");
|
||||
_output.Append(dt.Millisecond.ToString("000", NumberFormatInfo.InvariantInfo));
|
||||
|
||||
if (JSON.Instance.UseUTCDateTime)
|
||||
_output.Append("Z");
|
||||
|
||||
_output.Append("\"");
|
||||
}
|
||||
#if !SILVERLIGHT
|
||||
private DatasetSchema GetSchema(DataTable ds)
|
||||
{
|
||||
if (ds == null) return null;
|
||||
|
||||
DatasetSchema m = new DatasetSchema();
|
||||
m.Info = new List<string>();
|
||||
m.Name = ds.TableName;
|
||||
|
||||
foreach (DataColumn c in ds.Columns)
|
||||
{
|
||||
m.Info.Add(ds.TableName);
|
||||
m.Info.Add(c.ColumnName);
|
||||
m.Info.Add(c.DataType.ToString());
|
||||
}
|
||||
// TODO : serialize relations and constraints here
|
||||
|
||||
return m;
|
||||
}
|
||||
|
||||
private DatasetSchema GetSchema(DataSet ds)
|
||||
{
|
||||
if (ds == null) return null;
|
||||
|
||||
DatasetSchema m = new DatasetSchema();
|
||||
m.Info = new List<string>();
|
||||
m.Name = ds.DataSetName;
|
||||
|
||||
foreach (DataTable t in ds.Tables)
|
||||
{
|
||||
foreach (DataColumn c in t.Columns)
|
||||
{
|
||||
m.Info.Add(t.TableName);
|
||||
m.Info.Add(c.ColumnName);
|
||||
m.Info.Add(c.DataType.ToString());
|
||||
}
|
||||
}
|
||||
// TODO : serialize relations and constraints here
|
||||
|
||||
return m;
|
||||
}
|
||||
|
||||
private string GetXmlSchema(DataTable dt)
|
||||
{
|
||||
using (var writer = new StringWriter())
|
||||
{
|
||||
dt.WriteXmlSchema(writer);
|
||||
return dt.ToString();
|
||||
}
|
||||
}
|
||||
|
||||
private void WriteDataset(DataSet ds)
|
||||
{
|
||||
_output.Append('{');
|
||||
if (useExtension)
|
||||
{
|
||||
WritePair("$schema", useMinimalDataSetSchema ? (object)GetSchema(ds) : ds.GetXmlSchema());
|
||||
_output.Append(',');
|
||||
}
|
||||
bool tablesep = false;
|
||||
foreach (DataTable table in ds.Tables)
|
||||
{
|
||||
if (tablesep) _output.Append(",");
|
||||
tablesep = true;
|
||||
WriteDataTableData(table);
|
||||
}
|
||||
// end dataset
|
||||
_output.Append('}');
|
||||
}
|
||||
|
||||
private void WriteDataTableData(DataTable table)
|
||||
{
|
||||
_output.Append('\"');
|
||||
_output.Append(table.TableName);
|
||||
_output.Append("\":[");
|
||||
DataColumnCollection cols = table.Columns;
|
||||
bool rowseparator = false;
|
||||
foreach (DataRow row in table.Rows)
|
||||
{
|
||||
if (rowseparator) _output.Append(",");
|
||||
rowseparator = true;
|
||||
_output.Append('[');
|
||||
|
||||
bool pendingSeperator = false;
|
||||
foreach (DataColumn column in cols)
|
||||
{
|
||||
if (pendingSeperator) _output.Append(',');
|
||||
WriteValue(row[column]);
|
||||
pendingSeperator = true;
|
||||
}
|
||||
_output.Append(']');
|
||||
}
|
||||
|
||||
_output.Append(']');
|
||||
}
|
||||
|
||||
void WriteDataTable(DataTable dt)
|
||||
{
|
||||
_output.Append('{');
|
||||
if (useExtension)
|
||||
{
|
||||
WritePair("$schema", useMinimalDataSetSchema ? (object)GetSchema(dt) : GetXmlSchema(dt));
|
||||
_output.Append(',');
|
||||
}
|
||||
|
||||
WriteDataTableData(dt);
|
||||
|
||||
// end datatable
|
||||
_output.Append('}');
|
||||
}
|
||||
#endif
|
||||
bool _firstWritten;
|
||||
private void WriteObject(object obj)
|
||||
{
|
||||
Indent();
|
||||
if (_useGlobalTypes == false)
|
||||
_output.Append('{');
|
||||
else
|
||||
{
|
||||
if (_firstWritten)
|
||||
_output.Append("{");
|
||||
}
|
||||
_firstWritten = true;
|
||||
_current_depth++;
|
||||
if (_current_depth > _MAX_DEPTH)
|
||||
throw new Exception("Serializer encountered maximum depth of " + _MAX_DEPTH);
|
||||
|
||||
|
||||
var map = new Dictionary<string, string>();
|
||||
Type t = obj.GetType();
|
||||
bool append = false;
|
||||
if (useExtension)
|
||||
{
|
||||
if (_useGlobalTypes == false)
|
||||
WritePairFast("$type", JSON.Instance.GetTypeAssemblyName(t));
|
||||
else
|
||||
{
|
||||
int dt = 0;
|
||||
string ct = JSON.Instance.GetTypeAssemblyName(t);
|
||||
if (_globalTypes.TryGetValue(ct, out dt) == false)
|
||||
{
|
||||
dt = _globalTypes.Count + 1;
|
||||
_globalTypes.Add(ct, dt);
|
||||
}
|
||||
WritePairFast("$type", dt.ToString());
|
||||
}
|
||||
append = true;
|
||||
}
|
||||
|
||||
var g = JSON.Instance.GetGetters(t);
|
||||
foreach (var p in g)
|
||||
{
|
||||
if (append)
|
||||
_output.Append(',');
|
||||
object o = p.Getter(obj);
|
||||
if ((o == null || o is DBNull) && serializeNulls == false)
|
||||
append = false;
|
||||
else
|
||||
{
|
||||
WritePair(p.Name, o);
|
||||
if (o != null && useExtension)
|
||||
{
|
||||
Type tt = o.GetType();
|
||||
if (tt == typeof(Object))
|
||||
map.Add(p.Name, tt.ToString());
|
||||
}
|
||||
append = true;
|
||||
}
|
||||
}
|
||||
if (map.Count > 0 && useExtension)
|
||||
{
|
||||
_output.Append(",\"$map\":");
|
||||
WriteStringDictionary(map);
|
||||
}
|
||||
_current_depth--;
|
||||
Indent();
|
||||
_output.Append('}');
|
||||
_current_depth--;
|
||||
|
||||
}
|
||||
|
||||
private void Indent()
|
||||
{
|
||||
Indent(false);
|
||||
}
|
||||
|
||||
private void Indent(bool dec)
|
||||
{
|
||||
if (_Indent)
|
||||
{
|
||||
_output.Append("\r\n");
|
||||
for (int i = 0; i < _current_depth - (dec ? 1 : 0); i++)
|
||||
_output.Append("\t");
|
||||
}
|
||||
}
|
||||
|
||||
private void WritePairFast(string name, string value)
|
||||
{
|
||||
if ((value == null) && serializeNulls == false)
|
||||
return;
|
||||
Indent();
|
||||
WriteStringFast(name);
|
||||
|
||||
_output.Append(':');
|
||||
|
||||
WriteStringFast(value);
|
||||
}
|
||||
|
||||
private void WritePair(string name, object value)
|
||||
{
|
||||
if ((value == null || value is DBNull) && serializeNulls == false)
|
||||
return;
|
||||
Indent();
|
||||
WriteStringFast(name);
|
||||
|
||||
_output.Append(':');
|
||||
|
||||
WriteValue(value);
|
||||
}
|
||||
|
||||
private void WriteArray(IEnumerable array)
|
||||
{
|
||||
Indent();
|
||||
_output.Append('[');
|
||||
|
||||
bool pendingSeperator = false;
|
||||
|
||||
foreach (var obj in array)
|
||||
{
|
||||
Indent();
|
||||
if (pendingSeperator) _output.Append(',');
|
||||
|
||||
WriteValue(obj);
|
||||
|
||||
pendingSeperator = true;
|
||||
}
|
||||
Indent();
|
||||
_output.Append(']');
|
||||
}
|
||||
|
||||
private void WriteStringDictionary(IDictionary dic)
|
||||
{
|
||||
Indent();
|
||||
_output.Append('{');
|
||||
|
||||
bool pendingSeparator = false;
|
||||
|
||||
foreach (DictionaryEntry entry in dic)
|
||||
{
|
||||
if (pendingSeparator) _output.Append(',');
|
||||
|
||||
WritePair((string)entry.Key, entry.Value);
|
||||
|
||||
pendingSeparator = true;
|
||||
}
|
||||
Indent();
|
||||
_output.Append('}');
|
||||
}
|
||||
|
||||
private void WriteDictionary(IDictionary dic)
|
||||
{
|
||||
Indent();
|
||||
_output.Append('[');
|
||||
|
||||
bool pendingSeparator = false;
|
||||
|
||||
foreach (DictionaryEntry entry in dic)
|
||||
{
|
||||
if (pendingSeparator) _output.Append(',');
|
||||
Indent();
|
||||
_output.Append('{');
|
||||
WritePair("k", entry.Key);
|
||||
_output.Append(",");
|
||||
WritePair("v", entry.Value);
|
||||
Indent();
|
||||
_output.Append('}');
|
||||
|
||||
pendingSeparator = true;
|
||||
}
|
||||
Indent();
|
||||
_output.Append(']');
|
||||
}
|
||||
|
||||
private void WriteStringFast(string s)
|
||||
{
|
||||
//Indent();
|
||||
_output.Append('\"');
|
||||
_output.Append(s);
|
||||
_output.Append('\"');
|
||||
}
|
||||
|
||||
private void WriteString(string s)
|
||||
{
|
||||
//Indent();
|
||||
_output.Append('\"');
|
||||
|
||||
int runIndex = -1;
|
||||
|
||||
for (var index = 0; index < s.Length; ++index)
|
||||
{
|
||||
var c = s[index];
|
||||
|
||||
if (c >= ' ' && c < 128 && c != '\"' && c != '\\')
|
||||
{
|
||||
if (runIndex == -1)
|
||||
{
|
||||
runIndex = index;
|
||||
}
|
||||
|
||||
continue;
|
||||
}
|
||||
|
||||
if (runIndex != -1)
|
||||
{
|
||||
_output.Append(s, runIndex, index - runIndex);
|
||||
runIndex = -1;
|
||||
}
|
||||
|
||||
switch (c)
|
||||
{
|
||||
case '\t': _output.Append("\\t"); break;
|
||||
case '\r': _output.Append("\\r"); break;
|
||||
case '\n': _output.Append("\\n"); break;
|
||||
case '"':
|
||||
case '\\': _output.Append('\\'); _output.Append(c); break;
|
||||
default:
|
||||
_output.Append("\\u");
|
||||
_output.Append(((int)c).ToString("X4", NumberFormatInfo.InvariantInfo));
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
if (runIndex != -1)
|
||||
{
|
||||
_output.Append(s, runIndex, s.Length - runIndex);
|
||||
}
|
||||
|
||||
_output.Append('\"');
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,36 +0,0 @@
|
||||
//http://fastjson.codeplex.com/
|
||||
//http://fastjson.codeplex.com/license
|
||||
|
||||
using System.Collections.Generic;
|
||||
|
||||
namespace LogentriesNLog.fastJSON
|
||||
{
|
||||
internal class SafeDictionary<TKey, TValue>
|
||||
{
|
||||
private readonly object _Padlock = new object();
|
||||
private readonly Dictionary<TKey, TValue> _Dictionary = new Dictionary<TKey, TValue>();
|
||||
|
||||
|
||||
internal bool TryGetValue(TKey key, out TValue value)
|
||||
{
|
||||
return _Dictionary.TryGetValue(key, out value);
|
||||
}
|
||||
|
||||
internal TValue this[TKey key]
|
||||
{
|
||||
get
|
||||
{
|
||||
return _Dictionary[key];
|
||||
}
|
||||
}
|
||||
|
||||
internal void Add(TKey key, TValue value)
|
||||
{
|
||||
lock (_Padlock)
|
||||
{
|
||||
if (_Dictionary.ContainsKey(key) == false)
|
||||
_Dictionary.Add(key, value);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,87 +0,0 @@
|
||||
Copyright (C) 1989, 1991 Free Software Foundation, Inc.
|
||||
59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
|
||||
|
||||
Everyone is permitted to copy and distribute verbatim copies
|
||||
of this license document, but changing it is not allowed.
|
||||
|
||||
Preamble
|
||||
|
||||
The licenses for most software are designed to take away your freedom to share and change it. By contrast, the GNU General Public License is intended to guarantee your freedom to share and change free software--to make sure the software is free for all its users. This General Public License applies to most of the Free Software Foundation's software and to any other program whose authors commit to using it. (Some other Free Software Foundation software is covered by the GNU Library General Public License instead.) You can apply it to your programs, too.
|
||||
|
||||
When we speak of free software, we are referring to freedom, not price. Our General Public Licenses are designed to make sure that you have the freedom to distribute copies of free software (and charge for this service if you wish), that you receive source code or can get it if you want it, that you can change the software or use pieces of it in new free programs; and that you know you can do these things.
|
||||
|
||||
To protect your rights, we need to make restrictions that forbid anyone to deny you these rights or to ask you to surrender the rights. These restrictions translate to certain responsibilities for you if you distribute copies of the software, or if you modify it.
|
||||
|
||||
For example, if you distribute copies of such a program, whether gratis or for a fee, you must give the recipients all the rights that you have. You must make sure that they, too, receive or can get the source code. And you must show them these terms so they know their rights.
|
||||
|
||||
We protect your rights with two steps: (1) copyright the software, and (2) offer you this license which gives you legal permission to copy, distribute and/or modify the software.
|
||||
|
||||
Also, for each author's protection and ours, we want to make certain that everyone understands that there is no warranty for this free software. If the software is modified by someone else and passed on, we want its recipients to know that what they have is not the original, so that any problems introduced by others will not reflect on the original authors' reputations.
|
||||
|
||||
Finally, any free program is threatened constantly by software patents. We wish to avoid the danger that redistributors of a free program will individually obtain patent licenses, in effect making the program proprietary. To prevent this, we have made it clear that any patent must be licensed for everyone's free use or not licensed at all.
|
||||
|
||||
The precise terms and conditions for copying, distribution and modification follow.
|
||||
|
||||
TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION
|
||||
|
||||
0. This License applies to any program or other work which contains a notice placed by the copyright holder saying it may be distributed under the terms of this General Public License. The "Program", below, refers to any such program or work, and a "work based on the Program" means either the Program or any derivative work under copyright law: that is to say, a work containing the Program or a portion of it, either verbatim or with modifications and/or translated into another language. (Hereinafter, translation is included without limitation in the term "modification".) Each licensee is addressed as "you".
|
||||
|
||||
Activities other than copying, distribution and modification are not covered by this License; they are outside its scope. The act of running the Program is not restricted, and the output from the Program is covered only if its contents constitute a work based on the Program (independent of having been made by running the Program). Whether that is true depends on what the Program does.
|
||||
|
||||
1. You may copy and distribute verbatim copies of the Program's source code as you receive it, in any medium, provided that you conspicuously and appropriately publish on each copy an appropriate copyright notice and disclaimer of warranty; keep intact all the notices that refer to this License and to the absence of any warranty; and give any other recipients of the Program a copy of this License along with the Program.
|
||||
|
||||
You may charge a fee for the physical act of transferring a copy, and you may at your option offer warranty protection in exchange for a fee.
|
||||
|
||||
2. You may modify your copy or copies of the Program or any portion of it, thus forming a work based on the Program, and copy and distribute such modifications or work under the terms of Section 1 above, provided that you also meet all of these conditions:
|
||||
|
||||
a) You must cause the modified files to carry prominent notices stating that you changed the files and the date of any change.
|
||||
|
||||
b) You must cause any work that you distribute or publish, that in whole or in part contains or is derived from the Program or any part thereof, to be licensed as a whole at no charge to all third parties under the terms of this License.
|
||||
|
||||
c) If the modified program normally reads commands interactively when run, you must cause it, when started running for such interactive use in the most ordinary way, to print or display an announcement including an appropriate copyright notice and a notice that there is no warranty (or else, saying that you provide a warranty) and that users may redistribute the program under these conditions, and telling the user how to view a copy of this License. (Exception: if the Program itself is interactive but does not normally print such an announcement, your work based on the Program is not required to print an announcement.)
|
||||
|
||||
These requirements apply to the modified work as a whole. If identifiable sections of that work are not derived from the Program, and can be reasonably considered independent and separate works in themselves, then this License, and its terms, do not apply to those sections when you distribute them as separate works. But when you distribute the same sections as part of a whole which is a work based on the Program, the distribution of the whole must be on the terms of this License, whose permissions for other licensees extend to the entire whole, and thus to each and every part regardless of who wrote it.
|
||||
|
||||
Thus, it is not the intent of this section to claim rights or contest your rights to work written entirely by you; rather, the intent is to exercise the right to control the distribution of derivative or collective works based on the Program.
|
||||
|
||||
In addition, mere aggregation of another work not based on the Program with the Program (or with a work based on the Program) on a volume of a storage or distribution medium does not bring the other work under the scope of this License.
|
||||
|
||||
3. You may copy and distribute the Program (or a work based on it, under Section 2) in object code or executable form under the terms of Sections 1 and 2 above provided that you also do one of the following:
|
||||
|
||||
a) Accompany it with the complete corresponding machine-readable source code, which must be distributed under the terms of Sections 1 and 2 above on a medium customarily used for software interchange; or,
|
||||
|
||||
b) Accompany it with a written offer, valid for at least three years, to give any third party, for a charge no more than your cost of physically performing source distribution, a complete machine-readable copy of the corresponding source code, to be distributed under the terms of Sections 1 and 2 above on a medium customarily used for software interchange; or,
|
||||
|
||||
c) Accompany it with the information you received as to the offer to distribute corresponding source code. (This alternative is allowed only for noncommercial distribution and only if you received the program in object code or executable form with such an offer, in accord with Subsection b above.)
|
||||
|
||||
The source code for a work means the preferred form of the work for making modifications to it. For an executable work, complete source code means all the source code for all modules it contains, plus any associated interface definition files, plus the scripts used to control compilation and installation of the executable. However, as a special exception, the source code distributed need not include anything that is normally distributed (in either source or binary form) with the major components (compiler, kernel, and so on) of the operating system on which the executable runs, unless that component itself accompanies the executable.
|
||||
|
||||
If distribution of executable or object code is made by offering access to copy from a designated place, then offering equivalent access to copy the source code from the same place counts as distribution of the source code, even though third parties are not compelled to copy the source along with the object code.
|
||||
|
||||
4. You may not copy, modify, sublicense, or distribute the Program except as expressly provided under this License. Any attempt otherwise to copy, modify, sublicense or distribute the Program is void, and will automatically terminate your rights under this License. However, parties who have received copies, or rights, from you under this License will not have their licenses terminated so long as such parties remain in full compliance.
|
||||
|
||||
5. You are not required to accept this License, since you have not signed it. However, nothing else grants you permission to modify or distribute the Program or its derivative works. These actions are prohibited by law if you do not accept this License. Therefore, by modifying or distributing the Program (or any work based on the Program), you indicate your acceptance of this License to do so, and all its terms and conditions for copying, distributing or modifying the Program or works based on it.
|
||||
|
||||
6. Each time you redistribute the Program (or any work based on the Program), the recipient automatically receives a license from the original licensor to copy, distribute or modify the Program subject to these terms and conditions. You may not impose any further restrictions on the recipients' exercise of the rights granted herein. You are not responsible for enforcing compliance by third parties to this License.
|
||||
|
||||
7. If, as a consequence of a court judgment or allegation of patent infringement or for any other reason (not limited to patent issues), conditions are imposed on you (whether by court order, agreement or otherwise) that contradict the conditions of this License, they do not excuse you from the conditions of this License. If you cannot distribute so as to satisfy simultaneously your obligations under this License and any other pertinent obligations, then as a consequence you may not distribute the Program at all. For example, if a patent license would not permit royalty-free redistribution of the Program by all those who receive copies directly or indirectly through you, then the only way you could satisfy both it and this License would be to refrain entirely from distribution of the Program.
|
||||
|
||||
If any portion of this section is held invalid or unenforceable under any particular circumstance, the balance of the section is intended to apply and the section as a whole is intended to apply in other circumstances.
|
||||
|
||||
It is not the purpose of this section to induce you to infringe any patents or other property right claims or to contest validity of any such claims; this section has the sole purpose of protecting the integrity of the free software distribution system, which is implemented by public license practices. Many people have made generous contributions to the wide range of software distributed through that system in reliance on consistent application of that system; it is up to the author/donor to decide if he or she is willing to distribute software through any other system and a licensee cannot impose that choice.
|
||||
|
||||
This section is intended to make thoroughly clear what is believed to be a consequence of the rest of this License.
|
||||
|
||||
8. If the distribution and/or use of the Program is restricted in certain countries either by patents or by copyrighted interfaces, the original copyright holder who places the Program under this License may add an explicit geographical distribution limitation excluding those countries, so that distribution is permitted only in or among countries not thus excluded. In such case, this License incorporates the limitation as if written in the body of this License.
|
||||
|
||||
9. The Free Software Foundation may publish revised and/or new versions of the General Public License from time to time. Such new versions will be similar in spirit to the present version, but may differ in detail to address new problems or concerns.
|
||||
|
||||
Each version is given a distinguishing version number. If the Program specifies a version number of this License which applies to it and "any later version", you have the option of following the terms and conditions either of that version or of any later version published by the Free Software Foundation. If the Program does not specify a version number of this License, you may choose any version ever published by the Free Software Foundation.
|
||||
|
||||
10. If you wish to incorporate parts of the Program into other free programs whose distribution conditions are different, write to the author to ask for permission. For software which is copyrighted by the Free Software Foundation, write to the Free Software Foundation; we sometimes make exceptions for this. Our decision will be guided by the two goals of preserving the free status of all derivatives of our free software and of promoting the sharing and reuse of software generally.
|
||||
|
||||
NO WARRANTY
|
||||
|
||||
11. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
|
||||
|
||||
12. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR REDISTRIBUTE THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES.
|
||||
@@ -1,4 +0,0 @@
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<packages>
|
||||
<package id="NLog" version="4.5.0-rc06" targetFramework="net40" />
|
||||
</packages>
|
||||
@@ -1,4 +1,4 @@
|
||||
using System;
|
||||
using System;
|
||||
using System.IO;
|
||||
using System.IO.Compression;
|
||||
using System.Linq;
|
||||
@@ -23,7 +23,7 @@ namespace NzbDrone.Api.Extensions.Pipelines
|
||||
_logger = logger;
|
||||
|
||||
// On Mono GZipStream/DeflateStream leaks memory if an exception is thrown, use an intermediate buffer in that case.
|
||||
_writeGZipStream = OsInfo.IsMonoRuntime ? WriteGZipStreamMono : (Action<Action<Stream>, Stream>)WriteGZipStream;
|
||||
_writeGZipStream = PlatformInfo.IsMono ? WriteGZipStreamMono : (Action<Action<Stream>, Stream>)WriteGZipStream;
|
||||
}
|
||||
|
||||
public void Register(IPipelines pipelines)
|
||||
|
||||
@@ -14,7 +14,7 @@ namespace NzbDrone.Api.Frontend
|
||||
{
|
||||
public bool IsCacheable(NancyContext context)
|
||||
{
|
||||
if (!RuntimeInfoBase.IsProduction)
|
||||
if (!RuntimeInfo.IsProduction)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
@@ -46,4 +46,4 @@ namespace NzbDrone.Api.Frontend
|
||||
return true;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -79,7 +79,7 @@ namespace NzbDrone.Api.Frontend.Mappers
|
||||
|
||||
private string GetIndexText()
|
||||
{
|
||||
if (RuntimeInfoBase.IsProduction && _generatedContent != null)
|
||||
if (RuntimeInfo.IsProduction && _generatedContent != null)
|
||||
{
|
||||
return _generatedContent;
|
||||
}
|
||||
@@ -111,7 +111,7 @@ namespace NzbDrone.Api.Frontend.Mappers
|
||||
text = text.Replace("APP_BRANCH", _configFileProvider.Branch.ToLower());
|
||||
text = text.Replace("APP_ANALYTICS", _analyticsService.IsEnabled.ToString().ToLowerInvariant());
|
||||
text = text.Replace("URL_BASE", URL_BASE);
|
||||
text = text.Replace("PRODUCTION", RuntimeInfoBase.IsProduction.ToString().ToLowerInvariant());
|
||||
text = text.Replace("PRODUCTION", RuntimeInfo.IsProduction.ToString().ToLowerInvariant());
|
||||
|
||||
_generatedContent = text;
|
||||
|
||||
|
||||
@@ -67,7 +67,7 @@ namespace NzbDrone.Api.Frontend.Mappers
|
||||
|
||||
private string GetLoginText()
|
||||
{
|
||||
if (RuntimeInfoBase.IsProduction && _generatedContent != null)
|
||||
if (RuntimeInfo.IsProduction && _generatedContent != null)
|
||||
{
|
||||
return _generatedContent;
|
||||
}
|
||||
|
||||
@@ -21,7 +21,7 @@ namespace NzbDrone.Api.Frontend.Mappers
|
||||
_diskProvider = diskProvider;
|
||||
_logger = logger;
|
||||
|
||||
if (!RuntimeInfoBase.IsProduction)
|
||||
if (!RuntimeInfo.IsProduction)
|
||||
{
|
||||
_caseSensitive = StringComparison.OrdinalIgnoreCase;
|
||||
}
|
||||
|
||||
@@ -95,11 +95,11 @@ namespace NzbDrone.Api.Indexers
|
||||
}
|
||||
catch (NotImplementedException ex)
|
||||
{
|
||||
_logger.Error(ex, "One or more indexer you selected does not support movie search yet: " + ex.Message);
|
||||
_logger.Error(ex, "One or more indexer you selected does not support movie search yet: {0}", ex.Message);
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_logger.Error(ex, "Movie search failed: " + ex.Message);
|
||||
_logger.Error(ex, "Movie search failed: {0}", ex.Message);
|
||||
}
|
||||
|
||||
return new List<ReleaseResource>();
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
using System.Linq;
|
||||
using System.Linq;
|
||||
using Nancy.Bootstrapper;
|
||||
using Nancy.Diagnostics;
|
||||
using NLog;
|
||||
@@ -24,9 +24,9 @@ namespace NzbDrone.Api
|
||||
|
||||
protected override void ApplicationStartup(TinyIoCContainer container, IPipelines pipelines)
|
||||
{
|
||||
Logger.Info("Starting NzbDrone API");
|
||||
Logger.Info("Starting Web Server");
|
||||
|
||||
if (RuntimeInfoBase.IsProduction)
|
||||
if (RuntimeInfo.IsProduction)
|
||||
{
|
||||
DiagnosticsHook.Disable(pipelines);
|
||||
}
|
||||
|
||||
@@ -68,9 +68,8 @@
|
||||
<HintPath>..\packages\Nancy.Authentication.Forms.1.4.1\lib\net40\Nancy.Authentication.Forms.dll</HintPath>
|
||||
<Private>True</Private>
|
||||
</Reference>
|
||||
<Reference Include="Newtonsoft.Json, Version=6.0.0.0, Culture=neutral, PublicKeyToken=30ad4fe6b2a6aeed, processorArchitecture=MSIL">
|
||||
<SpecificVersion>False</SpecificVersion>
|
||||
<HintPath>..\packages\Newtonsoft.Json.6.0.6\lib\net40\Newtonsoft.Json.dll</HintPath>
|
||||
<Reference Include="Newtonsoft.Json, Version=9.0.0.0, Culture=neutral, PublicKeyToken=30ad4fe6b2a6aeed, processorArchitecture=MSIL">
|
||||
<HintPath>..\packages\Newtonsoft.Json.9.0.1\lib\net40\Newtonsoft.Json.dll</HintPath>
|
||||
</Reference>
|
||||
<Reference Include="NLog, Version=4.0.0.0, Culture=neutral, PublicKeyToken=5120e14c03d0593c, processorArchitecture=MSIL">
|
||||
<HintPath>..\packages\NLog.4.5.0-rc06\lib\net40-client\NLog.dll</HintPath>
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
using Nancy;
|
||||
using Nancy;
|
||||
using Nancy.Routing;
|
||||
using NzbDrone.Api.Extensions;
|
||||
using NzbDrone.Common.EnvironmentInfo;
|
||||
@@ -13,6 +13,8 @@ namespace NzbDrone.Api.System
|
||||
{
|
||||
private readonly IAppFolderInfo _appFolderInfo;
|
||||
private readonly IRuntimeInfo _runtimeInfo;
|
||||
private readonly IPlatformInfo _platformInfo;
|
||||
private readonly IOsInfo _osInfo;
|
||||
private readonly IRouteCacheProvider _routeCacheProvider;
|
||||
private readonly IConfigFileProvider _configFileProvider;
|
||||
private readonly IMainDatabase _database;
|
||||
@@ -20,14 +22,17 @@ namespace NzbDrone.Api.System
|
||||
|
||||
public SystemModule(IAppFolderInfo appFolderInfo,
|
||||
IRuntimeInfo runtimeInfo,
|
||||
IPlatformInfo platformInfo,
|
||||
IOsInfo osInfo,
|
||||
IRouteCacheProvider routeCacheProvider,
|
||||
IConfigFileProvider configFileProvider,
|
||||
IMainDatabase database,
|
||||
ILifecycleService lifecycleService)
|
||||
: base("system")
|
||||
ILifecycleService lifecycleService) : base("system")
|
||||
{
|
||||
_appFolderInfo = appFolderInfo;
|
||||
_runtimeInfo = runtimeInfo;
|
||||
_platformInfo = platformInfo;
|
||||
_osInfo = osInfo;
|
||||
_routeCacheProvider = routeCacheProvider;
|
||||
_configFileProvider = configFileProvider;
|
||||
_database = database;
|
||||
@@ -41,27 +46,29 @@ namespace NzbDrone.Api.System
|
||||
private Response GetStatus()
|
||||
{
|
||||
return new
|
||||
{
|
||||
Version = BuildInfo.Version.ToString(),
|
||||
BuildTime = BuildInfo.BuildDateTime,
|
||||
IsDebug = BuildInfo.IsDebug,
|
||||
IsProduction = RuntimeInfoBase.IsProduction,
|
||||
IsAdmin = _runtimeInfo.IsAdmin,
|
||||
IsUserInteractive = RuntimeInfoBase.IsUserInteractive,
|
||||
StartupPath = _appFolderInfo.StartUpFolder,
|
||||
AppData = _appFolderInfo.GetAppDataPath(),
|
||||
OsVersion = OsInfo.Version.ToString(),
|
||||
IsMonoRuntime = OsInfo.IsMonoRuntime,
|
||||
IsMono = OsInfo.IsNotWindows,
|
||||
IsLinux = OsInfo.IsLinux,
|
||||
IsOsx = OsInfo.IsOsx,
|
||||
IsWindows = OsInfo.IsWindows,
|
||||
Branch = _configFileProvider.Branch,
|
||||
Authentication = _configFileProvider.AuthenticationMethod,
|
||||
SqliteVersion = _database.Version,
|
||||
UrlBase = _configFileProvider.UrlBase,
|
||||
RuntimeVersion = _runtimeInfo.RuntimeVersion
|
||||
}.AsResponse();
|
||||
{
|
||||
Version = BuildInfo.Version.ToString(),
|
||||
BuildTime = BuildInfo.BuildDateTime,
|
||||
IsDebug = BuildInfo.IsDebug,
|
||||
IsProduction = RuntimeInfo.IsProduction,
|
||||
IsAdmin = _runtimeInfo.IsAdmin,
|
||||
IsUserInteractive = RuntimeInfo.IsUserInteractive,
|
||||
StartupPath = _appFolderInfo.StartUpFolder,
|
||||
AppData = _appFolderInfo.GetAppDataPath(),
|
||||
OsName = _osInfo.Name,
|
||||
OsVersion = _osInfo.Version,
|
||||
IsMonoRuntime = PlatformInfo.IsMono,
|
||||
IsMono = PlatformInfo.IsMono,
|
||||
IsLinux = OsInfo.IsLinux,
|
||||
IsOsx = OsInfo.IsOsx,
|
||||
IsWindows = OsInfo.IsWindows,
|
||||
Branch = _configFileProvider.Branch,
|
||||
Authentication = _configFileProvider.AuthenticationMethod,
|
||||
SqliteVersion = _database.Version,
|
||||
UrlBase = _configFileProvider.UrlBase,
|
||||
RuntimeVersion = _platformInfo.Version,
|
||||
RuntimeName = PlatformInfo.Platform
|
||||
}.AsResponse();
|
||||
}
|
||||
|
||||
private Response GetRoutes()
|
||||
|
||||
@@ -15,9 +15,9 @@ namespace NzbDrone.Api.Wanted
|
||||
{
|
||||
protected readonly IMovieService _movieService;
|
||||
|
||||
public MovieMissingModule(IMovieService movieService,
|
||||
IQualityUpgradableSpecification qualityUpgradableSpecification,
|
||||
IBroadcastSignalRMessage signalRBroadcaster)
|
||||
public MovieMissingModule(IMovieService movieService,
|
||||
IQualityUpgradableSpecification qualityUpgradableSpecification,
|
||||
IBroadcastSignalRMessage signalRBroadcaster)
|
||||
: base(movieService, qualityUpgradableSpecification, signalRBroadcaster, "wanted/missing")
|
||||
{
|
||||
|
||||
|
||||
@@ -4,7 +4,7 @@
|
||||
<assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">
|
||||
<dependentAssembly>
|
||||
<assemblyIdentity name="Newtonsoft.Json" publicKeyToken="30ad4fe6b2a6aeed" culture="neutral" />
|
||||
<bindingRedirect oldVersion="0.0.0.0-6.0.0.0" newVersion="6.0.0.0" />
|
||||
<bindingRedirect oldVersion="0.0.0.0-9.0.0.0" newVersion="9.0.0.0" />
|
||||
</dependentAssembly>
|
||||
<dependentAssembly>
|
||||
<assemblyIdentity name="FluentMigrator" publicKeyToken="aacfc7de5acabf05" culture="neutral" />
|
||||
|
||||
@@ -5,6 +5,6 @@
|
||||
<package id="Nancy" version="1.4.3" targetFramework="net40" />
|
||||
<package id="Nancy.Authentication.Basic" version="1.4.1" targetFramework="net40" />
|
||||
<package id="Nancy.Authentication.Forms" version="1.4.1" targetFramework="net40" />
|
||||
<package id="Newtonsoft.Json" version="6.0.6" targetFramework="net40" />
|
||||
<package id="Newtonsoft.Json" version="9.0.1" targetFramework="net40" />
|
||||
<package id="NLog" version="4.5.0-rc06" targetFramework="net40" />
|
||||
</packages>
|
||||
@@ -4,7 +4,7 @@
|
||||
<assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">
|
||||
<dependentAssembly>
|
||||
<assemblyIdentity name="Newtonsoft.Json" publicKeyToken="30ad4fe6b2a6aeed" culture="neutral" />
|
||||
<bindingRedirect oldVersion="0.0.0.0-6.0.0.0" newVersion="6.0.0.0" />
|
||||
<bindingRedirect oldVersion="0.0.0.0-9.0.0.0" newVersion="9.0.0.0" />
|
||||
</dependentAssembly>
|
||||
<dependentAssembly>
|
||||
<assemblyIdentity name="FluentMigrator" publicKeyToken="aacfc7de5acabf05" culture="neutral" />
|
||||
|
||||
@@ -29,7 +29,7 @@ namespace NzbDrone.Common.Test
|
||||
[Test]
|
||||
public void IsProduction_should_return_false_when_run_within_nunit()
|
||||
{
|
||||
RuntimeInfoBase.IsProduction.Should().BeFalse("Process name is " + Process.GetCurrentProcess().ProcessName + " Folder is " + Directory.GetCurrentDirectory());
|
||||
RuntimeInfo.IsProduction.Should().BeFalse("Process name is " + Process.GetCurrentProcess().ProcessName + " Folder is " + Directory.GetCurrentDirectory());
|
||||
}
|
||||
|
||||
[Test]
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
using System;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Globalization;
|
||||
using System.IO;
|
||||
@@ -9,6 +9,7 @@ using Moq;
|
||||
using NLog;
|
||||
using NUnit.Framework;
|
||||
using NzbDrone.Common.Cache;
|
||||
using NzbDrone.Common.EnvironmentInfo;
|
||||
using NzbDrone.Common.Http;
|
||||
using NzbDrone.Common.Http.Dispatchers;
|
||||
using NzbDrone.Common.Http.Proxy;
|
||||
@@ -30,6 +31,12 @@ namespace NzbDrone.Common.Test.Http
|
||||
[SetUp]
|
||||
public void SetUp()
|
||||
{
|
||||
Mocker.GetMock<IPlatformInfo>().Setup(c => c.Version).Returns(new Version("1.0.0"));
|
||||
Mocker.GetMock<IOsInfo>().Setup(c => c.Name).Returns("TestOS");
|
||||
Mocker.GetMock<IOsInfo>().Setup(c => c.Version).Returns("9.0.0");
|
||||
|
||||
Mocker.SetConstant<IUserAgentBuilder>(Mocker.Resolve<UserAgentBuilder>());
|
||||
|
||||
Mocker.SetConstant<ICacheManager>(Mocker.Resolve<CacheManager>());
|
||||
Mocker.SetConstant<ICreateManagedWebProxy>(Mocker.Resolve<ManagedWebProxyFactory>());
|
||||
Mocker.SetConstant<IRateLimitService>(Mocker.Resolve<RateLimitService>());
|
||||
@@ -48,7 +55,7 @@ namespace NzbDrone.Common.Test.Http
|
||||
[Test]
|
||||
public void should_execute_simple_get()
|
||||
{
|
||||
var request = new HttpRequest(string.Format("http://{0}/get", _httpBinHost));
|
||||
var request = new HttpRequest($"http://{_httpBinHost}/get");
|
||||
|
||||
var response = Subject.Execute(request);
|
||||
|
||||
@@ -58,7 +65,7 @@ namespace NzbDrone.Common.Test.Http
|
||||
[Test]
|
||||
public void should_execute_https_get()
|
||||
{
|
||||
var request = new HttpRequest(string.Format("https://{0}/get", _httpBinHost));
|
||||
var request = new HttpRequest($"https://{_httpBinHost}/get");
|
||||
|
||||
var response = Subject.Execute(request);
|
||||
|
||||
@@ -68,11 +75,12 @@ namespace NzbDrone.Common.Test.Http
|
||||
[Test]
|
||||
public void should_execute_typed_get()
|
||||
{
|
||||
var request = new HttpRequest(string.Format("http://{0}/get", _httpBinHost));
|
||||
var request = new HttpRequest($"http://{_httpBinHost}/get?test=1");
|
||||
|
||||
var response = Subject.Get<HttpBinResource>(request);
|
||||
|
||||
response.Resource.Url.Should().Be(request.Url.FullUri);
|
||||
response.Resource.Url.EndsWith("/get?test=1");
|
||||
response.Resource.Args.Should().Contain("test", "1");
|
||||
}
|
||||
|
||||
[Test]
|
||||
@@ -80,7 +88,7 @@ namespace NzbDrone.Common.Test.Http
|
||||
{
|
||||
var message = "{ my: 1 }";
|
||||
|
||||
var request = new HttpRequest(string.Format("http://{0}/post", _httpBinHost));
|
||||
var request = new HttpRequest($"http://{_httpBinHost}/post");
|
||||
request.SetContent(message);
|
||||
|
||||
var response = Subject.Post<HttpBinResource>(request);
|
||||
@@ -91,7 +99,7 @@ namespace NzbDrone.Common.Test.Http
|
||||
[TestCase("gzip")]
|
||||
public void should_execute_get_using_gzip(string compression)
|
||||
{
|
||||
var request = new HttpRequest(string.Format("http://{0}/{1}", _httpBinHost, compression));
|
||||
var request = new HttpRequest($"http://{_httpBinHost}/{compression}");
|
||||
|
||||
var response = Subject.Get<HttpBinResource>(request);
|
||||
|
||||
@@ -107,7 +115,7 @@ namespace NzbDrone.Common.Test.Http
|
||||
[TestCase(HttpStatusCode.BadGateway)]
|
||||
public void should_throw_on_unsuccessful_status_codes(int statusCode)
|
||||
{
|
||||
var request = new HttpRequest(string.Format("http://{0}/status/{1}", _httpBinHost, statusCode));
|
||||
var request = new HttpRequest($"http://{_httpBinHost}/status/{statusCode}");
|
||||
|
||||
var exception = Assert.Throws<HttpException>(() => Subject.Get<HttpBinResource>(request));
|
||||
|
||||
@@ -119,7 +127,7 @@ namespace NzbDrone.Common.Test.Http
|
||||
[Test]
|
||||
public void should_not_follow_redirects_when_not_in_production()
|
||||
{
|
||||
var request = new HttpRequest(string.Format("http://{0}/redirect/1", _httpBinHost));
|
||||
var request = new HttpRequest($"http://{_httpBinHost}/redirect/1");
|
||||
|
||||
Subject.Get(request);
|
||||
|
||||
@@ -129,7 +137,7 @@ namespace NzbDrone.Common.Test.Http
|
||||
[Test]
|
||||
public void should_follow_redirects()
|
||||
{
|
||||
var request = new HttpRequest(string.Format("http://{0}/redirect/1", _httpBinHost));
|
||||
var request = new HttpRequest($"http://{_httpBinHost}/redirect/1");
|
||||
request.AllowAutoRedirect = true;
|
||||
|
||||
var response = Subject.Get(request);
|
||||
@@ -182,7 +190,7 @@ namespace NzbDrone.Common.Test.Http
|
||||
[Test]
|
||||
public void should_send_user_agent()
|
||||
{
|
||||
var request = new HttpRequest(string.Format("http://{0}/get", _httpBinHost));
|
||||
var request = new HttpRequest($"http://{_httpBinHost}/get");
|
||||
|
||||
var response = Subject.Get<HttpBinResource>(request);
|
||||
|
||||
@@ -196,7 +204,7 @@ namespace NzbDrone.Common.Test.Http
|
||||
[TestCase("Accept", "text/xml, text/rss+xml, application/rss+xml")]
|
||||
public void should_send_headers(string header, string value)
|
||||
{
|
||||
var request = new HttpRequest(string.Format("http://{0}/get", _httpBinHost));
|
||||
var request = new HttpRequest($"http://{_httpBinHost}/get");
|
||||
request.Headers.Add(header, value);
|
||||
|
||||
var response = Subject.Get<HttpBinResource>(request);
|
||||
@@ -219,7 +227,7 @@ namespace NzbDrone.Common.Test.Http
|
||||
[Test]
|
||||
public void should_send_cookie()
|
||||
{
|
||||
var request = new HttpRequest(string.Format("http://{0}/get", _httpBinHost));
|
||||
var request = new HttpRequest($"http://{_httpBinHost}/get");
|
||||
request.Cookies["my"] = "cookie";
|
||||
|
||||
var response = Subject.Get<HttpBinResource>(request);
|
||||
@@ -236,7 +244,7 @@ namespace NzbDrone.Common.Test.Http
|
||||
var oldRequest = new HttpRequest("http://eu.httpbin.org/get");
|
||||
oldRequest.Cookies["my"] = "cookie";
|
||||
|
||||
var oldClient = new HttpClient(new IHttpRequestInterceptor[0], Mocker.Resolve<ICacheManager>(), Mocker.Resolve<IRateLimitService>(), Mocker.Resolve<IHttpDispatcher>(), Mocker.Resolve<Logger>());
|
||||
var oldClient = new HttpClient(new IHttpRequestInterceptor[0], Mocker.Resolve<ICacheManager>(), Mocker.Resolve<IRateLimitService>(), Mocker.Resolve<IHttpDispatcher>(), Mocker.GetMock<IUserAgentBuilder>().Object, Mocker.Resolve<Logger>());
|
||||
|
||||
oldClient.Should().NotBeSameAs(Subject);
|
||||
|
||||
@@ -329,7 +337,7 @@ namespace NzbDrone.Common.Test.Http
|
||||
[Test]
|
||||
public void should_not_store_response_cookie()
|
||||
{
|
||||
var requestSet = new HttpRequest(string.Format("http://{0}/cookies/set?my=cookie", _httpBinHost));
|
||||
var requestSet = new HttpRequest($"http://{_httpBinHost}/cookies/set?my=cookie");
|
||||
requestSet.AllowAutoRedirect = false;
|
||||
requestSet.StoreRequestCookie = false;
|
||||
requestSet.StoreResponseCookie.Should().BeFalse();
|
||||
@@ -348,7 +356,7 @@ namespace NzbDrone.Common.Test.Http
|
||||
[Test]
|
||||
public void should_store_response_cookie()
|
||||
{
|
||||
var requestSet = new HttpRequest(string.Format("http://{0}/cookies/set?my=cookie", _httpBinHost));
|
||||
var requestSet = new HttpRequest($"http://{_httpBinHost}/cookies/set?my=cookie");
|
||||
requestSet.AllowAutoRedirect = false;
|
||||
requestSet.StoreRequestCookie = false;
|
||||
requestSet.StoreResponseCookie = true;
|
||||
@@ -514,7 +522,7 @@ namespace NzbDrone.Common.Test.Http
|
||||
public void should_not_send_old_cookie()
|
||||
{
|
||||
GivenOldCookie();
|
||||
|
||||
|
||||
var requestCookies = new HttpRequest($"http://{_httpBinHost}/cookies");
|
||||
requestCookies.IgnorePersistentCookies = true;
|
||||
requestCookies.StoreRequestCookie = false;
|
||||
@@ -527,7 +535,7 @@ namespace NzbDrone.Common.Test.Http
|
||||
[Test]
|
||||
public void should_throw_on_http429_too_many_requests()
|
||||
{
|
||||
var request = new HttpRequest(string.Format("http://{0}/status/429", _httpBinHost));
|
||||
var request = new HttpRequest($"http://{_httpBinHost}/status/429");
|
||||
|
||||
Assert.Throws<TooManyRequestsException>(() => Subject.Get(request));
|
||||
|
||||
@@ -547,7 +555,7 @@ namespace NzbDrone.Common.Test.Http
|
||||
.Setup(v => v.PostResponse(It.IsAny<HttpResponse>()))
|
||||
.Returns<HttpResponse>(r => r);
|
||||
|
||||
var request = new HttpRequest(string.Format("http://{0}/get", _httpBinHost));
|
||||
var request = new HttpRequest($"http://{_httpBinHost}/get");
|
||||
|
||||
Subject.Get(request);
|
||||
|
||||
@@ -569,7 +577,7 @@ namespace NzbDrone.Common.Test.Http
|
||||
{
|
||||
// the date is bad in the below - should be 13-Jul-2026
|
||||
string malformedCookie = @"__cfduid=d29e686a9d65800021c66faca0a29b4261436890790; expires=Mon, 13-Jul-26 16:19:50 GMT; path=/; HttpOnly";
|
||||
var requestSet = new HttpRequestBuilder(string.Format("http://{0}/response-headers", _httpBinHost))
|
||||
var requestSet = new HttpRequestBuilder($"http://{_httpBinHost}/response-headers")
|
||||
.AddQueryParam("Set-Cookie", malformedCookie)
|
||||
.Build();
|
||||
|
||||
@@ -578,7 +586,7 @@ namespace NzbDrone.Common.Test.Http
|
||||
|
||||
var responseSet = Subject.Get(requestSet);
|
||||
|
||||
var request = new HttpRequest(string.Format("http://{0}/get", _httpBinHost));
|
||||
var request = new HttpRequest($"http://{_httpBinHost}/get");
|
||||
|
||||
var response = Subject.Get<HttpBinResource>(request);
|
||||
|
||||
@@ -602,7 +610,8 @@ namespace NzbDrone.Common.Test.Http
|
||||
{
|
||||
try
|
||||
{
|
||||
string url = string.Format("http://{0}/response-headers?Set-Cookie={1}", _httpBinHost, Uri.EscapeUriString(malformedCookie));
|
||||
string url =
|
||||
$"http://{_httpBinHost}/response-headers?Set-Cookie={Uri.EscapeUriString(malformedCookie)}";
|
||||
|
||||
var requestSet = new HttpRequest(url);
|
||||
requestSet.AllowAutoRedirect = false;
|
||||
@@ -610,7 +619,7 @@ namespace NzbDrone.Common.Test.Http
|
||||
|
||||
var responseSet = Subject.Get(requestSet);
|
||||
|
||||
var request = new HttpRequest(string.Format("http://{0}/get", _httpBinHost));
|
||||
var request = new HttpRequest($"http://{_httpBinHost}/get");
|
||||
|
||||
var response = Subject.Get<HttpBinResource>(request);
|
||||
|
||||
@@ -626,6 +635,7 @@ namespace NzbDrone.Common.Test.Http
|
||||
|
||||
public class HttpBinResource
|
||||
{
|
||||
public Dictionary<string, object> Args { get; set; }
|
||||
public Dictionary<string, object> Headers { get; set; }
|
||||
public string Origin { get; set; }
|
||||
public string Url { get; set; }
|
||||
|
||||
30
src/NzbDrone.Common.Test/Http/UserAgentBuilderFixture.cs
Normal file
30
src/NzbDrone.Common.Test/Http/UserAgentBuilderFixture.cs
Normal file
@@ -0,0 +1,30 @@
|
||||
using FluentAssertions;
|
||||
using NUnit.Framework;
|
||||
using NzbDrone.Common.EnvironmentInfo;
|
||||
using NzbDrone.Common.Http;
|
||||
using NzbDrone.Test.Common;
|
||||
|
||||
namespace NzbDrone.Common.Test.Http
|
||||
{
|
||||
[TestFixture]
|
||||
public class UserAgentBuilderFixture : TestBase<UserAgentBuilder>
|
||||
{
|
||||
[Test]
|
||||
public void should_get_user_agent_if_os_version_is_null()
|
||||
{
|
||||
Mocker.GetMock<IOsInfo>().SetupGet(c => c.Version).Returns((string)null);
|
||||
Mocker.GetMock<IOsInfo>().SetupGet(c => c.Name).Returns("TestOS");
|
||||
|
||||
Subject.GetUserAgent(false).Should().NotBeNullOrWhiteSpace();
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void should_get_use_os_family_if_name_is_null()
|
||||
{
|
||||
Mocker.GetMock<IOsInfo>().SetupGet(c => c.Version).Returns((string)null);
|
||||
Mocker.GetMock<IOsInfo>().SetupGet(c => c.Name).Returns((string)null);
|
||||
|
||||
Subject.GetUserAgent(false).Should().NotBeNullOrWhiteSpace();
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -91,6 +91,7 @@
|
||||
<Compile Include="Http\HttpRequestBuilderFixture.cs" />
|
||||
<Compile Include="Http\HttpRequestFixture.cs" />
|
||||
<Compile Include="Http\HttpUriFixture.cs" />
|
||||
<Compile Include="Http\UserAgentBuilderFixture.cs" />
|
||||
<Compile Include="InstrumentationTests\CleanseLogMessageFixture.cs" />
|
||||
<Compile Include="LevenshteinDistanceFixture.cs" />
|
||||
<Compile Include="OsPathFixture.cs" />
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
using System;
|
||||
using System;
|
||||
using System.IO;
|
||||
using FluentAssertions;
|
||||
using Moq;
|
||||
@@ -257,13 +257,13 @@ namespace NzbDrone.Common.Test
|
||||
[Test]
|
||||
public void GetUpdateClientFolder()
|
||||
{
|
||||
GetIAppDirectoryInfo().GetUpdateClientFolder().Should().BeEquivalentTo(@"C:\Temp\radarr_update\Radarr\NzbDrone.Update\".AsOsAgnostic());
|
||||
GetIAppDirectoryInfo().GetUpdateClientFolder(new Version("0.2.0.1480")).Should().BeEquivalentTo(@"C:\Temp\radarr_update\Radarr\NzbDrone.Update\".AsOsAgnostic());
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void GetUpdateClientExePath()
|
||||
{
|
||||
GetIAppDirectoryInfo().GetUpdateClientExePath().Should().BeEquivalentTo(@"C:\Temp\radarr_update\Radarr.Update.exe".AsOsAgnostic());
|
||||
GetIAppDirectoryInfo().GetUpdateClientExePath(new Version("0.2.0.1480")).Should().BeEquivalentTo(@"C:\Temp\radarr_update\Radarr.Update.exe".AsOsAgnostic());
|
||||
}
|
||||
|
||||
[Test]
|
||||
|
||||
@@ -13,7 +13,7 @@ namespace NzbDrone.Common.Cloud
|
||||
{
|
||||
public RadarrCloudRequestBuilder()
|
||||
{
|
||||
Services = new HttpRequestBuilder("https://radarr.aeonlucid.com/v1/")
|
||||
Services = new HttpRequestBuilder("https://radarr.lidarr.audio/v1/")
|
||||
.CreateFactory();
|
||||
|
||||
TMDB = new HttpRequestBuilder("https://api.themoviedb.org/3/{route}/{id}{secondaryRoute}")
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
using System;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Reflection;
|
||||
@@ -13,12 +13,15 @@ namespace NzbDrone.Common.Composition
|
||||
{
|
||||
private readonly List<Type> _loadedTypes;
|
||||
|
||||
public IContainer Container { get; private set; }
|
||||
protected IContainer Container { get; }
|
||||
|
||||
protected ContainerBuilderBase(IStartupContext args, params string[] assemblies)
|
||||
protected ContainerBuilderBase(IStartupContext args, List<string> assemblies)
|
||||
{
|
||||
_loadedTypes = new List<Type>();
|
||||
|
||||
assemblies.Add(OsInfo.IsWindows ? "NzbDrone.Windows" : "NzbDrone.Mono");
|
||||
assemblies.Add("NzbDrone.Common");
|
||||
|
||||
foreach (var assembly in assemblies)
|
||||
{
|
||||
_loadedTypes.AddRange(Assembly.Load(assembly).GetTypes());
|
||||
|
||||
@@ -17,6 +17,19 @@ namespace NzbDrone.Common.Disk
|
||||
{
|
||||
private static readonly Logger Logger = NzbDroneLogger.GetLogger(typeof(DiskProviderBase));
|
||||
|
||||
public static StringComparison PathStringComparison
|
||||
{
|
||||
get
|
||||
{
|
||||
if (OsInfo.IsWindows)
|
||||
{
|
||||
return StringComparison.OrdinalIgnoreCase;
|
||||
}
|
||||
|
||||
return StringComparison.Ordinal;
|
||||
}
|
||||
}
|
||||
|
||||
public abstract long? GetAvailableSpace(string path);
|
||||
public abstract void InheritFolderPermissions(string filename);
|
||||
public abstract void SetPermissions(string path, string mask, string user, string group);
|
||||
@@ -87,7 +100,7 @@ namespace NzbDrone.Common.Disk
|
||||
public bool FileExists(string path)
|
||||
{
|
||||
Ensure.That(path, () => path).IsValidPath();
|
||||
return FileExists(path, OsInfo.PathStringComparison);
|
||||
return FileExists(path, PathStringComparison);
|
||||
}
|
||||
|
||||
public bool FileExists(string path, StringComparison stringComparison)
|
||||
|
||||
@@ -45,7 +45,8 @@ namespace NzbDrone.Common.Disk
|
||||
".@__thumb",
|
||||
|
||||
// Synology
|
||||
"@eadir"
|
||||
"@eadir",
|
||||
"#recycle"
|
||||
};
|
||||
|
||||
public FileSystemLookupService(IDiskProvider diskProvider, Logger logger)
|
||||
|
||||
@@ -101,12 +101,12 @@ namespace NzbDrone.Common.EnsureThat
|
||||
|
||||
if (param.Value.IsPathValid()) return param;
|
||||
|
||||
if (OsInfo.IsNotWindows)
|
||||
if (OsInfo.IsWindows)
|
||||
{
|
||||
throw ExceptionFactory.CreateForParamValidation(param.Name, string.Format("value [{0}] is not a valid *nix path. paths must start with /", param.Value));
|
||||
throw ExceptionFactory.CreateForParamValidation(param.Name, string.Format("value [{0}] is not a valid Windows path. paths must be a full path eg. C:\\Windows", param.Value));
|
||||
}
|
||||
|
||||
throw ExceptionFactory.CreateForParamValidation(param.Name, string.Format("value [{0}] is not a valid Windows path. paths must be a full path eg. C:\\Windows", param.Value));
|
||||
throw ExceptionFactory.CreateForParamValidation(param.Name, string.Format("value [{0}] is not a valid *nix path. paths must start with /", param.Value));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,8 +1,9 @@
|
||||
using System;
|
||||
using System;
|
||||
using System.Security.AccessControl;
|
||||
using System.Security.Principal;
|
||||
using NLog;
|
||||
using NzbDrone.Common.Disk;
|
||||
using NzbDrone.Common.Exceptions;
|
||||
using NzbDrone.Common.Instrumentation;
|
||||
|
||||
namespace NzbDrone.Common.EnvironmentInfo
|
||||
@@ -27,12 +28,24 @@ namespace NzbDrone.Common.EnvironmentInfo
|
||||
|
||||
public void Register()
|
||||
{
|
||||
_diskProvider.EnsureFolder(_appFolderInfo.AppDataFolder);
|
||||
try
|
||||
{
|
||||
_diskProvider.EnsureFolder(_appFolderInfo.AppDataFolder);
|
||||
}
|
||||
catch (UnauthorizedAccessException)
|
||||
{
|
||||
throw new RadarrStartupException("Cannot create AppFolder, Access to the path {0} is denied", _appFolderInfo.AppDataFolder);
|
||||
}
|
||||
|
||||
if (OsInfo.IsWindows)
|
||||
{
|
||||
SetPermissions();
|
||||
}
|
||||
|
||||
if (!_diskProvider.FolderWritable(_appFolderInfo.AppDataFolder))
|
||||
{
|
||||
throw new RadarrStartupException("AppFolder {0} is not writable", _appFolderInfo.AppDataFolder);
|
||||
}
|
||||
}
|
||||
|
||||
private void SetPermissions()
|
||||
|
||||
@@ -1,12 +1,34 @@
|
||||
using System;
|
||||
using System;
|
||||
using System.IO;
|
||||
using System.Linq;
|
||||
using System.Reflection;
|
||||
|
||||
namespace NzbDrone.Common.EnvironmentInfo
|
||||
{
|
||||
public static class BuildInfo
|
||||
{
|
||||
public static Version Version => Assembly.GetExecutingAssembly().GetName().Version;
|
||||
static BuildInfo()
|
||||
{
|
||||
var assembly = Assembly.GetExecutingAssembly();
|
||||
|
||||
Version = assembly.GetName().Version;
|
||||
|
||||
var attributes = assembly.GetCustomAttributes(true);
|
||||
|
||||
Branch = "unknow";
|
||||
|
||||
var config = attributes.OfType<AssemblyConfigurationAttribute>().FirstOrDefault();
|
||||
if (config != null)
|
||||
{
|
||||
Branch = config.Configuration;
|
||||
}
|
||||
|
||||
Release = $"{Version}-{Branch}";
|
||||
}
|
||||
|
||||
public static Version Version { get; }
|
||||
public static String Branch { get; }
|
||||
public static string Release { get; }
|
||||
|
||||
public static DateTime BuildDateTime
|
||||
{
|
||||
@@ -29,4 +51,4 @@ namespace NzbDrone.Common.EnvironmentInfo
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,9 @@
|
||||
namespace NzbDrone.Common.EnvironmentInfo
|
||||
{
|
||||
public interface IOperatingSystemVersionInfo
|
||||
{
|
||||
string Version { get; }
|
||||
string Name { get; }
|
||||
string FullName { get; }
|
||||
}
|
||||
}
|
||||
9
src/NzbDrone.Common/EnvironmentInfo/IOsVersionAdapter.cs
Normal file
9
src/NzbDrone.Common/EnvironmentInfo/IOsVersionAdapter.cs
Normal file
@@ -0,0 +1,9 @@
|
||||
namespace NzbDrone.Common.EnvironmentInfo
|
||||
{
|
||||
|
||||
public interface IOsVersionAdapter
|
||||
{
|
||||
bool Enabled { get; }
|
||||
OsVersionModel Read();
|
||||
}
|
||||
}
|
||||
50
src/NzbDrone.Common/EnvironmentInfo/IPlatformInfo.cs
Normal file
50
src/NzbDrone.Common/EnvironmentInfo/IPlatformInfo.cs
Normal file
@@ -0,0 +1,50 @@
|
||||
using System;
|
||||
|
||||
namespace NzbDrone.Common.EnvironmentInfo
|
||||
{
|
||||
|
||||
public enum PlatformType
|
||||
{
|
||||
DotNet = 0,
|
||||
Mono = 1
|
||||
}
|
||||
|
||||
public interface IPlatformInfo
|
||||
{
|
||||
Version Version { get; }
|
||||
}
|
||||
|
||||
public abstract class PlatformInfo : IPlatformInfo
|
||||
{
|
||||
static PlatformInfo()
|
||||
{
|
||||
if (Type.GetType("Mono.Runtime") != null)
|
||||
{
|
||||
Platform = PlatformType.Mono;
|
||||
}
|
||||
else
|
||||
{
|
||||
Platform = PlatformType.DotNet;
|
||||
}
|
||||
}
|
||||
|
||||
public static PlatformType Platform { get; }
|
||||
public static bool IsMono => Platform == PlatformType.Mono;
|
||||
public static bool IsDotNet => Platform == PlatformType.DotNet;
|
||||
|
||||
public static string PlatformName
|
||||
{
|
||||
get
|
||||
{
|
||||
if (IsDotNet)
|
||||
{
|
||||
return ".NET";
|
||||
}
|
||||
|
||||
return "Mono";
|
||||
}
|
||||
}
|
||||
|
||||
public abstract Version Version { get; }
|
||||
}
|
||||
}
|
||||
@@ -1,14 +1,13 @@
|
||||
namespace NzbDrone.Common.EnvironmentInfo
|
||||
namespace NzbDrone.Common.EnvironmentInfo
|
||||
{
|
||||
public interface IRuntimeInfo
|
||||
{
|
||||
bool IsUserInteractive { get; }
|
||||
bool IsAdmin { get; }
|
||||
bool IsWindowsService { get; }
|
||||
bool IsConsole { get; }
|
||||
bool IsRunning { get; set; }
|
||||
bool IsWindowsTray { get; }
|
||||
bool IsExiting { get; set; }
|
||||
bool RestartPending { get; set; }
|
||||
string ExecutingApplication { get; }
|
||||
string RuntimeVersion { get; }
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,87 +1,95 @@
|
||||
using System;
|
||||
using System.Diagnostics;
|
||||
using System.Globalization;
|
||||
using System.Runtime.InteropServices;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.IO;
|
||||
using System.Linq;
|
||||
using NLog;
|
||||
|
||||
namespace NzbDrone.Common.EnvironmentInfo
|
||||
{
|
||||
public static class OsInfo
|
||||
public class OsInfo : IOsInfo
|
||||
{
|
||||
public static Os Os { get; }
|
||||
|
||||
public static bool IsNotWindows => !IsWindows;
|
||||
public static bool IsLinux => Os == Os.Linux;
|
||||
public static bool IsOsx => Os == Os.Osx;
|
||||
public static bool IsWindows => Os == Os.Windows;
|
||||
|
||||
public string Version { get; }
|
||||
public string Name { get; }
|
||||
public string FullName { get; }
|
||||
|
||||
static OsInfo()
|
||||
{
|
||||
var platform = (int)Environment.OSVersion.Platform;
|
||||
var platform = Environment.OSVersion.Platform;
|
||||
|
||||
Version = Environment.OSVersion.Version;
|
||||
|
||||
IsMonoRuntime = Type.GetType("Mono.Runtime") != null;
|
||||
IsNotWindows = (platform == 4) || (platform == 6) || (platform == 128);
|
||||
IsOsx = IsRunningOnMac();
|
||||
IsLinux = IsNotWindows && !IsOsx;
|
||||
IsWindows = !IsNotWindows;
|
||||
|
||||
FirstDayOfWeek = CultureInfo.CurrentCulture.DateTimeFormat.FirstDayOfWeek;
|
||||
|
||||
if (IsWindows)
|
||||
switch (platform)
|
||||
{
|
||||
Os = Os.Windows;
|
||||
PathStringComparison = StringComparison.OrdinalIgnoreCase;
|
||||
case PlatformID.Win32NT:
|
||||
{
|
||||
Os = Os.Windows;
|
||||
break;
|
||||
}
|
||||
case PlatformID.MacOSX:
|
||||
case PlatformID.Unix:
|
||||
{
|
||||
// Sometimes Mac OS reports itself as Unix
|
||||
if (Directory.Exists("/System/Library/CoreServices/") &&
|
||||
(File.Exists("/System/Library/CoreServices/SystemVersion.plist") ||
|
||||
File.Exists("/System/Library/CoreServices/ServerVersion.plist"))
|
||||
)
|
||||
{
|
||||
Os = Os.Osx;
|
||||
}
|
||||
else
|
||||
{
|
||||
Os = Os.Linux;
|
||||
}
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public OsInfo(IEnumerable<IOsVersionAdapter> versionAdapters, Logger logger)
|
||||
{
|
||||
OsVersionModel osInfo = null;
|
||||
|
||||
foreach (var osVersionAdapter in versionAdapters.Where(c => c.Enabled))
|
||||
{
|
||||
try
|
||||
{
|
||||
osInfo = osVersionAdapter.Read();
|
||||
}
|
||||
catch (Exception e)
|
||||
{
|
||||
logger.Error(e, "Couldn't get OS Version info");
|
||||
}
|
||||
|
||||
if (osInfo != null)
|
||||
{
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
if (osInfo != null)
|
||||
{
|
||||
Name = osInfo.Name;
|
||||
Version = osInfo.Version;
|
||||
FullName = osInfo.FullName;
|
||||
}
|
||||
else
|
||||
{
|
||||
Os = IsOsx ? Os.Osx : Os.Linux;
|
||||
|
||||
PathStringComparison = StringComparison.Ordinal;
|
||||
Name = Os.ToString();
|
||||
FullName = Name;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public static Version Version { get; private set; }
|
||||
public static bool IsMonoRuntime { get; private set; }
|
||||
public static bool IsNotWindows { get; private set; }
|
||||
public static bool IsLinux { get; private set; }
|
||||
public static bool IsOsx { get; private set; }
|
||||
public static bool IsWindows { get; private set; }
|
||||
public static Os Os { get; private set; }
|
||||
public static DayOfWeek FirstDayOfWeek { get; private set; }
|
||||
public static StringComparison PathStringComparison { get; private set; }
|
||||
|
||||
//Borrowed from: https://github.com/jpobst/Pinta/blob/master/Pinta.Core/Managers/SystemManager.cs
|
||||
//From Managed.Windows.Forms/XplatUI
|
||||
[DllImport("libc")]
|
||||
static extern int uname(IntPtr buf);
|
||||
|
||||
[DebuggerStepThrough]
|
||||
static bool IsRunningOnMac()
|
||||
{
|
||||
var buf = IntPtr.Zero;
|
||||
|
||||
try
|
||||
{
|
||||
buf = Marshal.AllocHGlobal(8192);
|
||||
// This is a hacktastic way of getting sysname from uname ()
|
||||
if (uname(buf) == 0)
|
||||
{
|
||||
var os = Marshal.PtrToStringAnsi(buf);
|
||||
|
||||
if (os == "Darwin")
|
||||
{
|
||||
return true;
|
||||
}
|
||||
}
|
||||
}
|
||||
catch
|
||||
{
|
||||
}
|
||||
finally
|
||||
{
|
||||
if (buf != IntPtr.Zero)
|
||||
{
|
||||
Marshal.FreeHGlobal(buf);
|
||||
}
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
public interface IOsInfo
|
||||
{
|
||||
string Version { get; }
|
||||
string Name { get; }
|
||||
string FullName { get; }
|
||||
}
|
||||
|
||||
public enum Os
|
||||
@@ -90,4 +98,4 @@ namespace NzbDrone.Common.EnvironmentInfo
|
||||
Linux,
|
||||
Osx
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
29
src/NzbDrone.Common/EnvironmentInfo/OsVersionModel.cs
Normal file
29
src/NzbDrone.Common/EnvironmentInfo/OsVersionModel.cs
Normal file
@@ -0,0 +1,29 @@
|
||||
namespace NzbDrone.Common.EnvironmentInfo
|
||||
{
|
||||
public class OsVersionModel
|
||||
{
|
||||
|
||||
|
||||
public OsVersionModel(string name, string version, string fullName = null)
|
||||
{
|
||||
Name = Trim(name);
|
||||
Version = Trim(version);
|
||||
|
||||
if (string.IsNullOrWhiteSpace(fullName))
|
||||
{
|
||||
fullName = $"{Name} {Version}";
|
||||
}
|
||||
|
||||
FullName = Trim(fullName);
|
||||
}
|
||||
|
||||
private static string Trim(string source)
|
||||
{
|
||||
return source.Trim().Trim('"', '\'');
|
||||
}
|
||||
|
||||
public string Name { get; }
|
||||
public string FullName { get; }
|
||||
public string Version { get; }
|
||||
}
|
||||
}
|
||||
@@ -1,4 +1,4 @@
|
||||
using System;
|
||||
using System;
|
||||
using System.Diagnostics;
|
||||
using System.IO;
|
||||
using System.Reflection;
|
||||
@@ -9,11 +9,11 @@ using NzbDrone.Common.Processes;
|
||||
|
||||
namespace NzbDrone.Common.EnvironmentInfo
|
||||
{
|
||||
public abstract class RuntimeInfoBase : IRuntimeInfo
|
||||
public class RuntimeInfo : IRuntimeInfo
|
||||
{
|
||||
private readonly Logger _logger;
|
||||
|
||||
public RuntimeInfoBase(IServiceProvider serviceProvider, Logger logger)
|
||||
public RuntimeInfo(IServiceProvider serviceProvider, Logger logger)
|
||||
{
|
||||
_logger = logger;
|
||||
|
||||
@@ -28,10 +28,11 @@ namespace NzbDrone.Common.EnvironmentInfo
|
||||
if (entry != null)
|
||||
{
|
||||
ExecutingApplication = entry.Location;
|
||||
IsWindowsTray = entry.ManifestModule.Name == $"{ProcessProvider.NZB_DRONE_PROCESS_NAME}.exe";
|
||||
}
|
||||
}
|
||||
|
||||
static RuntimeInfoBase()
|
||||
static RuntimeInfo()
|
||||
{
|
||||
IsProduction = InternalIsProduction();
|
||||
}
|
||||
@@ -59,31 +60,18 @@ namespace NzbDrone.Common.EnvironmentInfo
|
||||
|
||||
public bool IsWindowsService { get; private set; }
|
||||
|
||||
public bool IsConsole
|
||||
{
|
||||
get
|
||||
{
|
||||
if (OsInfo.IsWindows)
|
||||
{
|
||||
return IsUserInteractive && Process.GetCurrentProcess().ProcessName.Equals(ProcessProvider.NZB_DRONE_CONSOLE_PROCESS_NAME, StringComparison.InvariantCultureIgnoreCase);
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
public bool IsRunning { get; set; }
|
||||
public bool IsExiting { get; set; }
|
||||
public bool RestartPending { get; set; }
|
||||
public string ExecutingApplication { get; private set; }
|
||||
public string ExecutingApplication { get; }
|
||||
|
||||
public abstract string RuntimeVersion { get; }
|
||||
|
||||
public static bool IsProduction { get; private set; }
|
||||
public static bool IsProduction { get; }
|
||||
|
||||
private static bool InternalIsProduction()
|
||||
{
|
||||
if (BuildInfo.IsDebug || Debugger.IsAttached) return false;
|
||||
if (BuildInfo.Version.Revision > 10000) return false; //Official builds will never have such a high revision
|
||||
|
||||
//Official builds will never have such a high revision
|
||||
if (BuildInfo.Version.Revision > 10000) return false;
|
||||
|
||||
try
|
||||
{
|
||||
@@ -99,21 +87,23 @@ namespace NzbDrone.Common.EnvironmentInfo
|
||||
|
||||
}
|
||||
|
||||
try
|
||||
{
|
||||
var currentAssmeblyLocation = typeof(RuntimeInfoBase).Assembly.Location;
|
||||
if(currentAssmeblyLocation.ToLower().Contains("_output"))return false;
|
||||
}
|
||||
catch
|
||||
{
|
||||
try
|
||||
{
|
||||
var currentAssmeblyLocation = typeof(RuntimeInfo).Assembly.Location;
|
||||
if (currentAssmeblyLocation.ToLower().Contains("_output")) return false;
|
||||
}
|
||||
catch
|
||||
{
|
||||
|
||||
}
|
||||
}
|
||||
|
||||
string lowerCurrentDir = Directory.GetCurrentDirectory().ToLower();
|
||||
var lowerCurrentDir = Directory.GetCurrentDirectory().ToLower();
|
||||
if (lowerCurrentDir.Contains("teamcity")) return false;
|
||||
if (lowerCurrentDir.Contains("_output")) return false;
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
public bool IsWindowsTray { get; private set; }
|
||||
}
|
||||
}
|
||||
37
src/NzbDrone.Common/Exceptions/RadarrStartupException.cs
Normal file
37
src/NzbDrone.Common/Exceptions/RadarrStartupException.cs
Normal file
@@ -0,0 +1,37 @@
|
||||
using System;
|
||||
|
||||
namespace NzbDrone.Common.Exceptions
|
||||
{
|
||||
public class RadarrStartupException : NzbDroneException
|
||||
{
|
||||
public RadarrStartupException(string message, params object[] args)
|
||||
: base("Radarr failed to start: " + string.Format(message, args))
|
||||
{
|
||||
}
|
||||
|
||||
public RadarrStartupException(string message)
|
||||
: base("Radarr failed to start: " + message)
|
||||
{
|
||||
}
|
||||
|
||||
public RadarrStartupException()
|
||||
: base("Radarr failed to start")
|
||||
{
|
||||
}
|
||||
|
||||
public RadarrStartupException(Exception innerException, string message, params object[] args)
|
||||
: base("Radarr failed to start: " + string.Format(message, args), innerException)
|
||||
{
|
||||
}
|
||||
|
||||
public RadarrStartupException(Exception innerException, string message)
|
||||
: base("Radarr failed to start: " + message, innerException)
|
||||
{
|
||||
}
|
||||
|
||||
public RadarrStartupException(Exception innerException)
|
||||
: base("Radarr failed to start: " + innerException.Message)
|
||||
{
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,31 +0,0 @@
|
||||
using System;
|
||||
using NzbDrone.Common.EnvironmentInfo;
|
||||
|
||||
namespace NzbDrone.Common.Exceptron
|
||||
{
|
||||
public static class ExceptionExtentions
|
||||
{
|
||||
private const string IGNORE_FLAG = "exceptron_ignore";
|
||||
|
||||
public static Exception ExceptronIgnoreOnMono(this Exception exception)
|
||||
{
|
||||
if (OsInfo.IsNotWindows)
|
||||
{
|
||||
exception.ExceptronIgnore();
|
||||
}
|
||||
|
||||
return exception;
|
||||
}
|
||||
|
||||
public static Exception ExceptronIgnore(this Exception exception)
|
||||
{
|
||||
exception.Data.Add(IGNORE_FLAG, true);
|
||||
return exception;
|
||||
}
|
||||
|
||||
public static bool ExceptronShouldIgnore(this Exception exception)
|
||||
{
|
||||
return exception.Data.Contains(IGNORE_FLAG);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,7 +1,8 @@
|
||||
using System;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.IO;
|
||||
using System.Text.RegularExpressions;
|
||||
using NzbDrone.Common.Disk;
|
||||
using NzbDrone.Common.EnsureThat;
|
||||
using NzbDrone.Common.EnvironmentInfo;
|
||||
|
||||
@@ -13,7 +14,7 @@ namespace NzbDrone.Common.Extensions
|
||||
private const string NZBDRONE_DB = "nzbdrone.db";
|
||||
private const string NZBDRONE_LOG_DB = "logs.db";
|
||||
private const string NLOG_CONFIG_FILE = "nlog.config";
|
||||
private const string UPDATE_CLIENT_EXE = "Radarr.Update.exe";
|
||||
private const string UPDATE_CLIENT_EXE_NAME = "Radarr.Update";
|
||||
private const string BACKUP_FOLDER = "Backups";
|
||||
|
||||
private static readonly string UPDATE_SANDBOX_FOLDER_NAME = "radarr_update" + Path.DirectorySeparatorChar;
|
||||
@@ -21,6 +22,7 @@ namespace NzbDrone.Common.Extensions
|
||||
private static readonly string UPDATE_BACKUP_FOLDER_NAME = "radarr_backup" + Path.DirectorySeparatorChar;
|
||||
private static readonly string UPDATE_BACKUP_APPDATA_FOLDER_NAME = "radarr_appdata_backup" + Path.DirectorySeparatorChar;
|
||||
private static readonly string UPDATE_CLIENT_FOLDER_NAME = "NzbDrone.Update" + Path.DirectorySeparatorChar;
|
||||
private static readonly string UPDATE_V3_CLIENT_FOLDER_NAME = "Radarr.Update" + Path.DirectorySeparatorChar;
|
||||
private static readonly string UPDATE_LOG_FOLDER_NAME = "UpdateLogs" + Path.DirectorySeparatorChar;
|
||||
|
||||
public static string CleanFilePath(this string path)
|
||||
@@ -47,7 +49,7 @@ namespace NzbDrone.Common.Extensions
|
||||
{
|
||||
if (!comparison.HasValue)
|
||||
{
|
||||
comparison = OsInfo.PathStringComparison;
|
||||
comparison = DiskProviderBase.PathStringComparison;
|
||||
}
|
||||
|
||||
if (firstPath.Equals(secondPath, comparison.Value)) return true;
|
||||
@@ -93,7 +95,7 @@ namespace NzbDrone.Common.Extensions
|
||||
|
||||
while (child.Parent != null)
|
||||
{
|
||||
if (child.Parent.FullName.Equals(parent.FullName, OsInfo.PathStringComparison))
|
||||
if (child.Parent.FullName.Equals(parent.FullName, DiskProviderBase.PathStringComparison))
|
||||
{
|
||||
return true;
|
||||
}
|
||||
@@ -190,6 +192,19 @@ namespace NzbDrone.Common.Extensions
|
||||
return directories;
|
||||
}
|
||||
|
||||
private static string ProcessNameToExe(this string processName, Version version)
|
||||
{
|
||||
// Windows always has exe (but is shunted to net core)
|
||||
// Linux is kept on mono pending manual upgrade to net core so has .exe
|
||||
// macOS is shunted to net core and does not have .exe
|
||||
if (OsInfo.IsWindows || OsInfo.IsLinux || version.Major == 0)
|
||||
{
|
||||
processName += ".exe";
|
||||
}
|
||||
|
||||
return processName;
|
||||
}
|
||||
|
||||
public static string GetAppDataPath(this IAppFolderInfo appFolderInfo)
|
||||
{
|
||||
return appFolderInfo.AppDataFolder;
|
||||
@@ -245,14 +260,21 @@ namespace NzbDrone.Common.Extensions
|
||||
return Path.Combine(GetUpdateSandboxFolder(appFolderInfo), UPDATE_PACKAGE_FOLDER_NAME);
|
||||
}
|
||||
|
||||
public static string GetUpdateClientFolder(this IAppFolderInfo appFolderInfo)
|
||||
public static string GetUpdateClientFolder(this IAppFolderInfo appFolderInfo, Version version)
|
||||
{
|
||||
return Path.Combine(GetUpdatePackageFolder(appFolderInfo), UPDATE_CLIENT_FOLDER_NAME);
|
||||
if (version.Major >= 3)
|
||||
{
|
||||
return Path.Combine(GetUpdatePackageFolder(appFolderInfo), UPDATE_V3_CLIENT_FOLDER_NAME);
|
||||
}
|
||||
else
|
||||
{
|
||||
return Path.Combine(GetUpdatePackageFolder(appFolderInfo), UPDATE_CLIENT_FOLDER_NAME);
|
||||
}
|
||||
}
|
||||
|
||||
public static string GetUpdateClientExePath(this IAppFolderInfo appFolderInfo)
|
||||
public static string GetUpdateClientExePath(this IAppFolderInfo appFolderInfo, Version version)
|
||||
{
|
||||
return Path.Combine(GetUpdateSandboxFolder(appFolderInfo), UPDATE_CLIENT_EXE);
|
||||
return Path.Combine(GetUpdateSandboxFolder(appFolderInfo), UPDATE_CLIENT_EXE_NAME).ProcessNameToExe(version);
|
||||
}
|
||||
|
||||
public static string GetBackupFolder(this IAppFolderInfo appFolderInfo)
|
||||
@@ -275,4 +297,4 @@ namespace NzbDrone.Common.Extensions
|
||||
return Path.Combine(appFolderInfo.StartUpFolder, NLOG_CONFIG_FILE);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
using System;
|
||||
using System;
|
||||
using System.Text;
|
||||
|
||||
namespace NzbDrone.Common
|
||||
@@ -26,5 +26,11 @@ namespace NzbDrone.Common
|
||||
}
|
||||
return string.Format("{0:x8}", mCrc);
|
||||
}
|
||||
|
||||
public static string AnonymousToken()
|
||||
{
|
||||
var seed = $"{Environment.ProcessorCount}_{Environment.OSVersion.Platform}_{Environment.MachineName}_{Environment.UserName}";
|
||||
return HashUtil.CalculateCrc(seed);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -21,6 +21,7 @@ namespace NzbDrone.Common.Http.Dispatchers
|
||||
private static readonly Regex ExpiryDate = new Regex(@"(expires=)([^;]+)", RegexOptions.IgnoreCase | RegexOptions.Compiled);
|
||||
|
||||
private readonly IHttpProxySettingsProvider _proxySettingsProvider;
|
||||
private readonly IUserAgentBuilder _userAgentBuilder;
|
||||
private readonly Logger _logger;
|
||||
|
||||
private const string _caBundleFileName = "curl-ca-bundle.crt";
|
||||
@@ -37,10 +38,11 @@ namespace NzbDrone.Common.Http.Dispatchers
|
||||
_caBundleFilePath = _caBundleFileName;
|
||||
}
|
||||
}
|
||||
|
||||
public CurlHttpDispatcher(IHttpProxySettingsProvider proxySettingsProvider, Logger logger)
|
||||
|
||||
public CurlHttpDispatcher(IHttpProxySettingsProvider proxySettingsProvider, IUserAgentBuilder userAgentBuilder, Logger logger)
|
||||
{
|
||||
_proxySettingsProvider = proxySettingsProvider;
|
||||
_userAgentBuilder = userAgentBuilder;
|
||||
_logger = logger;
|
||||
}
|
||||
|
||||
@@ -68,94 +70,93 @@ namespace NzbDrone.Common.Http.Dispatchers
|
||||
{
|
||||
using (Stream responseStream = new MemoryStream())
|
||||
using (Stream headerStream = new MemoryStream())
|
||||
|
||||
using (var curlEasy = new CurlEasy())
|
||||
{
|
||||
using (var curlEasy = new CurlEasy())
|
||||
curlEasy.AutoReferer = false;
|
||||
curlEasy.WriteFunction = (b, s, n, o) =>
|
||||
{
|
||||
curlEasy.AutoReferer = false;
|
||||
curlEasy.WriteFunction = (b, s, n, o) =>
|
||||
responseStream.Write(b, 0, s * n);
|
||||
return s * n;
|
||||
};
|
||||
curlEasy.HeaderFunction = (b, s, n, o) =>
|
||||
{
|
||||
headerStream.Write(b, 0, s * n);
|
||||
return s * n;
|
||||
};
|
||||
|
||||
AddProxy(curlEasy, request);
|
||||
|
||||
curlEasy.Url = request.Url.FullUri;
|
||||
|
||||
switch (request.Method)
|
||||
{
|
||||
case HttpMethod.GET:
|
||||
curlEasy.HttpGet = true;
|
||||
break;
|
||||
|
||||
case HttpMethod.POST:
|
||||
curlEasy.Post = true;
|
||||
break;
|
||||
|
||||
case HttpMethod.PUT:
|
||||
curlEasy.Put = true;
|
||||
break;
|
||||
|
||||
default:
|
||||
throw new NotSupportedException($"HttpCurl method {request.Method} not supported");
|
||||
}
|
||||
curlEasy.UserAgent = _userAgentBuilder.GetUserAgent(request.UseSimplifiedUserAgent);
|
||||
curlEasy.FollowLocation = false;
|
||||
|
||||
if (request.RequestTimeout != TimeSpan.Zero)
|
||||
{
|
||||
curlEasy.Timeout = (int)Math.Ceiling(request.RequestTimeout.TotalSeconds);
|
||||
}
|
||||
|
||||
if (OsInfo.IsWindows)
|
||||
{
|
||||
curlEasy.CaInfo = _caBundleFilePath;
|
||||
}
|
||||
|
||||
if (cookies != null)
|
||||
{
|
||||
curlEasy.Cookie = cookies.GetCookieHeader((Uri)request.Url);
|
||||
}
|
||||
|
||||
if (request.ContentData != null)
|
||||
{
|
||||
curlEasy.PostFieldSize = request.ContentData.Length;
|
||||
curlEasy.SetOpt(CurlOption.CopyPostFields, new string(Array.ConvertAll(request.ContentData, v => (char)v)));
|
||||
}
|
||||
|
||||
// Yes, we have to keep a ref to the object to prevent corrupting the unmanaged state
|
||||
using (var httpRequestHeaders = SerializeHeaders(request))
|
||||
{
|
||||
curlEasy.HttpHeader = httpRequestHeaders;
|
||||
|
||||
var result = curlEasy.Perform();
|
||||
|
||||
if (result != CurlCode.Ok)
|
||||
{
|
||||
responseStream.Write(b, 0, s * n);
|
||||
return s * n;
|
||||
};
|
||||
curlEasy.HeaderFunction = (b, s, n, o) =>
|
||||
{
|
||||
headerStream.Write(b, 0, s * n);
|
||||
return s * n;
|
||||
};
|
||||
|
||||
AddProxy(curlEasy, request);
|
||||
|
||||
curlEasy.Url = request.Url.FullUri;
|
||||
|
||||
switch (request.Method)
|
||||
{
|
||||
case HttpMethod.GET:
|
||||
curlEasy.HttpGet = true;
|
||||
break;
|
||||
|
||||
case HttpMethod.POST:
|
||||
curlEasy.Post = true;
|
||||
break;
|
||||
|
||||
case HttpMethod.PUT:
|
||||
curlEasy.Put = true;
|
||||
break;
|
||||
|
||||
default:
|
||||
throw new NotSupportedException(string.Format("HttpCurl method {0} not supported", request.Method));
|
||||
}
|
||||
curlEasy.FollowLocation = false;
|
||||
curlEasy.UserAgent = request.UseSimplifiedUserAgent ? UserAgentBuilder.UserAgentSimplified : UserAgentBuilder.UserAgent; ;
|
||||
|
||||
if (request.RequestTimeout != TimeSpan.Zero)
|
||||
{
|
||||
curlEasy.Timeout = (int)Math.Ceiling(request.RequestTimeout.TotalSeconds);
|
||||
}
|
||||
|
||||
if (OsInfo.IsWindows)
|
||||
{
|
||||
curlEasy.CaInfo = _caBundleFilePath;
|
||||
}
|
||||
|
||||
if (cookies != null)
|
||||
{
|
||||
curlEasy.Cookie = cookies.GetCookieHeader((Uri)request.Url);
|
||||
}
|
||||
|
||||
if (request.ContentData != null)
|
||||
{
|
||||
curlEasy.PostFieldSize = request.ContentData.Length;
|
||||
curlEasy.SetOpt(CurlOption.CopyPostFields, new string(Array.ConvertAll(request.ContentData, v => (char)v)));
|
||||
}
|
||||
|
||||
// Yes, we have to keep a ref to the object to prevent corrupting the unmanaged state
|
||||
using (var httpRequestHeaders = SerializeHeaders(request))
|
||||
{
|
||||
curlEasy.HttpHeader = httpRequestHeaders;
|
||||
|
||||
var result = curlEasy.Perform();
|
||||
|
||||
if (result != CurlCode.Ok)
|
||||
switch (result)
|
||||
{
|
||||
switch (result)
|
||||
{
|
||||
case CurlCode.SslCaCert:
|
||||
case (CurlCode)77:
|
||||
throw new WebException(string.Format("Curl Error {0} for Url {1}, issues with your operating system SSL Root Certificate Bundle (ca-bundle).", result, curlEasy.Url));
|
||||
default:
|
||||
throw new WebException(string.Format("Curl Error {0} for Url {1}", result, curlEasy.Url));
|
||||
|
||||
}
|
||||
case CurlCode.SslCaCert:
|
||||
case (CurlCode)77:
|
||||
throw new WebException(string.Format("Curl Error {0} for Url {1}, issues with your operating system SSL Root Certificate Bundle (ca-bundle).", result, curlEasy.Url));
|
||||
default:
|
||||
throw new WebException(string.Format("Curl Error {0} for Url {1}", result, curlEasy.Url));
|
||||
|
||||
}
|
||||
}
|
||||
|
||||
var webHeaderCollection = ProcessHeaderStream(request, cookies, headerStream);
|
||||
var responseData = ProcessResponseStream(request, responseStream, webHeaderCollection);
|
||||
|
||||
var httpHeader = new HttpHeader(webHeaderCollection);
|
||||
|
||||
return new HttpResponse(request, httpHeader, responseData, (HttpStatusCode)curlEasy.ResponseCode);
|
||||
}
|
||||
|
||||
var webHeaderCollection = ProcessHeaderStream(request, cookies, headerStream);
|
||||
var responseData = ProcessResponseStream(request, responseStream, webHeaderCollection);
|
||||
|
||||
var httpHeader = new HttpHeader(webHeaderCollection);
|
||||
|
||||
return new HttpResponse(request, httpHeader, responseData, (HttpStatusCode)curlEasy.ResponseCode);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -243,7 +244,7 @@ namespace NzbDrone.Common.Http.Dispatchers
|
||||
private string FixSetCookieHeader(string setCookie)
|
||||
{
|
||||
// fix up the date if it was malformed
|
||||
var setCookieClean = ExpiryDate.Replace(setCookie, delegate(Match match)
|
||||
var setCookieClean = ExpiryDate.Replace(setCookie, delegate (Match match)
|
||||
{
|
||||
string shortFormat = "ddd, dd-MMM-yy HH:mm:ss";
|
||||
string longFormat = "ddd, dd-MMM-yyyy HH:mm:ss";
|
||||
@@ -260,7 +261,6 @@ namespace NzbDrone.Common.Http.Dispatchers
|
||||
|
||||
private byte[] ProcessResponseStream(HttpRequest request, Stream responseStream, WebHeaderCollection webHeaderCollection)
|
||||
{
|
||||
byte[] bytes = null;
|
||||
responseStream.Position = 0;
|
||||
|
||||
if (responseStream.Length != 0)
|
||||
@@ -270,27 +270,20 @@ namespace NzbDrone.Common.Http.Dispatchers
|
||||
{
|
||||
if (encoding.IndexOf("gzip") != -1)
|
||||
{
|
||||
using (var zipStream = new GZipStream(responseStream, CompressionMode.Decompress))
|
||||
{
|
||||
bytes = zipStream.ToBytes();
|
||||
}
|
||||
responseStream = new GZipStream(responseStream, CompressionMode.Decompress);
|
||||
|
||||
webHeaderCollection.Remove("Content-Encoding");
|
||||
}
|
||||
else if (encoding.IndexOf("deflate") != -1)
|
||||
{
|
||||
using (var deflateStream = new DeflateStream(responseStream, CompressionMode.Decompress))
|
||||
{
|
||||
bytes = deflateStream.ToBytes();
|
||||
}
|
||||
responseStream = new DeflateStream(responseStream, CompressionMode.Decompress);
|
||||
|
||||
webHeaderCollection.Remove("Content-Encoding");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (bytes == null) bytes = responseStream.ToBytes();
|
||||
return bytes;
|
||||
return responseStream.ToBytes();
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -10,21 +10,23 @@ namespace NzbDrone.Common.Http.Dispatchers
|
||||
{
|
||||
private readonly ManagedHttpDispatcher _managedDispatcher;
|
||||
private readonly CurlHttpDispatcher _curlDispatcher;
|
||||
private readonly IPlatformInfo _platformInfo;
|
||||
private readonly Logger _logger;
|
||||
|
||||
private readonly ICached<bool> _curlTLSFallbackCache;
|
||||
|
||||
public FallbackHttpDispatcher(ManagedHttpDispatcher managedDispatcher, CurlHttpDispatcher curlDispatcher, ICacheManager cacheManager, Logger logger)
|
||||
public FallbackHttpDispatcher(ManagedHttpDispatcher managedDispatcher, CurlHttpDispatcher curlDispatcher, ICacheManager cacheManager, IPlatformInfo platformInfo, Logger logger)
|
||||
{
|
||||
_managedDispatcher = managedDispatcher;
|
||||
_curlDispatcher = curlDispatcher;
|
||||
_platformInfo = platformInfo;
|
||||
_curlTLSFallbackCache = cacheManager.GetCache<bool>(GetType(), "curlTLSFallback");
|
||||
_logger = logger;
|
||||
}
|
||||
|
||||
public HttpResponse GetResponse(HttpRequest request, CookieContainer cookies)
|
||||
{
|
||||
if (OsInfo.IsMonoRuntime && request.Url.Scheme == "https")
|
||||
if (PlatformInfo.IsMono && request.Url.Scheme == "https")
|
||||
{
|
||||
if (!_curlTLSFallbackCache.Find(request.Url.Host))
|
||||
{
|
||||
|
||||
@@ -2,9 +2,13 @@ using System;
|
||||
using System.IO;
|
||||
using System.IO.Compression;
|
||||
using System.Net;
|
||||
using System.Reflection;
|
||||
using NLog;
|
||||
using NLog.Fluent;
|
||||
using NzbDrone.Common.EnvironmentInfo;
|
||||
using NzbDrone.Common.Extensions;
|
||||
using NzbDrone.Common.Http.Proxy;
|
||||
using NzbDrone.Common.Instrumentation.Extensions;
|
||||
using NzbDrone.Common.Security;
|
||||
|
||||
namespace NzbDrone.Common.Http.Dispatchers
|
||||
@@ -13,55 +17,59 @@ namespace NzbDrone.Common.Http.Dispatchers
|
||||
{
|
||||
private readonly IHttpProxySettingsProvider _proxySettingsProvider;
|
||||
private readonly ICreateManagedWebProxy _createManagedWebProxy;
|
||||
private readonly IUserAgentBuilder _userAgentBuilder;
|
||||
private readonly IPlatformInfo _platformInfo;
|
||||
private readonly Logger _logger;
|
||||
|
||||
public ManagedHttpDispatcher(IHttpProxySettingsProvider proxySettingsProvider, ICreateManagedWebProxy createManagedWebProxy)
|
||||
public ManagedHttpDispatcher(IHttpProxySettingsProvider proxySettingsProvider, ICreateManagedWebProxy createManagedWebProxy, IUserAgentBuilder userAgentBuilder, IPlatformInfo platformInfo, Logger logger)
|
||||
{
|
||||
_proxySettingsProvider = proxySettingsProvider;
|
||||
_createManagedWebProxy = createManagedWebProxy;
|
||||
_userAgentBuilder = userAgentBuilder;
|
||||
_platformInfo = platformInfo;
|
||||
_logger = logger;
|
||||
}
|
||||
|
||||
public HttpResponse GetResponse(HttpRequest request, CookieContainer cookies)
|
||||
{
|
||||
HttpWebResponse httpWebResponse = null;
|
||||
HttpWebRequest webRequest = null;
|
||||
var webRequest = (HttpWebRequest)WebRequest.Create((Uri)request.Url);
|
||||
|
||||
if (PlatformInfo.IsMono)
|
||||
{
|
||||
// On Mono GZipStream/DeflateStream leaks memory if an exception is thrown, use an intermediate buffer in that case.
|
||||
webRequest.AutomaticDecompression = DecompressionMethods.None;
|
||||
webRequest.Headers.Add("Accept-Encoding", "gzip");
|
||||
}
|
||||
else
|
||||
{
|
||||
// Deflate is not a standard and could break depending on implementation.
|
||||
// we should just stick with the more compatible Gzip
|
||||
//http://stackoverflow.com/questions/8490718/how-to-decompress-stream-deflated-with-java-util-zip-deflater-in-net
|
||||
webRequest.AutomaticDecompression = DecompressionMethods.GZip;
|
||||
}
|
||||
|
||||
webRequest.Method = request.Method.ToString();
|
||||
webRequest.UserAgent = _userAgentBuilder.GetUserAgent(request.UseSimplifiedUserAgent);
|
||||
webRequest.KeepAlive = request.ConnectionKeepAlive;
|
||||
webRequest.AllowAutoRedirect = false;
|
||||
webRequest.CookieContainer = cookies;
|
||||
|
||||
if (request.RequestTimeout != TimeSpan.Zero)
|
||||
{
|
||||
webRequest.Timeout = (int)Math.Ceiling(request.RequestTimeout.TotalMilliseconds);
|
||||
}
|
||||
|
||||
AddProxy(webRequest, request);
|
||||
|
||||
if (request.Headers != null)
|
||||
{
|
||||
AddRequestHeaders(webRequest, request.Headers);
|
||||
}
|
||||
|
||||
HttpWebResponse httpWebResponse;
|
||||
|
||||
try
|
||||
{
|
||||
webRequest = (HttpWebRequest) WebRequest.Create((Uri) request.Url);
|
||||
|
||||
if (OsInfo.IsMonoRuntime)
|
||||
{
|
||||
// On Mono GZipStream/DeflateStream leaks memory if an exception is thrown, use an intermediate buffer in that case.
|
||||
webRequest.AutomaticDecompression = DecompressionMethods.None;
|
||||
webRequest.Headers.Add("Accept-Encoding", "gzip");
|
||||
}
|
||||
else
|
||||
{
|
||||
// Deflate is not a standard and could break depending on implementation.
|
||||
// we should just stick with the more compatible Gzip
|
||||
//http://stackoverflow.com/questions/8490718/how-to-decompress-stream-deflated-with-java-util-zip-deflater-in-net
|
||||
webRequest.AutomaticDecompression = DecompressionMethods.GZip;
|
||||
}
|
||||
|
||||
webRequest.Method = request.Method.ToString();
|
||||
webRequest.UserAgent = request.UseSimplifiedUserAgent
|
||||
? UserAgentBuilder.UserAgentSimplified
|
||||
: UserAgentBuilder.UserAgent;
|
||||
webRequest.KeepAlive = request.ConnectionKeepAlive;
|
||||
webRequest.AllowAutoRedirect = false;
|
||||
webRequest.CookieContainer = cookies;
|
||||
|
||||
if (request.RequestTimeout != TimeSpan.Zero)
|
||||
{
|
||||
webRequest.Timeout = (int) Math.Ceiling(request.RequestTimeout.TotalMilliseconds);
|
||||
}
|
||||
|
||||
AddProxy(webRequest, request);
|
||||
|
||||
if (request.Headers != null)
|
||||
{
|
||||
AddRequestHeaders(webRequest, request.Headers);
|
||||
}
|
||||
|
||||
if (request.ContentData != null)
|
||||
{
|
||||
webRequest.ContentLength = request.ContentData.Length;
|
||||
@@ -71,34 +79,57 @@ namespace NzbDrone.Common.Http.Dispatchers
|
||||
}
|
||||
}
|
||||
|
||||
try
|
||||
httpWebResponse = (HttpWebResponse)webRequest.GetResponse();
|
||||
}
|
||||
catch (WebException e)
|
||||
{
|
||||
if (e.Status == WebExceptionStatus.SecureChannelFailure && OsInfo.IsWindows)
|
||||
{
|
||||
httpWebResponse = (HttpWebResponse) webRequest.GetResponse();
|
||||
SecurityProtocolPolicy.DisableTls12();
|
||||
}
|
||||
catch (WebException e)
|
||||
|
||||
httpWebResponse = (HttpWebResponse)e.Response;
|
||||
|
||||
if (httpWebResponse == null)
|
||||
{
|
||||
if (e.Status == WebExceptionStatus.SecureChannelFailure && OsInfo.IsWindows)
|
||||
// Workaround for mono not closing connections properly in certain situations.
|
||||
AbortWebRequest(webRequest);
|
||||
|
||||
// The default messages for WebException on mono are pretty horrible.
|
||||
if (e.Status == WebExceptionStatus.NameResolutionFailure)
|
||||
{
|
||||
SecurityProtocolPolicy.DisableTls12();
|
||||
throw new WebException($"DNS Name Resolution Failure: '{webRequest.RequestUri.Host}'", e.Status);
|
||||
}
|
||||
|
||||
httpWebResponse = (HttpWebResponse) e.Response;
|
||||
|
||||
if (httpWebResponse == null)
|
||||
else if (e.ToString().Contains("TLS Support not"))
|
||||
{
|
||||
throw new TlsFailureException(webRequest, e);
|
||||
}
|
||||
else if (e.ToString().Contains("The authentication or decryption has failed."))
|
||||
{
|
||||
throw new TlsFailureException(webRequest, e);
|
||||
}
|
||||
else if (OsInfo.IsNotWindows)
|
||||
{
|
||||
throw new WebException($"{e.Message}: '{webRequest.RequestUri}'", e, e.Status, e.Response);
|
||||
}
|
||||
else
|
||||
{
|
||||
throw;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
byte[] data = null;
|
||||
byte[] data = null;
|
||||
|
||||
using (var responseStream = httpWebResponse.GetResponseStream())
|
||||
using (var responseStream = httpWebResponse.GetResponseStream())
|
||||
{
|
||||
if (responseStream != null && responseStream != Stream.Null)
|
||||
{
|
||||
if (responseStream != null)
|
||||
try
|
||||
{
|
||||
data = responseStream.ToBytes();
|
||||
|
||||
if (OsInfo.IsMonoRuntime && httpWebResponse.ContentEncoding == "gzip")
|
||||
if (PlatformInfo.IsMono && httpWebResponse.ContentEncoding == "gzip")
|
||||
{
|
||||
using (var compressedStream = new MemoryStream(data))
|
||||
using (var gzip = new GZipStream(compressedStream, CompressionMode.Decompress))
|
||||
@@ -111,17 +142,14 @@ namespace NzbDrone.Common.Http.Dispatchers
|
||||
httpWebResponse.Headers.Remove("Content-Encoding");
|
||||
}
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
throw new WebException("Failed to read complete http response", ex, WebExceptionStatus.ReceiveFailure, httpWebResponse);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return new HttpResponse(request, new HttpHeader(httpWebResponse.Headers), data,
|
||||
httpWebResponse.StatusCode);
|
||||
}
|
||||
finally
|
||||
{
|
||||
webRequest = null;
|
||||
(httpWebResponse as IDisposable)?.Dispose();
|
||||
httpWebResponse = null;
|
||||
}
|
||||
return new HttpResponse(request, new HttpHeader(httpWebResponse.Headers), data, httpWebResponse.StatusCode);
|
||||
}
|
||||
|
||||
protected virtual void AddProxy(HttpWebRequest webRequest, HttpRequest request)
|
||||
@@ -181,5 +209,35 @@ namespace NzbDrone.Common.Http.Dispatchers
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Workaround for mono not closing connections properly on timeouts
|
||||
private void AbortWebRequest(HttpWebRequest webRequest)
|
||||
{
|
||||
// First affected version was mono 5.16
|
||||
if (OsInfo.IsNotWindows && _platformInfo.Version >= new Version(5, 16))
|
||||
{
|
||||
try
|
||||
{
|
||||
var currentOperationInfo = webRequest.GetType().GetField("currentOperation", BindingFlags.NonPublic | BindingFlags.Instance);
|
||||
var currentOperation = currentOperationInfo.GetValue(webRequest);
|
||||
|
||||
if (currentOperation != null)
|
||||
{
|
||||
var responseStreamInfo = currentOperation.GetType().GetField("responseStream", BindingFlags.NonPublic | BindingFlags.Instance);
|
||||
var responseStream = responseStreamInfo.GetValue(currentOperation) as Stream;
|
||||
// Note that responseStream will likely be null once mono fixes it.
|
||||
responseStream?.Dispose();
|
||||
}
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
// This can fail randomly on future mono versions that have been changed/fixed. Log to sentry and ignore.
|
||||
_logger.Trace()
|
||||
.Exception(ex)
|
||||
.Message("Unable to dispose responseStream on mono {0}", _platformInfo.Version)
|
||||
.Write();
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
using System;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Diagnostics;
|
||||
using System.IO;
|
||||
@@ -31,12 +31,19 @@ namespace NzbDrone.Common.Http
|
||||
private readonly ICached<CookieContainer> _cookieContainerCache;
|
||||
private readonly List<IHttpRequestInterceptor> _requestInterceptors;
|
||||
private readonly IHttpDispatcher _httpDispatcher;
|
||||
private readonly IUserAgentBuilder _userAgentBuilder;
|
||||
|
||||
public HttpClient(IEnumerable<IHttpRequestInterceptor> requestInterceptors, ICacheManager cacheManager, IRateLimitService rateLimitService, IHttpDispatcher httpDispatcher, Logger logger)
|
||||
public HttpClient(IEnumerable<IHttpRequestInterceptor> requestInterceptors,
|
||||
ICacheManager cacheManager,
|
||||
IRateLimitService rateLimitService,
|
||||
IHttpDispatcher httpDispatcher,
|
||||
IUserAgentBuilder userAgentBuilder,
|
||||
Logger logger)
|
||||
{
|
||||
_requestInterceptors = requestInterceptors.ToList();
|
||||
_rateLimitService = rateLimitService;
|
||||
_httpDispatcher = httpDispatcher;
|
||||
_userAgentBuilder = userAgentBuilder;
|
||||
_logger = logger;
|
||||
|
||||
ServicePointManager.DefaultConnectionLimit = 12;
|
||||
@@ -71,7 +78,7 @@ namespace NzbDrone.Common.Http
|
||||
while (response.HasHttpRedirect);
|
||||
}
|
||||
|
||||
if (response.HasHttpRedirect && !RuntimeInfoBase.IsProduction)
|
||||
if (response.HasHttpRedirect && !RuntimeInfo.IsProduction)
|
||||
{
|
||||
_logger.Error("Server requested a redirect to [{0}] while in developer mode. Update the request URL to avoid this redirect.", response.Headers["Location"]);
|
||||
}
|
||||
@@ -143,19 +150,30 @@ namespace NzbDrone.Common.Http
|
||||
if (!request.IgnorePersistentCookies)
|
||||
{
|
||||
var persistentCookies = presistentContainer.GetCookies((Uri)request.Url);
|
||||
sourceContainer.Add(persistentCookies);
|
||||
sourceContainer.Add(persistentCookies);
|
||||
}
|
||||
|
||||
if (request.Cookies.Count != 0)
|
||||
{
|
||||
foreach (var pair in request.Cookies)
|
||||
{
|
||||
var cookie = new Cookie(pair.Key, pair.Value, "/")
|
||||
Cookie cookie;
|
||||
if (pair.Value == null)
|
||||
{
|
||||
// Use Now rather than UtcNow to work around Mono cookie expiry bug.
|
||||
// See https://gist.github.com/ta264/7822b1424f72e5b4c961
|
||||
Expires = DateTime.Now.AddHours(1)
|
||||
};
|
||||
cookie = new Cookie(pair.Key, "", "/")
|
||||
{
|
||||
Expires = DateTime.Now.AddDays(-1)
|
||||
};
|
||||
}
|
||||
else
|
||||
{
|
||||
cookie = new Cookie(pair.Key, pair.Value, "/")
|
||||
{
|
||||
// Use Now rather than UtcNow to work around Mono cookie expiry bug.
|
||||
// See https://gist.github.com/ta264/7822b1424f72e5b4c961
|
||||
Expires = DateTime.Now.AddHours(1)
|
||||
};
|
||||
}
|
||||
|
||||
sourceContainer.Add((Uri)request.Url, cookie);
|
||||
|
||||
@@ -178,7 +196,6 @@ namespace NzbDrone.Common.Http
|
||||
var presistentContainer = _cookieContainerCache.Get("container", () => new CookieContainer());
|
||||
var persistentCookies = presistentContainer.GetCookies((Uri)request.Url);
|
||||
var existingCookies = cookieContainer.GetCookies((Uri)request.Url);
|
||||
|
||||
cookieContainer.Add(persistentCookies);
|
||||
cookieContainer.Add(existingCookies);
|
||||
}*/
|
||||
@@ -226,13 +243,11 @@ namespace NzbDrone.Common.Http
|
||||
_logger.Debug("Downloading [{0}] to [{1}]", url, fileName);
|
||||
|
||||
var stopWatch = Stopwatch.StartNew();
|
||||
using (var webClient = new GZipWebClient())
|
||||
{
|
||||
webClient.Headers.Add(HttpRequestHeader.UserAgent, UserAgentBuilder.UserAgent);
|
||||
webClient.DownloadFile(url, fileName);
|
||||
stopWatch.Stop();
|
||||
_logger.Debug("Downloading Completed. took {0:0}s", stopWatch.Elapsed.Seconds);
|
||||
}
|
||||
var webClient = new GZipWebClient();
|
||||
webClient.Headers.Add(HttpRequestHeader.UserAgent, _userAgentBuilder.GetUserAgent());
|
||||
webClient.DownloadFile(url, fileName);
|
||||
stopWatch.Stop();
|
||||
_logger.Debug("Downloading Completed. took {0:0}s", stopWatch.Elapsed.Seconds);
|
||||
}
|
||||
catch (WebException e)
|
||||
{
|
||||
@@ -255,6 +270,7 @@ namespace NzbDrone.Common.Http
|
||||
public HttpResponse<T> Get<T>(HttpRequest request) where T : new()
|
||||
{
|
||||
var response = Get(request);
|
||||
CheckResponseContentType(response);
|
||||
return new HttpResponse<T>(response);
|
||||
}
|
||||
|
||||
@@ -273,7 +289,16 @@ namespace NzbDrone.Common.Http
|
||||
public HttpResponse<T> Post<T>(HttpRequest request) where T : new()
|
||||
{
|
||||
var response = Post(request);
|
||||
CheckResponseContentType(response);
|
||||
return new HttpResponse<T>(response);
|
||||
}
|
||||
|
||||
private void CheckResponseContentType(HttpResponse response)
|
||||
{
|
||||
if (response.Headers.ContentType != null && response.Headers.ContentType.Contains("text/html"))
|
||||
{
|
||||
throw new UnexpectedHtmlContentException(response);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -7,13 +7,19 @@ namespace NzbDrone.Common.Http
|
||||
public HttpRequest Request { get; private set; }
|
||||
public HttpResponse Response { get; private set; }
|
||||
|
||||
public HttpException(HttpRequest request, HttpResponse response)
|
||||
: base(string.Format("HTTP request failed: [{0}:{1}] [{2}] at [{3}]", (int)response.StatusCode, response.StatusCode, request.Method, request.Url))
|
||||
public HttpException(HttpRequest request, HttpResponse response, string message)
|
||||
: base(message)
|
||||
{
|
||||
Request = request;
|
||||
Response = response;
|
||||
}
|
||||
|
||||
public HttpException(HttpRequest request, HttpResponse response)
|
||||
: this(request, response, string.Format("HTTP request failed: [{0}:{1}] [{2}] at [{3}]", (int)response.StatusCode, response.StatusCode, request.Method, request.Url))
|
||||
{
|
||||
|
||||
}
|
||||
|
||||
public HttpException(HttpResponse response)
|
||||
: this(response.Request, response)
|
||||
{
|
||||
@@ -30,4 +36,4 @@ namespace NzbDrone.Common.Http
|
||||
return base.ToString();
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -17,7 +17,7 @@ namespace NzbDrone.Common.Http
|
||||
IgnorePersistentCookies = false;
|
||||
Cookies = new Dictionary<string, string>();
|
||||
|
||||
if (!RuntimeInfoBase.IsProduction)
|
||||
if (!RuntimeInfo.IsProduction)
|
||||
{
|
||||
AllowAutoRedirect = false;
|
||||
}
|
||||
|
||||
18
src/NzbDrone.Common/Http/TlsFailureException.cs
Normal file
18
src/NzbDrone.Common/Http/TlsFailureException.cs
Normal file
@@ -0,0 +1,18 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Net;
|
||||
using System.Text;
|
||||
|
||||
namespace NzbDrone.Common.Http
|
||||
{
|
||||
public class TlsFailureException : WebException
|
||||
{
|
||||
public TlsFailureException(WebRequest request, WebException innerException)
|
||||
: base("Failed to establish secure https connection to '" + request.RequestUri + "', libcurl fallback might be unavailable.", innerException, WebExceptionStatus.SecureChannelFailure, innerException.Response)
|
||||
{
|
||||
|
||||
}
|
||||
|
||||
}
|
||||
}
|
||||
14
src/NzbDrone.Common/Http/UnexpectedHtmlContentException.cs
Normal file
14
src/NzbDrone.Common/Http/UnexpectedHtmlContentException.cs
Normal file
@@ -0,0 +1,14 @@
|
||||
|
||||
using System;
|
||||
|
||||
namespace NzbDrone.Common.Http
|
||||
{
|
||||
public class UnexpectedHtmlContentException : HttpException
|
||||
{
|
||||
public UnexpectedHtmlContentException(HttpResponse response)
|
||||
: base(response.Request, response, $"Site responded with browser content instead of api data. This disruption may be temporary, please try again later. [{response.Request.Url}]")
|
||||
{
|
||||
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -2,19 +2,39 @@ using NzbDrone.Common.EnvironmentInfo;
|
||||
|
||||
namespace NzbDrone.Common.Http
|
||||
{
|
||||
public static class UserAgentBuilder
|
||||
public interface IUserAgentBuilder
|
||||
{
|
||||
public static string UserAgent { get; private set; }
|
||||
public static string UserAgentSimplified { get; private set; }
|
||||
string GetUserAgent(bool simplified = false);
|
||||
}
|
||||
|
||||
static UserAgentBuilder()
|
||||
public class UserAgentBuilder : IUserAgentBuilder
|
||||
{
|
||||
private readonly string _userAgentSimplified;
|
||||
private readonly string _userAgent;
|
||||
|
||||
public string GetUserAgent(bool simplified)
|
||||
{
|
||||
UserAgent = string.Format("Radarr/{0} ({1} {2})",
|
||||
BuildInfo.Version,
|
||||
OsInfo.Os, OsInfo.Version.ToString(2));
|
||||
if (simplified)
|
||||
{
|
||||
return _userAgentSimplified;
|
||||
}
|
||||
|
||||
UserAgentSimplified = string.Format("Radarr/{0}",
|
||||
BuildInfo.Version.ToString(2));
|
||||
return _userAgent;
|
||||
}
|
||||
|
||||
public UserAgentBuilder(IOsInfo osInfo)
|
||||
{
|
||||
var osName = OsInfo.Os.ToString();
|
||||
|
||||
if (!string.IsNullOrWhiteSpace(osInfo.Name))
|
||||
{
|
||||
osName = osInfo.Name.ToLower();
|
||||
}
|
||||
|
||||
var osVersion = osInfo.Version?.ToLower();
|
||||
|
||||
_userAgent = $"Radarr/{BuildInfo.Version} ({osName} {osVersion})";
|
||||
_userAgentSimplified = $"Radarr/{BuildInfo.Version.ToString(2)}";
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
43
src/NzbDrone.Common/Instrumentation/CleansingJsonVisitor.cs
Normal file
43
src/NzbDrone.Common/Instrumentation/CleansingJsonVisitor.cs
Normal file
@@ -0,0 +1,43 @@
|
||||
using Newtonsoft.Json.Linq;
|
||||
using NzbDrone.Common.Serializer;
|
||||
|
||||
namespace NzbDrone.Common.Instrumentation
|
||||
{
|
||||
public class CleansingJsonVisitor : JsonVisitor
|
||||
{
|
||||
public override void Visit(JArray json)
|
||||
{
|
||||
for (var i = 0; i < json.Count; i++)
|
||||
{
|
||||
if (json[i].Type == JTokenType.String)
|
||||
{
|
||||
var text = json[i].Value<string>();
|
||||
json[i] = new JValue(CleanseLogMessage.Cleanse(text));
|
||||
}
|
||||
}
|
||||
foreach (JToken token in json)
|
||||
{
|
||||
Visit(token);
|
||||
}
|
||||
}
|
||||
|
||||
public override void Visit(JProperty property)
|
||||
{
|
||||
if (property.Value.Type == JTokenType.String)
|
||||
{
|
||||
property.Value = CleanseValue(property.Value as JValue);
|
||||
}
|
||||
else
|
||||
{
|
||||
base.Visit(property);
|
||||
}
|
||||
}
|
||||
|
||||
private JValue CleanseValue(JValue value)
|
||||
{
|
||||
var text = value.Value<string>();
|
||||
var cleansed = CleanseLogMessage.Cleanse(text);
|
||||
return new JValue(cleansed);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,89 +0,0 @@
|
||||
using System;
|
||||
using NLog;
|
||||
using NLog.Common;
|
||||
using NLog.Layouts;
|
||||
using NLog.Targets;
|
||||
using NzbDrone.Common.EnvironmentInfo;
|
||||
using NzbDrone.Common.Exceptron;
|
||||
using NzbDrone.Common.Exceptron.Configuration;
|
||||
|
||||
namespace NzbDrone.Common.Instrumentation
|
||||
{
|
||||
/// <summary>
|
||||
/// <see cref="NLog"/> target for exceptron. Allows you to automatically report all
|
||||
/// exceptions logged to Nlog/>
|
||||
/// </summary>
|
||||
[Target("Exceptron")]
|
||||
public class ExceptronTarget : Target
|
||||
{
|
||||
/// <summary>
|
||||
/// <see cref="ExceptronClient"/> instance that Nlog Target uses to report the exceptions.
|
||||
/// </summary>
|
||||
public IExceptronClient ExceptronClient { get; internal set; }
|
||||
|
||||
protected override void InitializeTarget()
|
||||
{
|
||||
var config = new ExceptronConfiguration
|
||||
{
|
||||
ApiKey = "d64e0a72845d495abc625af3a27cf5f5",
|
||||
IncludeMachineName = true,
|
||||
};
|
||||
|
||||
if (RuntimeInfoBase.IsProduction)
|
||||
{
|
||||
config.ApiKey = "82c0f66dd2d64d1480cc88b551c9bdd8";
|
||||
}
|
||||
|
||||
ExceptronClient = new ExceptronClient(config, BuildInfo.Version);
|
||||
}
|
||||
|
||||
|
||||
/// <summary>
|
||||
/// String that identifies the active user
|
||||
/// </summary>
|
||||
public Layout UserId { get; set; }
|
||||
|
||||
protected override void Write(LogEventInfo logEvent)
|
||||
{
|
||||
if (logEvent == null || logEvent.Exception == null || logEvent.Exception.ExceptronShouldIgnore()) return;
|
||||
|
||||
try
|
||||
{
|
||||
var exceptionData = new ExceptionData
|
||||
{
|
||||
Exception = logEvent.Exception,
|
||||
Component = logEvent.LoggerName,
|
||||
Message = logEvent.FormattedMessage,
|
||||
};
|
||||
|
||||
if (UserId != null)
|
||||
{
|
||||
exceptionData.UserId = UserId.Render(logEvent);
|
||||
}
|
||||
|
||||
if (logEvent.Level <= LogLevel.Info)
|
||||
{
|
||||
exceptionData.Severity = ExceptionSeverity.None;
|
||||
}
|
||||
else if (logEvent.Level <= LogLevel.Warn)
|
||||
{
|
||||
exceptionData.Severity = ExceptionSeverity.Warning;
|
||||
}
|
||||
else if (logEvent.Level <= LogLevel.Error)
|
||||
{
|
||||
exceptionData.Severity = ExceptionSeverity.Error;
|
||||
}
|
||||
else if (logEvent.Level <= LogLevel.Fatal)
|
||||
{
|
||||
exceptionData.Severity = ExceptionSeverity.Fatal;
|
||||
}
|
||||
|
||||
ExceptronClient.SubmitException(exceptionData);
|
||||
}
|
||||
catch (Exception e)
|
||||
{
|
||||
InternalLogger.Warn("Unable to report exception. {0}", e);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,55 @@
|
||||
using System.Linq;
|
||||
using NLog;
|
||||
using NLog.Fluent;
|
||||
|
||||
namespace NzbDrone.Common.Instrumentation.Extensions
|
||||
{
|
||||
public static class SentryLoggerExtensions
|
||||
{
|
||||
public static readonly Logger SentryLogger = LogManager.GetLogger("Sentry");
|
||||
|
||||
public static LogBuilder SentryFingerprint(this LogBuilder logBuilder, params string[] fingerprint)
|
||||
{
|
||||
return logBuilder.Property("Sentry", fingerprint);
|
||||
}
|
||||
|
||||
public static LogBuilder WriteSentryDebug(this LogBuilder logBuilder, params string[] fingerprint)
|
||||
{
|
||||
return LogSentryMessage(logBuilder, LogLevel.Debug, fingerprint);
|
||||
}
|
||||
|
||||
public static LogBuilder WriteSentryInfo(this LogBuilder logBuilder, params string[] fingerprint)
|
||||
{
|
||||
return LogSentryMessage(logBuilder, LogLevel.Info, fingerprint);
|
||||
}
|
||||
|
||||
public static LogBuilder WriteSentryWarn(this LogBuilder logBuilder, params string[] fingerprint)
|
||||
{
|
||||
return LogSentryMessage(logBuilder, LogLevel.Warn, fingerprint);
|
||||
}
|
||||
|
||||
public static LogBuilder WriteSentryError(this LogBuilder logBuilder, params string[] fingerprint)
|
||||
{
|
||||
return LogSentryMessage(logBuilder, LogLevel.Error, fingerprint);
|
||||
}
|
||||
|
||||
private static LogBuilder LogSentryMessage(LogBuilder logBuilder, LogLevel level, string[] fingerprint)
|
||||
{
|
||||
SentryLogger.Log(level)
|
||||
.CopyLogEvent(logBuilder.LogEventInfo)
|
||||
.SentryFingerprint(fingerprint)
|
||||
.Write();
|
||||
|
||||
return logBuilder.Property("Sentry", null);
|
||||
}
|
||||
|
||||
private static LogBuilder CopyLogEvent(this LogBuilder logBuilder, LogEventInfo logEvent)
|
||||
{
|
||||
return logBuilder.LoggerName(logEvent.LoggerName)
|
||||
.TimeStamp(logEvent.TimeStamp)
|
||||
.Message(logEvent.Message, logEvent.Parameters)
|
||||
.Properties(logEvent.Properties.ToDictionary(v => v.Key, v => v.Value))
|
||||
.Exception(logEvent.Exception);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,4 +1,4 @@
|
||||
using System;
|
||||
using System;
|
||||
using System.Threading.Tasks;
|
||||
using NLog;
|
||||
using NzbDrone.Common.EnvironmentInfo;
|
||||
@@ -19,7 +19,7 @@ namespace NzbDrone.Common.Instrumentation
|
||||
var exception = e.Exception;
|
||||
|
||||
Console.WriteLine("Task Error: {0}", exception);
|
||||
Logger.Error(exception, "Task Error: " + exception.Message);
|
||||
Logger.Error(exception, "Task Error");
|
||||
}
|
||||
|
||||
private static void HandleAppDomainException(object sender, UnhandledExceptionEventArgs e)
|
||||
@@ -35,7 +35,7 @@ namespace NzbDrone.Common.Instrumentation
|
||||
return;
|
||||
}
|
||||
|
||||
if (OsInfo.IsMonoRuntime)
|
||||
if (PlatformInfo.IsMono)
|
||||
{
|
||||
if (exception is TypeInitializationException && exception.InnerException is DllNotFoundException ||
|
||||
exception is DllNotFoundException)
|
||||
@@ -48,7 +48,7 @@ namespace NzbDrone.Common.Instrumentation
|
||||
Console.WriteLine(exception.StackTrace);
|
||||
|
||||
Console.WriteLine("EPIC FAIL: {0}", exception);
|
||||
Logger.Fatal(exception, "EPIC FAIL: " + exception.Message);
|
||||
Logger.Fatal(exception, "EPIC FAIL.");
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,12 +1,12 @@
|
||||
using System;
|
||||
using System;
|
||||
using System.Diagnostics;
|
||||
using System.IO;
|
||||
using LogentriesNLog;
|
||||
using NLog;
|
||||
using NLog.Config;
|
||||
using NLog.Targets;
|
||||
using NzbDrone.Common.EnvironmentInfo;
|
||||
using NzbDrone.Common.Extensions;
|
||||
using NzbDrone.Common.Instrumentation.Sentry;
|
||||
|
||||
namespace NzbDrone.Common.Instrumentation
|
||||
{
|
||||
@@ -19,6 +19,7 @@ namespace NzbDrone.Common.Instrumentation
|
||||
LogManager.Configuration = new LoggingConfiguration();
|
||||
}
|
||||
|
||||
const string FILE_LOG_LAYOUT = @"${date:format=yyyy-M-d HH\:mm\:ss.f}|${level}|${logger}|${message}${onexception:inner=${newline}${newline}[v${assembly-version}] ${exception:format=ToString}${newline}}";
|
||||
|
||||
public static void Register(IStartupContext startupContext, bool updateApp, bool inConsole)
|
||||
{
|
||||
@@ -38,17 +39,15 @@ namespace NzbDrone.Common.Instrumentation
|
||||
RegisterDebugger();
|
||||
}
|
||||
|
||||
//Disabling for now - until its fixed or we yank it out
|
||||
//RegisterExceptron();
|
||||
RegisterSentry(updateApp);
|
||||
|
||||
if (updateApp)
|
||||
{
|
||||
RegisterUpdateFile(appFolderInfo);
|
||||
RegisterLogEntries();
|
||||
}
|
||||
else
|
||||
{
|
||||
if (inConsole && (OsInfo.IsNotWindows || RuntimeInfoBase.IsUserInteractive))
|
||||
if (inConsole && (OsInfo.IsNotWindows || RuntimeInfo.IsUserInteractive))
|
||||
{
|
||||
RegisterConsole();
|
||||
}
|
||||
@@ -59,17 +58,34 @@ namespace NzbDrone.Common.Instrumentation
|
||||
LogManager.ReconfigExistingLoggers();
|
||||
}
|
||||
|
||||
private static void RegisterLogEntries()
|
||||
private static void RegisterSentry(bool updateClient)
|
||||
{
|
||||
var target = new LogentriesTarget();
|
||||
target.Name = "logentriesTarget";
|
||||
target.Token = "7688c9ac-015f-45c7-bfee-73f370f5f380";
|
||||
target.LogHostname = true;
|
||||
target.Debug = false;
|
||||
string dsn;
|
||||
|
||||
var loggingRule = new LoggingRule("*", LogLevel.Info, target);
|
||||
LogManager.Configuration.AddTarget("logentries", target);
|
||||
if (updateClient)
|
||||
{
|
||||
dsn = "https://40e47616afd84525bf49306123cb0926@sentry.radarr.video/10";
|
||||
}
|
||||
else
|
||||
{
|
||||
dsn = RuntimeInfo.IsProduction
|
||||
? "https://a8e4c507c1f84578b55a841759a99dfb@sentry.radarr.video/2"
|
||||
: "https://dee5b3fe26844368ac4458faa7d00a1f@sentry.radarr.video/9";
|
||||
}
|
||||
|
||||
var target = new SentryTarget(dsn)
|
||||
{
|
||||
Name = "sentryTarget",
|
||||
Layout = "${message}"
|
||||
};
|
||||
|
||||
var loggingRule = new LoggingRule("*", updateClient ? LogLevel.Trace : LogLevel.Debug, target);
|
||||
LogManager.Configuration.AddTarget("sentryTarget", target);
|
||||
LogManager.Configuration.LoggingRules.Add(loggingRule);
|
||||
|
||||
// Events logged to Sentry go only to Sentry.
|
||||
var loggingRuleSentry = new LoggingRule("Sentry", LogLevel.Debug, target) { Final = true };
|
||||
LogManager.Configuration.LoggingRules.Insert(0, loggingRuleSentry);
|
||||
}
|
||||
|
||||
private static void RegisterDebugger()
|
||||
@@ -99,8 +115,6 @@ namespace NzbDrone.Common.Instrumentation
|
||||
LogManager.Configuration.LoggingRules.Add(loggingRule);
|
||||
}
|
||||
|
||||
const string FILE_LOG_LAYOUT = @"${date:format=yy-M-d HH\:mm\:ss.f}|${level}|${logger}|${message}${onexception:inner=${newline}${newline}[v${assembly-version}] ${exception:format=ToString}${newline}}";
|
||||
|
||||
private static void RegisterAppFile(IAppFolderInfo appFolderInfo)
|
||||
{
|
||||
RegisterAppFile(appFolderInfo, "appFileInfo", "radarr.txt", 5, LogLevel.Info);
|
||||
@@ -152,16 +166,6 @@ namespace NzbDrone.Common.Instrumentation
|
||||
LogManager.Configuration.LoggingRules.Add(loggingRule);
|
||||
}
|
||||
|
||||
private static void RegisterExceptron()
|
||||
{
|
||||
var exceptronTarget = new ExceptronTarget();
|
||||
var rule = new LoggingRule("*", LogLevel.Warn, exceptronTarget);
|
||||
|
||||
LogManager.Configuration.AddTarget("ExceptronTarget", exceptronTarget);
|
||||
LogManager.Configuration.LoggingRules.Add(rule);
|
||||
}
|
||||
|
||||
|
||||
public static Logger GetLogger(Type obj)
|
||||
{
|
||||
return LogManager.GetLogger(obj.Name.Replace("NzbDrone.", ""));
|
||||
|
||||
@@ -0,0 +1,12 @@
|
||||
using SharpRaven.Data;
|
||||
|
||||
namespace NzbDrone.Common.Instrumentation.Sentry
|
||||
{
|
||||
public class MachineNameUserFactory : ISentryUserFactory
|
||||
{
|
||||
public SentryUser Create()
|
||||
{
|
||||
return new SentryUser(HashUtil.AnonymousToken());
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,72 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using SharpRaven.Data;
|
||||
|
||||
namespace NzbDrone.Common.Instrumentation.Sentry
|
||||
{
|
||||
public class RadarrJsonPacketFactory : IJsonPacketFactory
|
||||
{
|
||||
private readonly SentryPacketCleanser _cleanser;
|
||||
|
||||
public RadarrJsonPacketFactory()
|
||||
{
|
||||
_cleanser = new SentryPacketCleanser();
|
||||
}
|
||||
|
||||
private static string ShortenPath(string path)
|
||||
{
|
||||
|
||||
if (string.IsNullOrWhiteSpace(path))
|
||||
{
|
||||
return null;
|
||||
}
|
||||
|
||||
var index = path.IndexOf("\\src\\", StringComparison.Ordinal);
|
||||
|
||||
if (index <= 0)
|
||||
{
|
||||
return path;
|
||||
}
|
||||
|
||||
return path.Substring(index + "\\src".Length);
|
||||
}
|
||||
|
||||
public JsonPacket Create(string project, SentryEvent @event)
|
||||
{
|
||||
var packet = new RadarrSentryPacket(project, @event);
|
||||
|
||||
try
|
||||
{
|
||||
foreach (var exception in packet.Exceptions)
|
||||
{
|
||||
foreach (var frame in exception.Stacktrace.Frames)
|
||||
{
|
||||
frame.Filename = ShortenPath(frame.Filename);
|
||||
}
|
||||
}
|
||||
|
||||
_cleanser.CleansePacket(packet);
|
||||
}
|
||||
catch (Exception)
|
||||
{
|
||||
|
||||
}
|
||||
|
||||
return packet;
|
||||
}
|
||||
|
||||
[Obsolete]
|
||||
public JsonPacket Create(string project, SentryMessage message, ErrorLevel level = ErrorLevel.Info, IDictionary<string, string> tags = null,
|
||||
string[] fingerprint = null, object extra = null)
|
||||
{
|
||||
throw new NotImplementedException();
|
||||
}
|
||||
|
||||
[Obsolete]
|
||||
public JsonPacket Create(string project, Exception exception, SentryMessage message = null, ErrorLevel level = ErrorLevel.Error,
|
||||
IDictionary<string, string> tags = null, string[] fingerprint = null, object extra = null)
|
||||
{
|
||||
throw new NotImplementedException();
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,31 @@
|
||||
using Newtonsoft.Json;
|
||||
using SharpRaven.Data;
|
||||
|
||||
namespace NzbDrone.Common.Instrumentation.Sentry
|
||||
{
|
||||
public class RadarrSentryPacket : JsonPacket
|
||||
{
|
||||
private readonly JsonSerializerSettings _setting;
|
||||
|
||||
public RadarrSentryPacket(string project, SentryEvent @event) :
|
||||
base(project, @event)
|
||||
{
|
||||
_setting = new JsonSerializerSettings
|
||||
{
|
||||
DefaultValueHandling = DefaultValueHandling.Ignore
|
||||
};
|
||||
|
||||
Breadcrumbs = @event.Breadcrumbs;
|
||||
}
|
||||
|
||||
public override string ToString(Formatting formatting)
|
||||
{
|
||||
return JsonConvert.SerializeObject(this, formatting, _setting);
|
||||
}
|
||||
|
||||
public override string ToString()
|
||||
{
|
||||
return ToString(Formatting.None);
|
||||
}
|
||||
}
|
||||
}
|
||||
38
src/NzbDrone.Common/Instrumentation/Sentry/SentryDebounce.cs
Normal file
38
src/NzbDrone.Common/Instrumentation/Sentry/SentryDebounce.cs
Normal file
@@ -0,0 +1,38 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using NzbDrone.Common.Cache;
|
||||
using NzbDrone.Common.EnvironmentInfo;
|
||||
|
||||
namespace NzbDrone.Common.Instrumentation.Sentry
|
||||
{
|
||||
public class SentryDebounce
|
||||
{
|
||||
private readonly TimeSpan _ttl;
|
||||
private readonly Cached<bool> _cache;
|
||||
|
||||
public SentryDebounce()
|
||||
{
|
||||
_cache = new Cached<bool>();
|
||||
_ttl = RuntimeInfo.IsProduction ? TimeSpan.FromHours(1) : TimeSpan.FromSeconds(10);
|
||||
}
|
||||
|
||||
public bool Allowed(IEnumerable<string> fingerPrint)
|
||||
{
|
||||
var key = string.Join("|", fingerPrint);
|
||||
var exists = _cache.Find(key);
|
||||
|
||||
if (exists)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
_cache.Set(key, true, _ttl);
|
||||
return true;
|
||||
}
|
||||
|
||||
public void Clear()
|
||||
{
|
||||
_cache.Clear();
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,53 @@
|
||||
using Newtonsoft.Json.Linq;
|
||||
using SharpRaven.Data;
|
||||
using System;
|
||||
using System.Linq;
|
||||
|
||||
namespace NzbDrone.Common.Instrumentation.Sentry
|
||||
{
|
||||
public class SentryPacketCleanser
|
||||
{
|
||||
public void CleansePacket(RadarrSentryPacket packet)
|
||||
{
|
||||
packet.Message = CleanseLogMessage.Cleanse(packet.Message);
|
||||
|
||||
if (packet.Fingerprint != null)
|
||||
{
|
||||
for (var i = 0; i < packet.Fingerprint.Length; i++)
|
||||
{
|
||||
packet.Fingerprint[i] = CleanseLogMessage.Cleanse(packet.Fingerprint[i]);
|
||||
}
|
||||
}
|
||||
|
||||
if (packet.Extra != null)
|
||||
{
|
||||
var target = JObject.FromObject(packet.Extra);
|
||||
new CleansingJsonVisitor().Visit(target);
|
||||
packet.Extra = target;
|
||||
}
|
||||
|
||||
if (packet.Breadcrumbs != null)
|
||||
{
|
||||
for (var i = 0; i < packet.Breadcrumbs.Count; i++)
|
||||
{
|
||||
packet.Breadcrumbs[i] = CleanseBreadcrumb(packet.Breadcrumbs[i]);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private static Breadcrumb CleanseBreadcrumb(Breadcrumb b)
|
||||
{
|
||||
try
|
||||
{
|
||||
var message = CleanseLogMessage.Cleanse(b.Message);
|
||||
var data = b.Data?.ToDictionary(x => x.Key, y => CleanseLogMessage.Cleanse(y.Value));
|
||||
return new Breadcrumb(b.Category) { Message = message, Type = b.Type, Data = data, Level = b.Level };
|
||||
}
|
||||
catch (Exception)
|
||||
{
|
||||
}
|
||||
|
||||
return b;
|
||||
}
|
||||
}
|
||||
}
|
||||
276
src/NzbDrone.Common/Instrumentation/Sentry/SentryTarget.cs
Normal file
276
src/NzbDrone.Common/Instrumentation/Sentry/SentryTarget.cs
Normal file
@@ -0,0 +1,276 @@
|
||||
using System;
|
||||
using System.Collections;
|
||||
using System.Collections.Generic;
|
||||
using System.Data.SQLite;
|
||||
using System.Linq;
|
||||
using System.Net;
|
||||
using System.Threading;
|
||||
using NLog;
|
||||
using NLog.Common;
|
||||
using NLog.Targets;
|
||||
using NzbDrone.Common.EnvironmentInfo;
|
||||
using SharpRaven;
|
||||
using SharpRaven.Data;
|
||||
|
||||
namespace NzbDrone.Common.Instrumentation.Sentry
|
||||
{
|
||||
[Target("Sentry")]
|
||||
public class SentryTarget : TargetWithLayout
|
||||
{
|
||||
private readonly RavenClient _client;
|
||||
|
||||
// don't report uninformative SQLite exceptions
|
||||
// busy/locked are benign https://forums.sonarr.tv/t/owin-sqlite-error-5-database-is-locked/5423/11
|
||||
// The others will be user configuration problems and silt up Sentry
|
||||
private static readonly HashSet<SQLiteErrorCode> FilteredSQLiteErrors = new HashSet<SQLiteErrorCode>
|
||||
{
|
||||
SQLiteErrorCode.Busy,
|
||||
SQLiteErrorCode.Locked,
|
||||
SQLiteErrorCode.Perm,
|
||||
SQLiteErrorCode.ReadOnly,
|
||||
SQLiteErrorCode.IoErr,
|
||||
SQLiteErrorCode.Corrupt,
|
||||
SQLiteErrorCode.Full,
|
||||
SQLiteErrorCode.CantOpen,
|
||||
SQLiteErrorCode.Auth
|
||||
};
|
||||
|
||||
// use string and not Type so we don't need a reference to the project
|
||||
// where these are defined
|
||||
private static readonly HashSet<string> FilteredExceptionTypeNames = new HashSet<string>
|
||||
{
|
||||
// UnauthorizedAccessExceptions will just be user configuration issues
|
||||
"UnauthorizedAccessException",
|
||||
|
||||
// Filter out people stuck in boot loops
|
||||
"CorruptDatabaseException",
|
||||
|
||||
// This also filters some people in boot loops
|
||||
"TinyIoCResolutionException"
|
||||
};
|
||||
|
||||
public static readonly List<string> FilteredExceptionMessages = new List<string>
|
||||
{
|
||||
// Swallow the many, many exceptions flowing through from Jackett
|
||||
"Jackett.Common.IndexerException",
|
||||
|
||||
// Fix openflixr being stupid with permissions
|
||||
"openflixr"
|
||||
};
|
||||
|
||||
// exception types in this list will additionally have the exception message added to the
|
||||
// sentry fingerprint. Make sure that this message doesn't vary by exception
|
||||
// (e.g. containing a path or a url) so that the sentry grouping is sensible
|
||||
private static readonly HashSet<string> IncludeExceptionMessageTypes = new HashSet<string>
|
||||
{
|
||||
"SQLiteException"
|
||||
};
|
||||
|
||||
private static readonly IDictionary<LogLevel, ErrorLevel> LoggingLevelMap = new Dictionary<LogLevel, ErrorLevel>
|
||||
{
|
||||
{LogLevel.Debug, ErrorLevel.Debug},
|
||||
{LogLevel.Error, ErrorLevel.Error},
|
||||
{LogLevel.Fatal, ErrorLevel.Fatal},
|
||||
{LogLevel.Info, ErrorLevel.Info},
|
||||
{LogLevel.Trace, ErrorLevel.Debug},
|
||||
{LogLevel.Warn, ErrorLevel.Warning},
|
||||
};
|
||||
|
||||
private static readonly IDictionary<LogLevel, BreadcrumbLevel> BreadcrumbLevelMap = new Dictionary<LogLevel, BreadcrumbLevel>
|
||||
{
|
||||
{ LogLevel.Debug, BreadcrumbLevel.Debug },
|
||||
{ LogLevel.Error, BreadcrumbLevel.Error },
|
||||
{ LogLevel.Fatal, BreadcrumbLevel.Critical },
|
||||
{ LogLevel.Info, BreadcrumbLevel.Info },
|
||||
{ LogLevel.Trace, BreadcrumbLevel.Debug },
|
||||
{ LogLevel.Warn, BreadcrumbLevel.Warning },
|
||||
};
|
||||
|
||||
private readonly SentryDebounce _debounce;
|
||||
private bool _unauthorized;
|
||||
|
||||
public bool FilterEvents { get; set; }
|
||||
|
||||
|
||||
public SentryTarget(string dsn)
|
||||
{
|
||||
_client = new RavenClient(new Dsn(dsn), new RadarrJsonPacketFactory(), new SentryRequestFactory(), new MachineNameUserFactory())
|
||||
{
|
||||
Compression = true,
|
||||
Environment = RuntimeInfo.IsProduction ? "production" : "development",
|
||||
Release = BuildInfo.Release,
|
||||
ErrorOnCapture = OnError
|
||||
};
|
||||
|
||||
|
||||
_client.Tags.Add("osfamily", OsInfo.Os.ToString());
|
||||
_client.Tags.Add("runtime", PlatformInfo.PlatformName);
|
||||
_client.Tags.Add("culture", Thread.CurrentThread.CurrentCulture.Name);
|
||||
_client.Tags.Add("branch", BuildInfo.Branch);
|
||||
_client.Tags.Add("version", BuildInfo.Version.ToString());
|
||||
|
||||
_debounce = new SentryDebounce();
|
||||
|
||||
FilterEvents = true;
|
||||
}
|
||||
|
||||
private void OnError(Exception ex)
|
||||
{
|
||||
var webException = ex as WebException;
|
||||
|
||||
if (webException != null)
|
||||
{
|
||||
var response = webException.Response as HttpWebResponse;
|
||||
var statusCode = response?.StatusCode;
|
||||
if (statusCode == HttpStatusCode.Unauthorized)
|
||||
{
|
||||
_unauthorized = true;
|
||||
_debounce.Clear();
|
||||
}
|
||||
}
|
||||
|
||||
InternalLogger.Error(ex, "Unable to send error to Sentry");
|
||||
}
|
||||
|
||||
private static List<string> GetFingerPrint(LogEventInfo logEvent)
|
||||
{
|
||||
if (logEvent.Properties.ContainsKey("Sentry"))
|
||||
{
|
||||
return ((string[])logEvent.Properties["Sentry"]).ToList();
|
||||
}
|
||||
|
||||
var fingerPrint = new List<string>
|
||||
{
|
||||
logEvent.Level.Ordinal.ToString(),
|
||||
logEvent.LoggerName,
|
||||
logEvent.Message
|
||||
};
|
||||
|
||||
var ex = logEvent.Exception;
|
||||
|
||||
if (ex != null)
|
||||
{
|
||||
fingerPrint.Add(ex.GetType().FullName);
|
||||
fingerPrint.Add(ex.TargetSite.ToString());
|
||||
if (ex.InnerException != null)
|
||||
{
|
||||
fingerPrint.Add(ex.InnerException.GetType().FullName);
|
||||
}
|
||||
else if (IncludeExceptionMessageTypes.Contains(ex.GetType().Name))
|
||||
{
|
||||
fingerPrint.Add(ex?.Message);
|
||||
}
|
||||
}
|
||||
|
||||
return fingerPrint;
|
||||
}
|
||||
|
||||
private bool IsSentryMessage(LogEventInfo logEvent)
|
||||
{
|
||||
if (logEvent.Properties.ContainsKey("Sentry"))
|
||||
{
|
||||
return logEvent.Properties["Sentry"] != null;
|
||||
}
|
||||
|
||||
if (logEvent.Level >= LogLevel.Error && logEvent.Exception != null)
|
||||
{
|
||||
if (FilterEvents)
|
||||
{
|
||||
var sqlEx = logEvent.Exception as SQLiteException;
|
||||
if (sqlEx != null && FilteredSQLiteErrors.Contains(sqlEx.ResultCode))
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
if (FilteredExceptionTypeNames.Contains(logEvent.Exception.GetType().Name))
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
if (FilteredExceptionMessages.Any(x => logEvent.Exception.Message.Contains(x)))
|
||||
{
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
|
||||
protected override void Write(LogEventInfo logEvent)
|
||||
{
|
||||
if (_unauthorized)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
try
|
||||
{
|
||||
_client.AddTrail(new Breadcrumb(logEvent.LoggerName) { Level = BreadcrumbLevelMap[logEvent.Level], Message = logEvent.FormattedMessage });
|
||||
|
||||
// don't report non-critical events without exceptions
|
||||
if (!IsSentryMessage(logEvent))
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
var fingerPrint = GetFingerPrint(logEvent);
|
||||
if (!_debounce.Allowed(fingerPrint))
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
var extras = logEvent.Properties.ToDictionary(x => x.Key.ToString(), x => x.Value.ToString());
|
||||
extras.Remove("Sentry");
|
||||
_client.Logger = logEvent.LoggerName;
|
||||
|
||||
if (logEvent.Exception != null)
|
||||
{
|
||||
foreach (DictionaryEntry data in logEvent.Exception.Data)
|
||||
{
|
||||
extras.Add(data.Key.ToString(), data.Value.ToString());
|
||||
}
|
||||
}
|
||||
|
||||
var sentryMessage = new SentryMessage(logEvent.Message, logEvent.Parameters);
|
||||
|
||||
var sentryEvent = new SentryEvent(logEvent.Exception)
|
||||
{
|
||||
Level = LoggingLevelMap[logEvent.Level],
|
||||
Message = sentryMessage,
|
||||
Extra = extras,
|
||||
Fingerprint =
|
||||
{
|
||||
logEvent.Level.ToString(),
|
||||
logEvent.LoggerName,
|
||||
logEvent.Message
|
||||
}
|
||||
};
|
||||
|
||||
if (logEvent.Exception != null)
|
||||
{
|
||||
sentryEvent.Fingerprint.Add(logEvent.Exception.GetType().FullName);
|
||||
}
|
||||
|
||||
if (logEvent.Properties.ContainsKey("Sentry"))
|
||||
{
|
||||
sentryEvent.Fingerprint.Clear();
|
||||
Array.ForEach((string[])logEvent.Properties["Sentry"], sentryEvent.Fingerprint.Add);
|
||||
}
|
||||
|
||||
var runTimeVersion = Environment.GetEnvironmentVariable("RUNTIME_VERSION");
|
||||
|
||||
sentryEvent.Tags.Add("runtime_version", $"{PlatformInfo.PlatformName} {runTimeVersion}");
|
||||
|
||||
_client.Capture(sentryEvent);
|
||||
}
|
||||
catch (Exception e)
|
||||
{
|
||||
OnError(e);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -39,9 +39,8 @@
|
||||
<WarningLevel>4</WarningLevel>
|
||||
</PropertyGroup>
|
||||
<ItemGroup>
|
||||
<Reference Include="Newtonsoft.Json, Version=6.0.0.0, Culture=neutral, PublicKeyToken=30ad4fe6b2a6aeed, processorArchitecture=MSIL">
|
||||
<SpecificVersion>False</SpecificVersion>
|
||||
<HintPath>..\packages\Newtonsoft.Json.6.0.6\lib\net40\Newtonsoft.Json.dll</HintPath>
|
||||
<Reference Include="Newtonsoft.Json, Version=9.0.0.0, Culture=neutral, PublicKeyToken=30ad4fe6b2a6aeed, processorArchitecture=MSIL">
|
||||
<HintPath>..\packages\Newtonsoft.Json.9.0.1\lib\net40\Newtonsoft.Json.dll</HintPath>
|
||||
</Reference>
|
||||
<Reference Include="NLog, Version=4.0.0.0, Culture=neutral, PublicKeyToken=5120e14c03d0593c, processorArchitecture=MSIL">
|
||||
<HintPath>..\packages\NLog.4.5.0-rc06\lib\net40-client\NLog.dll</HintPath>
|
||||
@@ -50,6 +49,9 @@
|
||||
<HintPath>..\packages\DotNet4.SocksProxy.1.3.2.0\lib\net40\Org.Mentalis.dll</HintPath>
|
||||
<Private>True</Private>
|
||||
</Reference>
|
||||
<Reference Include="SharpRaven, Version=2.4.0.0, Culture=neutral, processorArchitecture=MSIL">
|
||||
<HintPath>..\packages\SharpRaven.2.4.0\lib\net40\SharpRaven.dll</HintPath>
|
||||
</Reference>
|
||||
<Reference Include="SocksWebProxy, Version=1.3.2.0, Culture=neutral, processorArchitecture=MSIL">
|
||||
<HintPath>..\packages\DotNet4.SocksProxy.1.3.2.0\lib\net40\SocksWebProxy.dll</HintPath>
|
||||
<Private>True</Private>
|
||||
@@ -57,6 +59,9 @@
|
||||
<Reference Include="System" />
|
||||
<Reference Include="System.Configuration" />
|
||||
<Reference Include="System.Configuration.Install" />
|
||||
<Reference Include="System.Data.SQLite">
|
||||
<HintPath>..\Libraries\Sqlite\System.Data.SQLite.dll</HintPath>
|
||||
</Reference>
|
||||
<Reference Include="System.Core" />
|
||||
<Reference Include="System.Data" />
|
||||
<Reference Include="System.Drawing" />
|
||||
@@ -94,6 +99,11 @@
|
||||
<Compile Include="Disk\RelativeFileSystemModel.cs" />
|
||||
<Compile Include="Disk\FileSystemModel.cs" />
|
||||
<Compile Include="Disk\FileSystemResult.cs" />
|
||||
<Compile Include="EnvironmentInfo\IOperatingSystemVersionInfo.cs" />
|
||||
<Compile Include="EnvironmentInfo\IOsVersionAdapter.cs" />
|
||||
<Compile Include="EnvironmentInfo\IPlatformInfo.cs" />
|
||||
<Compile Include="EnvironmentInfo\OsVersionModel.cs" />
|
||||
<Compile Include="Exceptions\RadarrStartupException.cs" />
|
||||
<Compile Include="Extensions\DictionaryExtensions.cs" />
|
||||
<Compile Include="Disk\GdiPlusInterop.cs" />
|
||||
<Compile Include="Disk\OsPath.cs" />
|
||||
@@ -125,13 +135,12 @@
|
||||
<Compile Include="EnvironmentInfo\BuildInfo.cs" />
|
||||
<Compile Include="EnvironmentInfo\OsInfo.cs" />
|
||||
<Compile Include="EnvironmentInfo\IRuntimeInfo.cs" />
|
||||
<Compile Include="EnvironmentInfo\RuntimeInfoBase.cs" />
|
||||
<Compile Include="EnvironmentInfo\RuntimeInfo.cs" />
|
||||
<Compile Include="EnvironmentInfo\StartupContext.cs" />
|
||||
<Compile Include="Exceptions\NotParentException.cs" />
|
||||
<Compile Include="Exceptions\NzbDroneException.cs" />
|
||||
<Compile Include="Exceptron\Configuration\ExceptronConfiguration.cs" />
|
||||
<Compile Include="Exceptron\ExceptionData.cs" />
|
||||
<Compile Include="Exceptron\ExceptionExtentions.cs" />
|
||||
<Compile Include="Exceptron\ExceptionSeverity.cs" />
|
||||
<Compile Include="Exceptron\ExceptronApiException.cs" />
|
||||
<Compile Include="Exceptron\ExceptronClient.cs" />
|
||||
@@ -190,16 +199,24 @@
|
||||
<Compile Include="Http\HttpRequestBuilder.cs" />
|
||||
<Compile Include="Http\HttpRequestBuilderFactory.cs" />
|
||||
<Compile Include="Http\Proxy\ProxyType.cs" />
|
||||
<Compile Include="Http\TlsFailureException.cs" />
|
||||
<Compile Include="Http\TooManyRequestsException.cs" />
|
||||
<Compile Include="Extensions\IEnumerableExtensions.cs" />
|
||||
<Compile Include="Http\UnexpectedHtmlContentException.cs" />
|
||||
<Compile Include="Http\UserAgentBuilder.cs" />
|
||||
<Compile Include="Instrumentation\CleanseLogMessage.cs" />
|
||||
<Compile Include="Instrumentation\ExceptronTarget.cs" />
|
||||
<Compile Include="Instrumentation\CleansingJsonVisitor.cs" />
|
||||
<Compile Include="Instrumentation\Extensions\LoggerProgressExtensions.cs" />
|
||||
<Compile Include="Instrumentation\GlobalExceptionHandlers.cs" />
|
||||
<Compile Include="Instrumentation\LogEventExtensions.cs" />
|
||||
<Compile Include="Instrumentation\NzbDroneFileTarget.cs" />
|
||||
<Compile Include="Instrumentation\NzbDroneLogger.cs" />
|
||||
<Compile Include="Instrumentation\Sentry\MachineNameUserFactory.cs" />
|
||||
<Compile Include="Instrumentation\Sentry\RadarrJsonPacketFactory.cs" />
|
||||
<Compile Include="Instrumentation\Sentry\RadarrSentryPacket.cs" />
|
||||
<Compile Include="Instrumentation\Sentry\SentryDebounce.cs" />
|
||||
<Compile Include="Instrumentation\Sentry\SentryPacketCleanser.cs" />
|
||||
<Compile Include="Instrumentation\Sentry\SentryTarget.cs" />
|
||||
<Compile Include="Instrumentation\VersionLayoutRenderer.cs" />
|
||||
<Compile Include="Extensions\LevenstheinExtensions.cs" />
|
||||
<Compile Include="Messaging\IEvent.cs" />
|
||||
@@ -220,6 +237,7 @@
|
||||
<Compile Include="Serializer\HttpUriConverter.cs" />
|
||||
<Compile Include="Serializer\IntConverter.cs" />
|
||||
<Compile Include="Serializer\Json.cs" />
|
||||
<Compile Include="Serializer\JsonVisitor.cs" />
|
||||
<Compile Include="Serializer\UnderscoreStringEnumConverter.cs" />
|
||||
<Compile Include="ServiceFactory.cs" />
|
||||
<Compile Include="ServiceProvider.cs" />
|
||||
@@ -252,10 +270,6 @@
|
||||
<Project>{74420a79-cc16-442c-8b1e-7c1b913844f0}</Project>
|
||||
<Name>CurlSharp</Name>
|
||||
</ProjectReference>
|
||||
<ProjectReference Include="..\LogentriesNLog\LogentriesNLog.csproj">
|
||||
<Project>{9DC31DE3-79FF-47A8-96B4-6BA18F6BB1CB}</Project>
|
||||
<Name>LogentriesNLog</Name>
|
||||
</ProjectReference>
|
||||
</ItemGroup>
|
||||
<Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" />
|
||||
<!-- To modify your build process, add your task inside one of the targets below and uncomment it.
|
||||
|
||||
@@ -1,7 +1,8 @@
|
||||
using System;
|
||||
using System;
|
||||
using System.IO;
|
||||
using NLog;
|
||||
using NzbDrone.Common.EnvironmentInfo;
|
||||
using NzbDrone.Common.Exceptions;
|
||||
|
||||
namespace NzbDrone.Common.Processes
|
||||
{
|
||||
@@ -37,8 +38,8 @@ namespace NzbDrone.Common.Processes
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_logger.Error(ex, "Unable to write PID file: " + filename);
|
||||
throw;
|
||||
_logger.Error(ex, "Unable to write PID file: {0}", filename);
|
||||
throw new RadarrStartupException(ex, "Unable to write PID file {0}", filename);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -108,7 +108,7 @@ namespace NzbDrone.Common.Processes
|
||||
|
||||
public Process Start(string path, string args = null, StringDictionary environmentVariables = null, Action<string> onOutputDataReceived = null, Action<string> onErrorDataReceived = null)
|
||||
{
|
||||
if (OsInfo.IsMonoRuntime && path.EndsWith(".exe", StringComparison.InvariantCultureIgnoreCase))
|
||||
if (PlatformInfo.IsMono && path.EndsWith(".exe", StringComparison.InvariantCultureIgnoreCase))
|
||||
{
|
||||
args = GetMonoArgs(path, args);
|
||||
path = "mono";
|
||||
@@ -192,7 +192,7 @@ namespace NzbDrone.Common.Processes
|
||||
|
||||
public Process SpawnNewProcess(string path, string args = null, StringDictionary environmentVariables = null)
|
||||
{
|
||||
if (OsInfo.IsMonoRuntime && path.EndsWith(".exe", StringComparison.InvariantCultureIgnoreCase))
|
||||
if (PlatformInfo.IsMono && path.EndsWith(".exe", StringComparison.InvariantCultureIgnoreCase))
|
||||
{
|
||||
args = GetMonoArgs(path, args);
|
||||
path = "mono";
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
using System.Reflection;
|
||||
using System.Runtime.InteropServices;
|
||||
|
||||
[assembly: AssemblyConfiguration("")]
|
||||
[assembly: AssemblyConfiguration("debug")]
|
||||
[assembly: AssemblyCompany("radarr.video")]
|
||||
[assembly: AssemblyProduct("Radarr")]
|
||||
[assembly: AssemblyVersion("10.0.0.*")]
|
||||
|
||||
95
src/NzbDrone.Common/Serializer/JsonVisitor.cs
Normal file
95
src/NzbDrone.Common/Serializer/JsonVisitor.cs
Normal file
@@ -0,0 +1,95 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
using Newtonsoft.Json.Linq;
|
||||
|
||||
namespace NzbDrone.Common.Serializer
|
||||
{
|
||||
|
||||
public class JsonVisitor
|
||||
{
|
||||
protected void Dispatch(JToken json)
|
||||
{
|
||||
switch (json.Type)
|
||||
{
|
||||
case JTokenType.Object:
|
||||
Visit(json as JObject);
|
||||
break;
|
||||
|
||||
case JTokenType.Array:
|
||||
Visit(json as JArray);
|
||||
break;
|
||||
|
||||
case JTokenType.Raw:
|
||||
Visit(json as JRaw);
|
||||
break;
|
||||
|
||||
case JTokenType.Constructor:
|
||||
Visit(json as JConstructor);
|
||||
break;
|
||||
|
||||
case JTokenType.Property:
|
||||
Visit(json as JProperty);
|
||||
break;
|
||||
|
||||
case JTokenType.Comment:
|
||||
case JTokenType.Integer:
|
||||
case JTokenType.Float:
|
||||
case JTokenType.String:
|
||||
case JTokenType.Boolean:
|
||||
case JTokenType.Null:
|
||||
case JTokenType.Undefined:
|
||||
case JTokenType.Date:
|
||||
case JTokenType.Bytes:
|
||||
case JTokenType.Guid:
|
||||
case JTokenType.Uri:
|
||||
case JTokenType.TimeSpan:
|
||||
Visit(json as JValue);
|
||||
break;
|
||||
|
||||
default:
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
public virtual void Visit(JToken json)
|
||||
{
|
||||
Dispatch(json);
|
||||
}
|
||||
|
||||
public virtual void Visit(JContainer json)
|
||||
{
|
||||
Dispatch(json);
|
||||
}
|
||||
|
||||
public virtual void Visit(JArray json)
|
||||
{
|
||||
foreach (JToken token in json)
|
||||
{
|
||||
Visit(token);
|
||||
}
|
||||
}
|
||||
public virtual void Visit(JConstructor json)
|
||||
{
|
||||
}
|
||||
|
||||
public virtual void Visit(JObject json)
|
||||
{
|
||||
foreach (JProperty property in json.Properties())
|
||||
{
|
||||
Visit(property);
|
||||
}
|
||||
}
|
||||
|
||||
public virtual void Visit(JProperty property)
|
||||
{
|
||||
Visit(property.Value);
|
||||
}
|
||||
|
||||
public virtual void Visit(JValue value)
|
||||
{
|
||||
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -4,7 +4,7 @@
|
||||
<assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">
|
||||
<dependentAssembly>
|
||||
<assemblyIdentity name="Newtonsoft.Json" publicKeyToken="30ad4fe6b2a6aeed" culture="neutral" />
|
||||
<bindingRedirect oldVersion="0.0.0.0-6.0.0.0" newVersion="6.0.0.0" />
|
||||
<bindingRedirect oldVersion="0.0.0.0-9.0.0.0" newVersion="9.0.0.0" />
|
||||
</dependentAssembly>
|
||||
</assemblyBinding>
|
||||
</runtime>
|
||||
|
||||
@@ -2,7 +2,8 @@
|
||||
<packages>
|
||||
<package id="DotNet4.SocksProxy" version="1.3.2.0" targetFramework="net40" />
|
||||
<package id="ICSharpCode.SharpZipLib.Patched" version="0.86.5" targetFramework="net40" />
|
||||
<package id="Newtonsoft.Json" version="6.0.6" targetFramework="net40" />
|
||||
<package id="Newtonsoft.Json" version="9.0.1" targetFramework="net40" />
|
||||
<package id="NLog" version="4.5.0-rc06" targetFramework="net40" />
|
||||
<package id="SharpRaven" version="2.4.0" targetFramework="net40" />
|
||||
<package id="System.ValueTuple" version="4.5.0" targetFramework="net40" />
|
||||
</packages>
|
||||
@@ -2,6 +2,7 @@ using System;
|
||||
using System.Net.Sockets;
|
||||
using NLog;
|
||||
using NzbDrone.Common.EnvironmentInfo;
|
||||
using NzbDrone.Common.Exceptions;
|
||||
using NzbDrone.Common.Instrumentation;
|
||||
using Radarr.Host;
|
||||
|
||||
@@ -15,7 +16,8 @@ namespace NzbDrone.Console
|
||||
{
|
||||
Normal = 0,
|
||||
UnknownFailure = 1,
|
||||
RecoverableFailure = 2
|
||||
RecoverableFailure = 2,
|
||||
NonRecoverableFailure = 3
|
||||
}
|
||||
|
||||
public static void Main(string[] args)
|
||||
@@ -34,6 +36,13 @@ namespace NzbDrone.Console
|
||||
}
|
||||
Bootstrap.Start(startupArgs, new ConsoleAlerts());
|
||||
}
|
||||
catch (RadarrStartupException ex)
|
||||
{
|
||||
System.Console.WriteLine("");
|
||||
System.Console.WriteLine("");
|
||||
Logger.Fatal(ex, "EPIC FAIL!");
|
||||
Exit(ExitCodes.NonRecoverableFailure);
|
||||
}
|
||||
catch (SocketException e)
|
||||
{
|
||||
System.Console.WriteLine("");
|
||||
@@ -53,7 +62,6 @@ namespace NzbDrone.Console
|
||||
|
||||
Exit(ExitCodes.Normal);
|
||||
}
|
||||
|
||||
private static void Exit(ExitCodes exitCode)
|
||||
{
|
||||
LogManager.Shutdown();
|
||||
@@ -64,6 +72,19 @@ namespace NzbDrone.Console
|
||||
|
||||
System.Threading.Thread.Sleep(1000);
|
||||
|
||||
if (exitCode == ExitCodes.NonRecoverableFailure)
|
||||
{
|
||||
System.Console.WriteLine("Non-recoverable failure, waiting for user intervention...");
|
||||
for (int i = 0; i < 3600; i++)
|
||||
{
|
||||
System.Threading.Thread.Sleep(1000);
|
||||
if (System.Console.KeyAvailable)
|
||||
{
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Please note that ReadLine silently succeeds if there is no console, KeyAvailable does not.
|
||||
System.Console.ReadLine();
|
||||
}
|
||||
|
||||
@@ -72,9 +72,8 @@
|
||||
<SpecificVersion>False</SpecificVersion>
|
||||
<HintPath>..\packages\Microsoft.Owin.Hosting.2.1.0\lib\net40\Microsoft.Owin.Hosting.dll</HintPath>
|
||||
</Reference>
|
||||
<Reference Include="Newtonsoft.Json, Version=6.0.0.0, Culture=neutral, PublicKeyToken=30ad4fe6b2a6aeed, processorArchitecture=MSIL">
|
||||
<SpecificVersion>False</SpecificVersion>
|
||||
<HintPath>..\packages\Newtonsoft.Json.6.0.6\lib\net40\Newtonsoft.Json.dll</HintPath>
|
||||
<Reference Include="Newtonsoft.Json, Version=9.0.0.0, Culture=neutral, PublicKeyToken=30ad4fe6b2a6aeed, processorArchitecture=MSIL">
|
||||
<HintPath>..\packages\Newtonsoft.Json.9.0.1\lib\net40\Newtonsoft.Json.dll</HintPath>
|
||||
</Reference>
|
||||
<Reference Include="NLog, Version=4.0.0.0, Culture=neutral, PublicKeyToken=5120e14c03d0593c, processorArchitecture=MSIL">
|
||||
<HintPath>..\packages\NLog.4.5.0-rc06\lib\net40-client\NLog.dll</HintPath>
|
||||
|
||||
@@ -2,7 +2,7 @@
|
||||
<packages>
|
||||
<package id="Microsoft.Owin" version="2.1.0" targetFramework="net40" />
|
||||
<package id="Microsoft.Owin.Hosting" version="2.1.0" targetFramework="net40" />
|
||||
<package id="Newtonsoft.Json" version="6.0.6" targetFramework="net40" />
|
||||
<package id="Newtonsoft.Json" version="9.0.1" targetFramework="net40" />
|
||||
<package id="NLog" version="4.5.0-rc06" targetFramework="net40" />
|
||||
<package id="Owin" version="1.0" targetFramework="net40" />
|
||||
</packages>
|
||||
@@ -9,6 +9,7 @@ using NzbDrone.Core.MediaFiles.TorrentInfo;
|
||||
using NzbDrone.Core.Download;
|
||||
using NzbDrone.Core.Download.Clients.QBittorrent;
|
||||
using NzbDrone.Test.Common;
|
||||
using NzbDrone.Core.Exceptions;
|
||||
|
||||
namespace NzbDrone.Core.Test.Download.DownloadClientTests.QBittorrentTests
|
||||
{
|
||||
@@ -37,8 +38,12 @@ namespace NzbDrone.Core.Test.Download.DownloadClientTests.QBittorrentTests
|
||||
.Returns<HttpRequest>(r => new HttpResponse(r, new HttpHeader(), new Byte[0]));
|
||||
|
||||
Mocker.GetMock<IQBittorrentProxy>()
|
||||
.Setup(s => s.GetConfig(It.IsAny<QBittorrentSettings>()))
|
||||
.Returns(new QBittorrentPreferences());
|
||||
.Setup(s => s.GetConfig(It.IsAny<QBittorrentSettings>()))
|
||||
.Returns(new QBittorrentPreferences() { DhtEnabled = true });
|
||||
|
||||
Mocker.GetMock<IQBittorrentProxySelector>()
|
||||
.Setup(s => s.GetProxy(It.IsAny<QBittorrentSettings>(), It.IsAny<bool>()))
|
||||
.Returns(Mocker.GetMock<IQBittorrentProxy>().Object);
|
||||
}
|
||||
|
||||
protected void GivenRedirectToMagnet()
|
||||
@@ -154,7 +159,7 @@ namespace NzbDrone.Core.Test.Download.DownloadClientTests.QBittorrentTests
|
||||
|
||||
var item = Subject.GetItems().Single();
|
||||
VerifyPaused(item);
|
||||
item.RemainingTime.Should().NotBe(TimeSpan.Zero);
|
||||
item.RemainingTime.Should().NotHaveValue();
|
||||
}
|
||||
|
||||
[TestCase("pausedUP")]
|
||||
@@ -162,6 +167,7 @@ namespace NzbDrone.Core.Test.Download.DownloadClientTests.QBittorrentTests
|
||||
[TestCase("uploading")]
|
||||
[TestCase("stalledUP")]
|
||||
[TestCase("checkingUP")]
|
||||
[TestCase("forcedUP")]
|
||||
public void completed_item_should_have_required_properties(string state)
|
||||
{
|
||||
var torrent = new QBittorrentTorrent
|
||||
@@ -184,6 +190,7 @@ namespace NzbDrone.Core.Test.Download.DownloadClientTests.QBittorrentTests
|
||||
|
||||
[TestCase("queuedDL")]
|
||||
[TestCase("checkingDL")]
|
||||
[TestCase("metaDL")]
|
||||
public void queued_item_should_have_required_properties(string state)
|
||||
{
|
||||
var torrent = new QBittorrentTorrent
|
||||
@@ -201,7 +208,7 @@ namespace NzbDrone.Core.Test.Download.DownloadClientTests.QBittorrentTests
|
||||
|
||||
var item = Subject.GetItems().Single();
|
||||
VerifyQueued(item);
|
||||
item.RemainingTime.Should().NotBe(TimeSpan.Zero);
|
||||
item.RemainingTime.Should().NotHaveValue();
|
||||
}
|
||||
|
||||
[Test]
|
||||
@@ -243,7 +250,7 @@ namespace NzbDrone.Core.Test.Download.DownloadClientTests.QBittorrentTests
|
||||
|
||||
var item = Subject.GetItems().Single();
|
||||
VerifyWarning(item);
|
||||
item.RemainingTime.Should().NotBe(TimeSpan.Zero);
|
||||
item.RemainingTime.Should().NotHaveValue();
|
||||
}
|
||||
|
||||
[Test]
|
||||
@@ -271,6 +278,35 @@ namespace NzbDrone.Core.Test.Download.DownloadClientTests.QBittorrentTests
|
||||
id.Should().Be(expectedHash);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void Download_should_refuse_magnet_if_no_trackers_provided_and_dht_is_disabled()
|
||||
{
|
||||
Mocker.GetMock<IQBittorrentProxy>()
|
||||
.Setup(s => s.GetConfig(It.IsAny<QBittorrentSettings>()))
|
||||
.Returns(new QBittorrentPreferences() { DhtEnabled = false });
|
||||
|
||||
var remoteMovie = CreateRemoteMovie();
|
||||
remoteMovie.Release.DownloadUrl = "magnet:?xt=urn:btih:ZPBPA2P6ROZPKRHK44D5OW6NHXU5Z6KR";
|
||||
|
||||
Assert.Throws<ReleaseDownloadException>(() => Subject.Download(remoteMovie));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void Download_should_accept_magnet_if_trackers_provided_and_dht_is_disabled()
|
||||
{
|
||||
Mocker.GetMock<IQBittorrentProxy>()
|
||||
.Setup(s => s.GetConfig(It.IsAny<QBittorrentSettings>()))
|
||||
.Returns(new QBittorrentPreferences() { DhtEnabled = false });
|
||||
|
||||
var remoteMovie = CreateRemoteMovie();
|
||||
remoteMovie.Release.DownloadUrl = "magnet:?xt=urn:btih:ZPBPA2P6ROZPKRHK44D5OW6NHXU5Z6KR&tr=udp://abc";
|
||||
|
||||
Assert.DoesNotThrow(() => Subject.Download(remoteMovie));
|
||||
|
||||
Mocker.GetMock<IQBittorrentProxy>()
|
||||
.Verify(s => s.AddTorrentFromUrl(It.IsAny<string>(), It.IsAny<QBittorrentSettings>()), Times.Once());
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void Download_should_set_top_priority()
|
||||
{
|
||||
@@ -494,5 +530,19 @@ namespace NzbDrone.Core.Test.Download.DownloadClientTests.QBittorrentTests
|
||||
var item = Subject.GetItems().Single();
|
||||
item.Category.Should().Be(category);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void Test_should_force_api_version_check()
|
||||
{
|
||||
// Set TestConnection up to fail quick
|
||||
Mocker.GetMock<IQBittorrentProxy>()
|
||||
.Setup(v => v.GetApiVersion(It.IsAny<QBittorrentSettings>()))
|
||||
.Returns(new Version(1, 0));
|
||||
|
||||
Subject.Test();
|
||||
|
||||
Mocker.GetMock<IQBittorrentProxySelector>()
|
||||
.Verify(v => v.GetProxy(It.IsAny<QBittorrentSettings>(), true), Times.Once());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,9 +1,9 @@
|
||||
using System.Collections.Specialized;
|
||||
using System.Security.AccessControl;
|
||||
using Moq;
|
||||
using System;
|
||||
using NUnit.Framework;
|
||||
using NzbDrone.Common.Cache;
|
||||
using NzbDrone.Common.Cloud;
|
||||
using NzbDrone.Common.EnvironmentInfo;
|
||||
using NzbDrone.Common.Http;
|
||||
using NzbDrone.Common.Http.Dispatchers;
|
||||
using NzbDrone.Common.TPL;
|
||||
@@ -24,12 +24,16 @@ namespace NzbDrone.Core.Test.Framework
|
||||
{
|
||||
protected void UseRealHttp()
|
||||
{
|
||||
Mocker.GetMock<IPlatformInfo>().SetupGet(c => c.Version).Returns(new Version("3.0.0"));
|
||||
Mocker.GetMock<IOsInfo>().SetupGet(c => c.Version).Returns("1.0.0");
|
||||
Mocker.GetMock<IOsInfo>().SetupGet(c => c.Name).Returns("TestOS");
|
||||
|
||||
Mocker.SetConstant<IHttpProxySettingsProvider>(new HttpProxySettingsProvider(Mocker.Resolve<ConfigService>()));
|
||||
Mocker.SetConstant<ICreateManagedWebProxy>(new ManagedWebProxyFactory(Mocker.Resolve<CacheManager>()));
|
||||
Mocker.SetConstant<ManagedHttpDispatcher>(new ManagedHttpDispatcher(Mocker.Resolve<IHttpProxySettingsProvider>(), Mocker.Resolve<ICreateManagedWebProxy>()));
|
||||
Mocker.SetConstant<CurlHttpDispatcher>(new CurlHttpDispatcher(Mocker.Resolve<IHttpProxySettingsProvider>(), Mocker.Resolve<NLog.Logger>()));
|
||||
Mocker.SetConstant<ManagedHttpDispatcher>(new ManagedHttpDispatcher(Mocker.Resolve<IHttpProxySettingsProvider>(), Mocker.Resolve<ICreateManagedWebProxy>(), Mocker.Resolve<UserAgentBuilder>(), Mocker.Resolve<IPlatformInfo>(), TestLogger));
|
||||
Mocker.SetConstant<CurlHttpDispatcher>(new CurlHttpDispatcher(Mocker.Resolve<IHttpProxySettingsProvider>(), Mocker.Resolve<UserAgentBuilder>(), TestLogger));
|
||||
Mocker.SetConstant<IHttpProvider>(new HttpProvider(TestLogger));
|
||||
Mocker.SetConstant<IHttpClient>(new HttpClient(new IHttpRequestInterceptor[0], Mocker.Resolve<CacheManager>(), Mocker.Resolve<RateLimitService>(), Mocker.Resolve<FallbackHttpDispatcher>(), TestLogger));
|
||||
Mocker.SetConstant<IHttpClient>(new HttpClient(new IHttpRequestInterceptor[0], Mocker.Resolve<CacheManager>(), Mocker.Resolve<RateLimitService>(), Mocker.Resolve<FallbackHttpDispatcher>(), Mocker.Resolve<UserAgentBuilder>(), TestLogger));
|
||||
Mocker.SetConstant<IRadarrCloudRequestBuilder>(new RadarrCloudRequestBuilder());
|
||||
}
|
||||
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
using NUnit.Framework;
|
||||
using System;
|
||||
using NUnit.Framework;
|
||||
using NzbDrone.Common.EnvironmentInfo;
|
||||
using NzbDrone.Core.HealthCheck.Checks;
|
||||
using NzbDrone.Core.Test.Framework;
|
||||
@@ -8,17 +9,12 @@ namespace NzbDrone.Core.Test.HealthCheck.Checks
|
||||
[TestFixture]
|
||||
public class MonoVersionCheckFixture : CoreTest<MonoVersionCheck>
|
||||
{
|
||||
[SetUp]
|
||||
public void Setup()
|
||||
{
|
||||
MonoOnly();
|
||||
}
|
||||
|
||||
private void GivenOutput(string version)
|
||||
{
|
||||
Mocker.GetMock<IRuntimeInfo>()
|
||||
.SetupGet(s => s.RuntimeVersion)
|
||||
.Returns(string.Format("{0} (tarball Wed Sep 25 16:35:44 CDT 2013)", version));
|
||||
MonoOnly();
|
||||
Mocker.GetMock<IPlatformInfo>()
|
||||
.SetupGet(s => s.Version)
|
||||
.Returns(new Version(version));
|
||||
}
|
||||
|
||||
[TestCase("3.10")]
|
||||
|
||||
@@ -0,0 +1,85 @@
|
||||
using System.Linq;
|
||||
using FluentAssertions;
|
||||
using Newtonsoft.Json;
|
||||
using NUnit.Framework;
|
||||
using NzbDrone.Common.Http;
|
||||
using NzbDrone.Core.Indexers.HDBits;
|
||||
using NzbDrone.Core.IndexerSearch.Definitions;
|
||||
using NzbDrone.Core.Test.Framework;
|
||||
|
||||
namespace NzbDrone.Core.Test.IndexerTests.HDBitsTests
|
||||
{
|
||||
public class HDBitsRequestGeneratorFixture : CoreTest<HDBitsRequestGenerator>
|
||||
{
|
||||
private MovieSearchCriteria _movieSearchCriteria;
|
||||
|
||||
[SetUp]
|
||||
public void Setup()
|
||||
{
|
||||
Subject.Settings = new HDBitsSettings()
|
||||
{
|
||||
BaseUrl = "http://127.0.0.1:1234/",
|
||||
Categories = new[] { 1, 2 },
|
||||
ApiKey = "abcd",
|
||||
Username = "somename"
|
||||
};
|
||||
|
||||
_movieSearchCriteria = new MovieSearchCriteria
|
||||
{
|
||||
Movie = new Movies.Movie { ImdbId = "tt0076759", Title = "Star Wars", Year = 1977 }
|
||||
};
|
||||
}
|
||||
|
||||
private void MovieWithoutIMDB()
|
||||
{
|
||||
_movieSearchCriteria.Movie.ImdbId = null;
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void should_use_all_categories_for_feed()
|
||||
{
|
||||
var results = Subject.GetRecentRequests();
|
||||
|
||||
results.GetAllTiers().Should().HaveCount(1);
|
||||
|
||||
var page = results.GetAllTiers().First().First();
|
||||
|
||||
var encoding = HttpHeader.GetEncodingFromContentType(page.HttpRequest.Headers.ContentType);
|
||||
|
||||
var body = encoding.GetString(page.HttpRequest.ContentData);
|
||||
var query = JsonConvert.DeserializeObject<TorrentQuery>(body);
|
||||
|
||||
query.Category.Should().HaveCount(2);
|
||||
query.Username.Should().Be(Subject.Settings.Username);
|
||||
query.Passkey.Should().Be(Subject.Settings.ApiKey);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void should_search_by_imdbid_if_supported()
|
||||
{
|
||||
var results = Subject.GetSearchRequests(_movieSearchCriteria);
|
||||
var imdbQuery = int.Parse(_movieSearchCriteria.Movie.ImdbId.Substring(2));
|
||||
|
||||
results.GetAllTiers().Should().HaveCount(1);
|
||||
|
||||
var page = results.GetAllTiers().First().First();
|
||||
|
||||
var encoding = HttpHeader.GetEncodingFromContentType(page.HttpRequest.Headers.ContentType);
|
||||
|
||||
var body = encoding.GetString(page.HttpRequest.ContentData);
|
||||
var query = JsonConvert.DeserializeObject<TorrentQuery>(body);
|
||||
|
||||
query.Category.Should().HaveCount(2);
|
||||
query.ImdbInfo.Id.Should().Be(imdbQuery);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void should_return_no_results_if_no_imdb()
|
||||
{
|
||||
MovieWithoutIMDB();
|
||||
|
||||
var results = Subject.GetSearchRequests(_movieSearchCriteria);
|
||||
results.GetTier(0).Should().HaveCount(0);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -48,7 +48,7 @@ namespace NzbDrone.Core.Test.IndexerTests.RarbgTests
|
||||
torrentInfo.Title.Should().Be("Sense8.S01E01.WEBRip.x264-FGT");
|
||||
torrentInfo.DownloadProtocol.Should().Be(DownloadProtocol.Torrent);
|
||||
torrentInfo.DownloadUrl.Should().Be("magnet:?xt=urn:btih:d8bde635f573acb390c7d7e7efc1556965fdc802&dn=Sense8.S01E01.WEBRip.x264-FGT&tr=http%3A%2F%2Ftracker.trackerfix.com%3A80%2Fannounce&tr=udp%3A%2F%2F9.rarbg.me%3A2710&tr=udp%3A%2F%2F9.rarbg.to%3A2710&tr=udp%3A%2F%2Fopen.demonii.com%3A1337%2Fannounce");
|
||||
torrentInfo.InfoUrl.Should().Be("https://torrentapi.org/redirect_to_info.php?token=i5cx7b9agd&p=8_6_4_4_5_6__d8bde635f5");
|
||||
torrentInfo.InfoUrl.Should().Be("https://torrentapi.org/redirect_to_info.php?token=i5cx7b9agd&p=8_6_4_4_5_6__d8bde635f5&app_id=Radarr");
|
||||
torrentInfo.Indexer.Should().Be(Subject.Definition.Name);
|
||||
torrentInfo.PublishDate.Should().Be(DateTime.Parse("2015-06-05 16:58:11 +0000").ToUniversalTime());
|
||||
torrentInfo.Size.Should().Be(564198371);
|
||||
|
||||
@@ -1,13 +1,9 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using FluentAssertions;
|
||||
using NUnit.Framework;
|
||||
using NzbDrone.Core.Exceptions;
|
||||
using NzbDrone.Core.MediaCover;
|
||||
using NzbDrone.Core.MetadataSource;
|
||||
using NzbDrone.Core.MetadataSource.SkyHook;
|
||||
using NzbDrone.Core.Test.Framework;
|
||||
using NzbDrone.Core.Movies;
|
||||
using NzbDrone.Core.Test.Framework;
|
||||
using NzbDrone.Test.Common.Categories;
|
||||
|
||||
namespace NzbDrone.Core.Test.MetadataSource.SkyHook
|
||||
@@ -20,6 +16,8 @@ namespace NzbDrone.Core.Test.MetadataSource.SkyHook
|
||||
public void Setup()
|
||||
{
|
||||
UseRealHttp();
|
||||
|
||||
Mocker.SetConstant<ITmdbConfigService>(Mocker.Resolve<TmdbConfigService>());
|
||||
}
|
||||
|
||||
[TestCase(11, "Star Wars")]
|
||||
|
||||
@@ -18,7 +18,8 @@ namespace NzbDrone.Core.Test.MetadataSource.SkyHook
|
||||
}
|
||||
|
||||
[TestCase("Prometheus", "Prometheus")]
|
||||
[TestCase("The Man from U.N.C.L.E.", "The Man from U.N.C.L.E.")]
|
||||
// TODO: TMDB does not like when we clean '.'
|
||||
// [TestCase("The Man from U.N.C.L.E.", "The Man from U.N.C.L.E.")]
|
||||
[TestCase("imdb:tt2527336", "Star Wars: The Last Jedi")]
|
||||
[TestCase("imdb:tt2798920", "Annihilation")]
|
||||
public void successful_search(string title, string expected)
|
||||
|
||||
@@ -0,0 +1,32 @@
|
||||
using FizzWare.NBuilder;
|
||||
using FluentAssertions;
|
||||
using NUnit.Framework;
|
||||
using NzbDrone.Core.Movies.AlternativeTitles;
|
||||
using NzbDrone.Core.Test.Framework;
|
||||
|
||||
namespace NzbDrone.Core.Test.MovieTests.AlternativeTitleServiceTests
|
||||
{
|
||||
[TestFixture]
|
||||
public class AlternativeTitleFixture : CoreTest
|
||||
{
|
||||
private AlternativeTitle CreateFakeTitle(SourceType source, int votes)
|
||||
{
|
||||
return Builder<AlternativeTitle>.CreateNew().With(t => t.SourceType = source).With(t => t.Votes = votes)
|
||||
.Build();
|
||||
}
|
||||
|
||||
[TestCase(SourceType.TMDB, -1, true)]
|
||||
[TestCase(SourceType.TMDB, 1000, true)]
|
||||
[TestCase(SourceType.Mappings, 0, false)]
|
||||
[TestCase(SourceType.Mappings, 4, true)]
|
||||
[TestCase(SourceType.Mappings, -1, false)]
|
||||
[TestCase(SourceType.Indexer, 0, true)]
|
||||
[TestCase(SourceType.User, 0, true)]
|
||||
public void should_be_trusted(SourceType source, int votes, bool trusted)
|
||||
{
|
||||
var fakeTitle = CreateFakeTitle(source, votes);
|
||||
|
||||
fakeTitle.IsTrusted().Should().Be(trusted);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,104 @@
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using FizzWare.NBuilder;
|
||||
using FluentAssertions;
|
||||
using Moq;
|
||||
using NUnit.Framework;
|
||||
using NzbDrone.Common.Extensions;
|
||||
using NzbDrone.Core.Movies;
|
||||
using NzbDrone.Core.Movies.AlternativeTitles;
|
||||
using NzbDrone.Core.Test.Framework;
|
||||
|
||||
namespace NzbDrone.Core.Test.MovieTests.AlternativeTitleServiceTests
|
||||
{
|
||||
[TestFixture]
|
||||
public class AlternativeTitleServiceFixture : CoreTest<AlternativeTitleService>
|
||||
{
|
||||
private AlternativeTitle _title1;
|
||||
private AlternativeTitle _title2;
|
||||
private AlternativeTitle _title3;
|
||||
|
||||
private Movie _movie;
|
||||
|
||||
[SetUp]
|
||||
public void Setup()
|
||||
{
|
||||
var titles = Builder<AlternativeTitle>.CreateListOfSize(3).All().With(t => t.MovieId = 0).Build();
|
||||
_title1 = titles[0];
|
||||
_title2 = titles[1];
|
||||
_title3 = titles[2];
|
||||
_movie = Builder<Movie>.CreateNew().With(m => m.CleanTitle = "myothertitle").With(m => m.Id = 1).Build();
|
||||
}
|
||||
|
||||
private void GivenExistingTitles(params AlternativeTitle[] titles)
|
||||
{
|
||||
Mocker.GetMock<IAlternativeTitleRepository>().Setup(r => r.FindByMovieId(_movie.Id))
|
||||
.Returns(titles.ToList());
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void should_update_insert_remove_titles()
|
||||
{
|
||||
var titles = new List<AlternativeTitle> {_title2, _title3};
|
||||
var updates = new List<AlternativeTitle> {_title2};
|
||||
var deletes = new List<AlternativeTitle> {_title1};
|
||||
var inserts = new List<AlternativeTitle> {_title3};
|
||||
GivenExistingTitles(_title1, _title2);
|
||||
|
||||
Subject.UpdateTitles(titles, _movie);
|
||||
|
||||
Mocker.GetMock<IAlternativeTitleRepository>().Verify(r => r.InsertMany(inserts), Times.Once());
|
||||
Mocker.GetMock<IAlternativeTitleRepository>().Verify(r => r.UpdateMany(updates), Times.Once());
|
||||
Mocker.GetMock<IAlternativeTitleRepository>().Verify(r => r.DeleteMany(deletes), Times.Once());
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void should_not_insert_duplicates()
|
||||
{
|
||||
GivenExistingTitles();
|
||||
var titles = new List<AlternativeTitle> {_title1, _title1};
|
||||
var inserts = new List<AlternativeTitle>{ _title1 };
|
||||
|
||||
Subject.UpdateTitles(titles, _movie);
|
||||
|
||||
Mocker.GetMock<IAlternativeTitleRepository>().Verify(r => r.InsertMany(inserts), Times.Once());
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void should_not_insert_main_title()
|
||||
{
|
||||
GivenExistingTitles();
|
||||
var titles = new List<AlternativeTitle>{_title1};
|
||||
var movie = Builder<Movie>.CreateNew().With(m => m.CleanTitle = _title1.CleanTitle).Build();
|
||||
|
||||
Subject.UpdateTitles(titles, movie);
|
||||
|
||||
Mocker.GetMock<IAlternativeTitleRepository>().Verify(r => r.InsertMany(new List<AlternativeTitle>()), Times.Once());
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void should_update_movie_id()
|
||||
{
|
||||
GivenExistingTitles();
|
||||
var titles = new List<AlternativeTitle> {_title1, _title2};
|
||||
|
||||
Subject.UpdateTitles(titles, _movie);
|
||||
|
||||
_title1.MovieId.Should().Be(_movie.Id);
|
||||
_title2.MovieId.Should().Be(_movie.Id);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void should_update_with_correct_id()
|
||||
{
|
||||
var existingTitle = Builder<AlternativeTitle>.CreateNew().With(t => t.Id = 2).Build();
|
||||
GivenExistingTitles(existingTitle);
|
||||
var updateTitle = existingTitle.JsonClone();
|
||||
updateTitle.Id = 0;
|
||||
|
||||
Subject.UpdateTitles(new List<AlternativeTitle> {updateTitle}, _movie);
|
||||
|
||||
Mocker.GetMock<IAlternativeTitleRepository>().Verify(r => r.UpdateMany(It.Is<IList<AlternativeTitle>>(list => list.First().Id == existingTitle.Id)), Times.Once());
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -80,9 +80,8 @@
|
||||
<HintPath>..\packages\Unity.2.1.505.2\lib\NET35\Microsoft.Practices.Unity.Configuration.dll</HintPath>
|
||||
<Private>True</Private>
|
||||
</Reference>
|
||||
<Reference Include="Newtonsoft.Json, Version=6.0.0.0, Culture=neutral, PublicKeyToken=30ad4fe6b2a6aeed, processorArchitecture=MSIL">
|
||||
<SpecificVersion>False</SpecificVersion>
|
||||
<HintPath>..\packages\Newtonsoft.Json.6.0.6\lib\net40\Newtonsoft.Json.dll</HintPath>
|
||||
<Reference Include="Newtonsoft.Json, Version=9.0.0.0, Culture=neutral, PublicKeyToken=30ad4fe6b2a6aeed, processorArchitecture=MSIL">
|
||||
<HintPath>..\packages\Newtonsoft.Json.9.0.1\lib\net40\Newtonsoft.Json.dll</HintPath>
|
||||
</Reference>
|
||||
<Reference Include="NLog, Version=4.0.0.0, Culture=neutral, PublicKeyToken=5120e14c03d0593c, processorArchitecture=MSIL">
|
||||
<HintPath>..\packages\NLog.4.5.0-rc06\lib\net40-client\NLog.dll</HintPath>
|
||||
@@ -296,6 +295,8 @@
|
||||
<Compile Include="MetadataSource\SkyHook\SkyHookProxySearchFixture.cs" />
|
||||
<Compile Include="MetadataSource\SearchMovieComparerFixture.cs" />
|
||||
<Compile Include="MetadataSource\SkyHook\SkyHookProxyFixture.cs" />
|
||||
<Compile Include="MovieTests\AlternativeTitleServiceTests\AlternativeTitleFixture.cs" />
|
||||
<Compile Include="MovieTests\AlternativeTitleServiceTests\AlternativeTitleServiceFixture.cs" />
|
||||
<Compile Include="NetImport\CouchPotato\CouchPotatoParserFixture.cs" />
|
||||
<Compile Include="NetImport\RSSImportFixture.cs" />
|
||||
<Compile Include="NetImport\RSSImportParserFixture.cs" />
|
||||
|
||||
@@ -26,6 +26,8 @@ namespace NzbDrone.Core.Test.ParserTests
|
||||
[TestCase("Castle.2009.S01E14.Mandarin.HDTV.XviD-LOL", Language.Mandarin)]
|
||||
[TestCase("Castle.2009.S01E14.Korean.HDTV.XviD-LOL", Language.Korean)]
|
||||
[TestCase("Castle.2009.S01E14.Russian.HDTV.XviD-LOL", Language.Russian)]
|
||||
[TestCase("Castle.2009.S01E14.Ukrainian.HDTV.XviD-LOL", Language.Ukrainian)]
|
||||
[TestCase("Castle.2009.S01E14.Ukr.HDTV.XviD-LOL", Language.Ukrainian)]
|
||||
[TestCase("Castle.2009.S01E14.Polish.HDTV.XviD-LOL", Language.Polish)]
|
||||
[TestCase("Castle.2009.S01E14.Vietnamese.HDTV.XviD-LOL", Language.Vietnamese)]
|
||||
[TestCase("Castle.2009.S01E14.Swedish.HDTV.XviD-LOL", Language.Swedish)]
|
||||
|
||||
@@ -79,9 +79,9 @@ namespace NzbDrone.Core.Test.ParserTests.ParsingServiceTests.AugmentersTests
|
||||
[Test]
|
||||
public void should_add_size()
|
||||
{
|
||||
var history = HistoryWithData("Size", 1500.ToString());
|
||||
var history = HistoryWithData("Size", 9663676416.ToString());
|
||||
var movieInfo = Subject.AugmentMovieInfo(MovieInfo, history);
|
||||
movieInfo.ExtraInfo["Size"].ShouldBeEquivalentTo(1500);
|
||||
movieInfo.ExtraInfo["Size"].ShouldBeEquivalentTo(9663676416);
|
||||
}
|
||||
|
||||
[Test]
|
||||
|
||||
@@ -251,6 +251,7 @@ namespace NzbDrone.Core.Test.ParserTests
|
||||
|
||||
[TestCase("Contract.to.Kill.2016.REMUX.2160p.BluRay.AVC.DTS-HD.MA.5.1-iFT")]
|
||||
[TestCase("27.Dresses.2008.REMUX.2160p.Bluray.AVC.DTS-HR.MA.5.1-LEGi0N")]
|
||||
[TestCase("Los Vengadores (2012) [UHDRemux HDR HEVC 2160p][Dolby Atmos TrueHD 7 1 Eng DTS 5 1 Esp]")]
|
||||
public void should_parse_remux2160p_quality(string title)
|
||||
{
|
||||
ParseAndVerifyQuality(title, Source.BLURAY, false, Resolution.R2160P, Modifier.REMUX);
|
||||
|
||||
@@ -29,6 +29,16 @@ namespace NzbDrone.Core.Test.ParserTests
|
||||
[TestCase("The.Middle.720p.HEVC.x265-MeGusta-Pre", "MeGusta")]
|
||||
[TestCase("Haunted.Hayride.2018.720p.WEBRip.DDP5.1.x264-NTb-postbot", "NTb")]
|
||||
[TestCase("Haunted.Hayride.2018.720p.WEBRip.DDP5.1.x264-NTb-xpost", "NTb")]
|
||||
[TestCase("Men.in.Black.International.2019.BluRay.1080p.AVC.DTS-HD.MA5.1-CHDBits-RakuvArrow", "CHDBits")]
|
||||
[TestCase("Aladdin.2019.1080p.BluRay.x264-SPARKS-WhiteRev", "SPARKS")]
|
||||
[TestCase("Elvis.Presley.The.Searcher.2018.1080p.BluRay.x264-HANDJOB-BUYMORE", "HANDJOB")]
|
||||
[TestCase("Kill.Bill.Vol.2.2004.1080p.BluRay.DTS.x264-CyTSuNee-AsRequested", "CyTSuNee")]
|
||||
[TestCase("The.Good.Doctor.S02E17.Breakdown.1080p.AMZN.WEB-DL.DDP5.1.H.264-SiGMA-AlternativeToRequested", "SiGMA")]
|
||||
[TestCase("Mandy.2018.NORDiC.1080p.BluRay.x264-EGEN-GEROV", "EGEN")]
|
||||
[TestCase("TheEqualizer.2.2018.1080p.BluRay.DTS.X264-CMRG-Z0iDS3N", "CMRG")]
|
||||
[TestCase("Ghosthouse.1988.720p.BluRay.x264-SADPANDA-Chamele0n", "SADPANDA")]
|
||||
[TestCase("The.Walking.Dead.S08E08.1080p.BluRay.x264-ROVERS-4P", "ROVERS")]
|
||||
[TestCase("Stranger.Things.S01E02.720p.BluRay.X264-REWARD-4Planet", "REWARD")]
|
||||
//[TestCase("", "")]
|
||||
public void should_parse_release_group(string title, string expected)
|
||||
{
|
||||
|
||||
@@ -2,6 +2,7 @@ using System;
|
||||
using System.Linq;
|
||||
using FluentAssertions;
|
||||
using NUnit.Framework;
|
||||
using NzbDrone.Common.EnvironmentInfo;
|
||||
using NzbDrone.Common.Extensions;
|
||||
using NzbDrone.Core.Test.Framework;
|
||||
using NzbDrone.Core.Update;
|
||||
@@ -10,6 +11,12 @@ namespace NzbDrone.Core.Test.UpdateTests
|
||||
{
|
||||
public class UpdatePackageProviderFixture : CoreTest<UpdatePackageProvider>
|
||||
{
|
||||
[SetUp]
|
||||
public void Setup()
|
||||
{
|
||||
Mocker.GetMock<IPlatformInfo>().SetupGet(c => c.Version).Returns(new Version("9.9.9"));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void no_update_when_version_higher()
|
||||
{
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user