Fixed: Remove obsolete XBMC HTTP notification API

pull/1689/head
ta264 5 years ago committed by Qstick
parent aa66358725
commit c0d77af26d

@ -8,10 +8,10 @@ using NzbDrone.Core.Notifications.Xbmc.Model;
using NzbDrone.Core.Test.Framework;
using NzbDrone.Core.Music;
namespace NzbDrone.Core.Test.NotificationTests.Xbmc.Json
namespace NzbDrone.Core.Test.NotificationTests.Xbmc
{
[TestFixture]
public class GetArtistPathFixture : CoreTest<JsonApiProvider>
public class GetArtistPathFixture : CoreTest<XbmcService>
{
private const string MB_ID = "9f4e41c3-2648-428e-b8c7-dc10465b49ac";
private XbmcSettings _settings;

@ -1,70 +0,0 @@
using System.Linq;
using FluentAssertions;
using NUnit.Framework;
using NzbDrone.Common.Http;
using NzbDrone.Core.Notifications.Xbmc;
using NzbDrone.Core.Test.Framework;
namespace NzbDrone.Core.Test.NotificationTests.Xbmc.Http
{
[TestFixture]
public class ActivePlayersFixture : CoreTest<HttpApiProvider>
{
private XbmcSettings _settings;
private string _expectedUrl;
private void WithNoActivePlayers()
{
Mocker.GetMock<IHttpProvider>()
.Setup(s => s.DownloadString(_expectedUrl, _settings.Username, _settings.Password))
.Returns("<html><li>Filename:[Nothing Playing]</html>");
}
private void WithVideoPlayerActive()
{
var activePlayers = @"<html><li>Filename:C:\Test\TV\2 Broke Girls\Season 01\2 Broke Girls - S01E01 - Pilot [SDTV].avi" +
"<li>PlayStatus:Playing<li>VideoNo:0<li>Type:Audio<li>Thumb:special://masterprofile/Thumbnails/Video/a/auto-a664d5a2.tbn" +
"<li>Time:00:06<li>Duration:21:35<li>Percentage:0<li>File size:183182590<li>Changed:True</html>";
Mocker.GetMock<IHttpProvider>()
.Setup(s => s.DownloadString(_expectedUrl, _settings.Username, _settings.Password))
.Returns(activePlayers);
}
[SetUp]
public void Setup()
{
_settings = new XbmcSettings
{
Host = "localhost",
Port = 8080,
Username = "xbmc",
Password = "xbmc",
AlwaysUpdate = false,
CleanLibrary = false,
UpdateLibrary = true
};
_expectedUrl = string.Format("http://{0}/xbmcCmds/xbmcHttp?command={1}", _settings.Address, "getcurrentlyplaying");
}
[Test]
public void _should_be_empty_when_no_active_players()
{
WithNoActivePlayers();
Subject.GetActivePlayers(_settings).Should().BeEmpty();
}
[Test]
public void should_have_active_audio_player()
{
WithVideoPlayerActive();
var result = Subject.GetActivePlayers(_settings);
result.Should().HaveCount(1);
result.First().Type.Should().Be("audio");
}
}
}

@ -1,35 +0,0 @@
using FluentAssertions;
using NUnit.Framework;
using NzbDrone.Core.Notifications.Xbmc;
using NzbDrone.Core.Test.Framework;
namespace NzbDrone.Core.Test.NotificationTests.Xbmc.Http
{
[TestFixture]
public class CheckForErrorFixture : CoreTest<HttpApiProvider>
{
[Test]
public void should_be_true_when_the_response_contains_an_error()
{
const string response = "html><li>Error:Unknown command</html>";
Subject.CheckForError(response).Should().BeTrue();
}
[Test]
public void JsonError_true_empty_response()
{
var response = string.Empty;
Subject.CheckForError(response).Should().BeTrue();
}
[Test]
public void JsonError_false()
{
const string response = "html><li>Filename:[Nothing Playing]</html>";
Subject.CheckForError(response).Should().BeFalse();
}
}
}

@ -1,94 +0,0 @@
using FluentAssertions;
using NUnit.Framework;
using NzbDrone.Common.Http;
using NzbDrone.Core.Notifications.Xbmc;
using NzbDrone.Core.Test.Framework;
using NzbDrone.Core.Music;
namespace NzbDrone.Core.Test.NotificationTests.Xbmc.Http
{
[TestFixture]
public class GetArtistPathFixture : CoreTest<HttpApiProvider>
{
private XbmcSettings _settings;
private Artist _artist;
[SetUp]
public void Setup()
{
_settings = new XbmcSettings
{
Host = "localhost",
Port = 8080,
Username = "xbmc",
Password = "xbmc",
AlwaysUpdate = false,
CleanLibrary = false,
UpdateLibrary = true
};
_artist = new Artist
{
ForeignArtistId = "9f4e41c3-2648-428e-b8c7-dc10465b49ac",
Name = "Shawn Desman"
};
const string setResponseUrl = "http://localhost:8080/xbmcCmds/xbmcHttp?command=SetResponseFormat(webheader;false;webfooter;false;header;<xml>;footer;</xml>;opentag;<tag>;closetag;</tag>;closefinaltag;false)";
const string resetResponseUrl = "http://localhost:8080/xbmcCmds/xbmcHttp?command=SetResponseFormat()";
Mocker.GetMock<IHttpProvider>()
.Setup(s => s.DownloadString(setResponseUrl, _settings.Username, _settings.Password))
.Returns("<xml><tag>OK</xml>");
Mocker.GetMock<IHttpProvider>()
.Setup(s => s.DownloadString(resetResponseUrl, _settings.Username, _settings.Password))
.Returns(@"<html>
<li>OK
</html>");
}
[Test]
public void should_get_artist_path()
{
const string queryResult = @"<xml><record><field>smb://xbmc:xbmc@HOMESERVER/Music/Shawn Desman/</field></record></xml>";
var query = string.Format("http://localhost:8080/xbmcCmds/xbmcHttp?command=QueryMusicDatabase(select path.strPath from path, artist, artistlinkpath where artist.c12 = 9f4e41c3-2648-428e-b8c7-dc10465b49ac and artistlinkpath.idArtist = artist.idArtist and artistlinkpath.idPath = path.idPath)");
Mocker.GetMock<IHttpProvider>()
.Setup(s => s.DownloadString(query, _settings.Username, _settings.Password))
.Returns(queryResult);
Subject.GetArtistPath(_settings, _artist)
.Should().Be("smb://xbmc:xbmc@HOMESERVER/Music/Shawn Desman/");
}
[Test]
public void should_get_null_for_artist_path()
{
const string queryResult = @"<xml></xml>";
var query = string.Format("http://localhost:8080/xbmcCmds/xbmcHttp?command=QueryMusicDatabase(select path.strPath from path, artist, artistlinkpath where artist.c12 = 9f4e41c3-2648-428e-b8c7-dc10465b49ac and artistlinkpath.idArtist = artist.idArtist and artistlinkpath.idPath = path.idPath)");
Mocker.GetMock<IHttpProvider>()
.Setup(s => s.DownloadString(query, _settings.Username, _settings.Password))
.Returns(queryResult);
Subject.GetArtistPath(_settings, _artist)
.Should().BeNull();
}
[Test]
public void should_get_artist_path_with_special_characters_in_it()
{
const string queryResult = @"<xml><record><field>smb://xbmc:xbmc@HOMESERVER/Music/-wumpscut-/</field></record></xml>";
var query = string.Format("http://localhost:8080/xbmcCmds/xbmcHttp?command=QueryMusicDatabase(select path.strPath from path, artist, artistlinkpath where artist.c12 = 9f4e41c3-2648-428e-b8c7-dc10465b49ac and artistlinkpath.idArtist = artist.idArtist and artistlinkpath.idPath = path.idPath)");
Mocker.GetMock<IHttpProvider>()
.Setup(s => s.DownloadString(query, _settings.Username, _settings.Password))
.Returns(queryResult);
Subject.GetArtistPath(_settings, _artist)
.Should().Be("smb://xbmc:xbmc@HOMESERVER/Music/-wumpscut-/");
}
}
}

@ -1,75 +0,0 @@
using FizzWare.NBuilder;
using NUnit.Framework;
using NzbDrone.Common.Http;
using NzbDrone.Core.Notifications.Xbmc;
using NzbDrone.Core.Test.Framework;
using NzbDrone.Core.Music;
namespace NzbDrone.Core.Test.NotificationTests.Xbmc.Http
{
[TestFixture]
public class UpdateFixture : CoreTest<HttpApiProvider>
{
private XbmcSettings _settings;
private string _artistQueryUrl = "http://localhost:8080/xbmcCmds/xbmcHttp?command=QueryMusicDatabase(select path.strPath from path, artist, artistlinkpath where artist.c12 = 9f4e41c3-2648-428e-b8c7-dc10465b49ac and artistlinkpath.idArtist = artist.idArtist and artistlinkpath.idPath = path.idPath)";
private Artist _fakeArtist;
[SetUp]
public void Setup()
{
_settings = new XbmcSettings
{
Host = "localhost",
Port = 8080,
Username = "xbmc",
Password = "xbmc",
AlwaysUpdate = false,
CleanLibrary = false,
UpdateLibrary = true
};
_fakeArtist = Builder<Artist>.CreateNew()
.With(s => s.ForeignArtistId = "9f4e41c3-2648-428e-b8c7-dc10465b49ac")
.With(s => s.Name = "Shawn Desman")
.Build();
}
private void WithArtistPath()
{
Mocker.GetMock<IHttpProvider>()
.Setup(s => s.DownloadString(_artistQueryUrl, _settings.Username, _settings.Password))
.Returns("<xml><record><field>smb://xbmc:xbmc@HOMESERVER/Music/Shawn Desman/</field></record></xml>");
}
private void WithoutArtistPath()
{
Mocker.GetMock<IHttpProvider>()
.Setup(s => s.DownloadString(_artistQueryUrl, _settings.Username, _settings.Password))
.Returns("<xml></xml>");
}
[Test]
public void should_update_using_artist_path()
{
WithArtistPath();
const string url = "http://localhost:8080/xbmcCmds/xbmcHttp?command=ExecBuiltIn(UpdateLibrary(music,smb://xbmc:xbmc@HOMESERVER/Music/Shawn Desman/))";
Mocker.GetMock<IHttpProvider>().Setup(s => s.DownloadString(url, _settings.Username, _settings.Password));
Subject.Update(_settings, _fakeArtist);
Mocker.VerifyAllMocks();
}
[Test]
public void should_update_all_paths_when_artist_path_not_found()
{
WithoutArtistPath();
const string url = "http://localhost:8080/xbmcCmds/xbmcHttp?command=ExecBuiltIn(UpdateLibrary(music))";
Mocker.GetMock<IHttpProvider>().Setup(s => s.DownloadString(url, _settings.Username, _settings.Password));
Subject.Update(_settings, _fakeArtist);
Mocker.VerifyAllMocks();
}
}
}

@ -8,10 +8,10 @@ using NzbDrone.Core.Notifications.Xbmc.Model;
using NzbDrone.Core.Test.Framework;
using NzbDrone.Core.Music;
namespace NzbDrone.Core.Test.NotificationTests.Xbmc.Json
namespace NzbDrone.Core.Test.NotificationTests.Xbmc
{
[TestFixture]
public class UpdateFixture : CoreTest<JsonApiProvider>
public class UpdateFixture : CoreTest<XbmcService>
{
private const string MB_ID = "9f4e41c3-2648-428e-b8c7-dc10465b49ac";
private XbmcSettings _settings;

@ -1,89 +0,0 @@
using FluentAssertions;
using NUnit.Framework;
using NzbDrone.Core.Notifications.Xbmc.Model;
namespace NzbDrone.Core.Test
{
public class XbmcVersionTests
{
[TestCase(6, 0, 0)]
[TestCase(5, 1, 0)]
[TestCase(5, 0, 1)]
public void Icomparer_greater_test(int major, int minor, int patch)
{
var first = new XbmcVersion(5, 0, 0);
var second = new XbmcVersion(major, minor, patch);
second.Should().BeGreaterThan(first);
}
[TestCase(4, 5, 5)]
[TestCase(5, 4, 5)]
[TestCase(5, 5, 4)]
public void Icomparer_lesser_test(int major, int minor, int patch)
{
var first = new XbmcVersion(5, 5, 5);
var second = new XbmcVersion(major, minor, patch);
second.Should().BeLessThan(first);
}
[Test]
public void equal_operand()
{
var first = new XbmcVersion(5, 0, 0);
var second = new XbmcVersion(5, 0, 0);
(first == second).Should().BeTrue();
(first >= second).Should().BeTrue();
(first <= second).Should().BeTrue();
}
[Test]
public void equal_operand_false()
{
var first = new XbmcVersion(5, 0, 0);
var second = new XbmcVersion(6, 0, 0);
(first == second).Should().BeFalse();
}
[Test]
public void not_equal_operand_false()
{
var first = new XbmcVersion(5, 0, 0);
var second = new XbmcVersion(5, 0, 0);
(first != second).Should().BeFalse();
}
[Test]
public void not_equal_operand_true()
{
var first = new XbmcVersion(5, 0, 0);
var second = new XbmcVersion(6, 0, 0);
(first != second).Should().BeTrue();
}
[Test]
public void greater_operand()
{
var first = new XbmcVersion(5, 0, 0);
var second = new XbmcVersion(6, 0, 0);
(first < second).Should().BeTrue();
(first <= second).Should().BeTrue();
}
[Test]
public void lesser_operand()
{
var first = new XbmcVersion(5, 0, 0);
var second = new XbmcVersion(6, 0, 0);
(second > first).Should().BeTrue();
(second >= first).Should().BeTrue();
}
}
}

@ -1,187 +0,0 @@
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Xml.Linq;
using NLog;
using NzbDrone.Common.Http;
using NzbDrone.Core.Notifications.Xbmc.Model;
using NzbDrone.Core.Music;
namespace NzbDrone.Core.Notifications.Xbmc
{
public class HttpApiProvider : IApiProvider
{
private readonly IHttpProvider _httpProvider;
private readonly Logger _logger;
public HttpApiProvider(IHttpProvider httpProvider, Logger logger)
{
_httpProvider = httpProvider;
_logger = logger;
}
public bool CanHandle(XbmcVersion version)
{
return version < new XbmcVersion(5);
}
public void Notify(XbmcSettings settings, string title, string message)
{
var notification = string.Format("Notification({0},{1},{2},{3})", title, message, settings.DisplayTime * 1000, "https://raw.github.com/Lidarr/Lidarr/develop/Logo/64.png");
var command = BuildExecBuiltInCommand(notification);
SendCommand(settings, command);
}
public void Update(XbmcSettings settings, Artist artist)
{
if (!settings.AlwaysUpdate)
{
_logger.Debug("Determining if there are any active players on XBMC host: {0}", settings.Address);
var activePlayers = GetActivePlayers(settings);
if (activePlayers.Any(a => a.Type.Equals("audio")))
{
_logger.Debug("Audio is currently playing, skipping library update");
return;
}
}
UpdateLibrary(settings, artist);
}
public void Clean(XbmcSettings settings)
{
const string cleanMusicLibrary = "CleanLibrary(music)";
var command = BuildExecBuiltInCommand(cleanMusicLibrary);
SendCommand(settings, command);
}
internal List<ActivePlayer> GetActivePlayers(XbmcSettings settings)
{
try
{
var result = new List<ActivePlayer>();
var response = SendCommand(settings, "getcurrentlyplaying");
if (response.Contains("<li>Filename:[Nothing Playing]")) return new List<ActivePlayer>();
if (response.Contains("<li>Type:Audio")) result.Add(new ActivePlayer(1, "audio"));
return result;
}
catch (Exception ex)
{
_logger.Debug(ex, ex.Message);
}
return new List<ActivePlayer>();
}
internal string GetArtistPath(XbmcSettings settings, Artist artist)
{
var query =
string.Format(
"select path.strPath from path, artist, artistlinkpath where artist.c12 = {0} and artistlinkpath.idArtist = artist.idArtist and artistlinkpath.idPath = path.idPath",
artist.Metadata.Value.ForeignArtistId);
var command = string.Format("QueryMusicDatabase({0})", query);
const string setResponseCommand =
"SetResponseFormat(webheader;false;webfooter;false;header;<xml>;footer;</xml>;opentag;<tag>;closetag;</tag>;closefinaltag;false)";
const string resetResponseCommand = "SetResponseFormat()";
SendCommand(settings, setResponseCommand);
var response = SendCommand(settings, command);
SendCommand(settings, resetResponseCommand);
if (string.IsNullOrEmpty(response))
return string.Empty;
var xDoc = XDocument.Load(new StringReader(response.Replace("&", "&amp;")));
var xml = xDoc.Descendants("xml").Select(x => x).FirstOrDefault();
if (xml == null)
return null;
var field = xml.Descendants("field").FirstOrDefault();
if (field == null)
return null;
return field.Value;
}
internal bool CheckForError(string response)
{
_logger.Debug("Looking for error in response: {0}", response);
if (string.IsNullOrWhiteSpace(response))
{
_logger.Debug("Invalid response from XBMC, the response is not valid JSON");
return true;
}
var errorIndex = response.IndexOf("Error", StringComparison.InvariantCultureIgnoreCase);
if (errorIndex > -1)
{
var errorMessage = response.Substring(errorIndex + 6);
errorMessage = errorMessage.Substring(0, errorMessage.IndexOfAny(new char[] { '<', ';' }));
_logger.Debug("Error found in response: {0}", errorMessage);
return true;
}
return false;
}
private void UpdateLibrary(XbmcSettings settings, Artist artist)
{
try
{
_logger.Debug("Sending Update DB Request to XBMC Host: {0}", settings.Address);
var xbmcArtistPath = GetArtistPath(settings, artist);
//If the path is found update it, else update the whole library
if (!string.IsNullOrEmpty(xbmcArtistPath))
{
_logger.Debug("Updating artist [{0}] on XBMC host: {1}", artist, settings.Address);
var command = BuildExecBuiltInCommand(string.Format("UpdateLibrary(music,{0})", xbmcArtistPath));
SendCommand(settings, command);
}
else
{
//Update the entire library
_logger.Debug("Artist [{0}] doesn't exist on XBMC host: {1}, Updating Entire Library", artist, settings.Address);
var command = BuildExecBuiltInCommand("UpdateLibrary(music)");
SendCommand(settings, command);
}
}
catch (Exception ex)
{
_logger.Debug(ex, ex.Message);
}
}
private string SendCommand(XbmcSettings settings, string command)
{
var url = string.Format("http://{0}/xbmcCmds/xbmcHttp?command={1}", settings.Address, command);
if (!string.IsNullOrEmpty(settings.Username))
{
return _httpProvider.DownloadString(url, settings.Username, settings.Password);
}
return _httpProvider.DownloadString(url);
}
private string BuildExecBuiltInCommand(string command)
{
return string.Format("ExecBuiltIn({0})", command);
}
}
}

@ -1,13 +0,0 @@
using NzbDrone.Core.Notifications.Xbmc.Model;
using NzbDrone.Core.Music;
namespace NzbDrone.Core.Notifications.Xbmc
{
public interface IApiProvider
{
void Notify(XbmcSettings settings, string title, string message);
void Update(XbmcSettings settings, Artist artist);
void Clean(XbmcSettings settings);
bool CanHandle(XbmcVersion version);
}
}

@ -1,15 +0,0 @@
using System;
namespace NzbDrone.Core.Notifications.Xbmc
{
public class InvalidXbmcVersionException : Exception
{
public InvalidXbmcVersionException()
{
}
public InvalidXbmcVersionException(string message) : base(message)
{
}
}
}

@ -1,109 +0,0 @@
using System;
using System.Collections.Generic;
using System.Linq;
using NLog;
using NzbDrone.Core.Notifications.Xbmc.Model;
using NzbDrone.Core.Music;
namespace NzbDrone.Core.Notifications.Xbmc
{
public class JsonApiProvider : IApiProvider
{
private readonly IXbmcJsonApiProxy _proxy;
private readonly Logger _logger;
public JsonApiProvider(IXbmcJsonApiProxy proxy, Logger logger)
{
_proxy = proxy;
_logger = logger;
}
public bool CanHandle(XbmcVersion version)
{
return version >= new XbmcVersion(5);
}
public void Notify(XbmcSettings settings, string title, string message)
{
_proxy.Notify(settings, title, message);
}
public void Update(XbmcSettings settings, Artist artist)
{
if (!settings.AlwaysUpdate)
{
_logger.Debug("Determining if there are any active players on XBMC host: {0}", settings.Address);
var activePlayers = _proxy.GetActivePlayers(settings);
if (activePlayers.Any(a => a.Type.Equals("audio")))
{
_logger.Debug("Audio is currently playing, skipping library update");
return;
}
}
UpdateLibrary(settings, artist);
}
public void Clean(XbmcSettings settings)
{
_proxy.CleanLibrary(settings);
}
public List<ActivePlayer> GetActivePlayers(XbmcSettings settings)
{
return _proxy.GetActivePlayers(settings);
}
public string GetArtistPath(XbmcSettings settings, Artist artist)
{
var allArtists = _proxy.GetArtist(settings);
if (!allArtists.Any())
{
_logger.Debug("No Artists returned from XBMC");
return null;
}
var matchingArtist = allArtists.FirstOrDefault(s =>
{
var musicBrainzId = s.MusicbrainzArtistId.FirstOrDefault();
return musicBrainzId == artist.Metadata.Value.ForeignArtistId || s.Label == artist.Name;
});
return matchingArtist?.File;
}
private void UpdateLibrary(XbmcSettings settings, Artist artist)
{
try
{
var artistPath = GetArtistPath(settings, artist);
if (artistPath != null)
{
_logger.Debug("Updating artist {0} (Path: {1}) on XBMC host: {2}", artist, artistPath, settings.Address);
}
else
{
_logger.Debug("Artist {0} doesn't exist on XBMC host: {1}, Updating Entire Library", artist,
settings.Address);
}
var response = _proxy.UpdateLibrary(settings, artistPath);
if (!response.Equals("OK", StringComparison.InvariantCultureIgnoreCase))
{
_logger.Debug("Failed to update library for: {0}", settings.Address);
}
}
catch (Exception ex)
{
_logger.Debug(ex, ex.Message);
}
}
}
}

@ -1,11 +0,0 @@
using System.Collections.Generic;
namespace NzbDrone.Core.Notifications.Xbmc.Model
{
public class ActivePlayersDharmaResult
{
public string Id { get; set; }
public string JsonRpc { get; set; }
public Dictionary<string, bool> Result { get; set; }
}
}

@ -2,7 +2,7 @@
namespace NzbDrone.Core.Notifications.Xbmc.Model
{
public class ActivePlayersEdenResult
public class ActivePlayersResult
{
public string Id { get; set; }
public string JsonRpc { get; set; }

@ -1,11 +0,0 @@
using System.Collections.Generic;
namespace NzbDrone.Core.Notifications.Xbmc.Model
{
public class VersionResult
{
public string Id { get; set; }
public string JsonRpc { get; set; }
public Dictionary<string, int> Result { get; set; }
}
}

@ -1,125 +0,0 @@
using System;
namespace NzbDrone.Core.Notifications.Xbmc.Model
{
public class XbmcVersion : IComparable<XbmcVersion>
{
public XbmcVersion()
{
}
public XbmcVersion(int major)
{
Major = major;
}
public XbmcVersion(int major, int minor, int patch)
{
Major = major;
Minor = minor;
Patch = patch;
}
public int Major { get; set; }
public int Minor { get; set; }
public int Patch { get; set; }
public int CompareTo(XbmcVersion other)
{
if(other.Major > Major)
return -1;
if(other.Major < Major)
return 1;
if (other.Minor > Minor)
return -1;
if (other.Minor < Minor)
return 1;
if (other.Patch > Patch)
return -1;
if (other.Patch < Patch)
return 1;
return 0;
}
public static bool operator !=(XbmcVersion x, XbmcVersion y)
{
return !(x == y);
}
public static bool operator ==(XbmcVersion x, XbmcVersion y)
{
var xObj = (object)x;
var yObj = (object)y;
if (xObj == null || yObj == null)
{
return xObj == yObj;
}
return x.CompareTo(y) == 0;
}
public static bool operator >(XbmcVersion x, XbmcVersion y)
{
return x.CompareTo(y) > 0;
}
public static bool operator <(XbmcVersion x, XbmcVersion y)
{
return x.CompareTo(y) < 0;
}
public static bool operator <=(XbmcVersion x, XbmcVersion y)
{
return x.CompareTo(y) <= 0;
}
public static bool operator >=(XbmcVersion x, XbmcVersion y)
{
return x.CompareTo(y) >= 0;
}
public override string ToString()
{
return string.Format("{0}.{1}.{2}", Major, Minor, Patch);
}
public override int GetHashCode()
{
unchecked // Overflow is fine, just wrap
{
int hash = 17;
hash = hash * 23 + Major.GetHashCode();
hash = hash * 23 + Minor.GetHashCode();
hash = hash * 23 + Patch.GetHashCode();
return hash;
}
}
public bool Equals(XbmcVersion other)
{
if (ReferenceEquals(null, other)) return false;
if (ReferenceEquals(this, other)) return true;
return (Equals(other.Major, Major) && Equals(other.Minor, Minor) && Equals(other.Patch, Patch));
}
public override bool Equals(object obj)
{
if (ReferenceEquals(null, obj)) return false;
if (ReferenceEquals(this, obj)) return true;
if (obj.GetType() != typeof(XbmcVersion)) return false;
return Equals((XbmcVersion)obj);
}
public static XbmcVersion NONE = new XbmcVersion(0, 0, 0);
public static XbmcVersion DHARMA = new XbmcVersion(2, 0, 0);
public static XbmcVersion EDEN = new XbmcVersion(4, 0, 0);
public static XbmcVersion FRODO = new XbmcVersion(6, 0, 0);
}
}

@ -76,7 +76,7 @@ namespace NzbDrone.Core.Notifications.Xbmc
var response = ProcessRequest(request, settings, "Player.GetActivePlayers");
return Json.Deserialize<ActivePlayersEdenResult>(response).Result;
return Json.Deserialize<ActivePlayersResult>(response).Result;
}
public List<KodiArtist> GetArtist(XbmcSettings settings)

@ -1,12 +1,7 @@
using System;
using System.Collections.Generic;
using System.Linq;
using FluentValidation.Results;
using Newtonsoft.Json.Linq;
using NLog;
using NzbDrone.Common.Cache;
using NzbDrone.Common.Serializer;
using NzbDrone.Core.Notifications.Xbmc.Model;
using NzbDrone.Core.Music;
namespace NzbDrone.Core.Notifications.Xbmc
@ -22,95 +17,97 @@ namespace NzbDrone.Core.Notifications.Xbmc
public class XbmcService : IXbmcService
{
private readonly IXbmcJsonApiProxy _proxy;
private readonly IEnumerable<IApiProvider> _apiProviders;
private readonly Logger _logger;
private readonly ICached<XbmcVersion> _xbmcVersionCache;
public XbmcService(IXbmcJsonApiProxy proxy,
IEnumerable<IApiProvider> apiProviders,
ICacheManager cacheManager,
Logger logger)
{
_proxy = proxy;
_apiProviders = apiProviders;
_logger = logger;
_xbmcVersionCache = cacheManager.GetCache<XbmcVersion>(GetType());
}
public void Notify(XbmcSettings settings, string title, string message)
{
var provider = GetApiProvider(settings);
provider.Notify(settings, title, message);
_proxy.Notify(settings, title, message);
}
public void Update(XbmcSettings settings, Artist artist)
{
var provider = GetApiProvider(settings);
provider.Update(settings, artist);
if (!settings.AlwaysUpdate)
{
_logger.Debug("Determining if there are any active players on XBMC host: {0}", settings.Address);
var activePlayers = _proxy.GetActivePlayers(settings);
if (activePlayers.Any(a => a.Type.Equals("audio")))
{
_logger.Debug("Audio is currently playing, skipping library update");
return;
}
}
UpdateLibrary(settings, artist);
}
public void Clean(XbmcSettings settings)
{
var provider = GetApiProvider(settings);
provider.Clean(settings);
_proxy.CleanLibrary(settings);
}
private XbmcVersion GetJsonVersion(XbmcSettings settings)
public string GetArtistPath(XbmcSettings settings, Artist artist)
{
return _xbmcVersionCache.Get(settings.Address, () =>
var allArtists = _proxy.GetArtist(settings);
if (!allArtists.Any())
{
var response = _proxy.GetJsonVersion(settings);
_logger.Debug("No Artists returned from XBMC");
return null;
}
_logger.Debug("Getting version from response: " + response);
var result = Json.Deserialize<XbmcJsonResult<JObject>>(response);
var matchingArtist = allArtists.FirstOrDefault(s =>
{
var musicBrainzId = s.MusicbrainzArtistId.FirstOrDefault();
var versionObject = result.Result.Property("version");
return musicBrainzId == artist.Metadata.Value.ForeignArtistId || s.Label == artist.Name;
});
if (versionObject.Value.Type == JTokenType.Integer)
return matchingArtist?.File;
}
private void UpdateLibrary(XbmcSettings settings, Artist artist)
{
try
{
var artistPath = GetArtistPath(settings, artist);
if (artistPath != null)
{
return new XbmcVersion((int)versionObject.Value);
_logger.Debug("Updating artist {0} (Path: {1}) on XBMC host: {2}", artist, artistPath, settings.Address);
}
if (versionObject.Value.Type == JTokenType.Object)
else
{
return Json.Deserialize<XbmcVersion>(versionObject.Value.ToString());
_logger.Debug("Artist {0} doesn't exist on XBMC host: {1}, Updating Entire Library", artist,
settings.Address);
}
throw new InvalidCastException("Unknown Version structure!: " + versionObject);
}, TimeSpan.FromHours(12));
}
var response = _proxy.UpdateLibrary(settings, artistPath);
private IApiProvider GetApiProvider(XbmcSettings settings)
{
var version = GetJsonVersion(settings);
var apiProvider = _apiProviders.SingleOrDefault(a => a.CanHandle(version));
if (!response.Equals("OK", StringComparison.InvariantCultureIgnoreCase))
{
_logger.Debug("Failed to update library for: {0}", settings.Address);
}
}
if (apiProvider == null)
catch (Exception ex)
{
var message = string.Format("Invalid API Version: {0} for {1}", version, settings.Address);
throw new InvalidXbmcVersionException(message);
_logger.Debug(ex, ex.Message);
}
return apiProvider;
}
public ValidationFailure Test(XbmcSettings settings, string message)
{
_xbmcVersionCache.Clear();
try
{
_logger.Debug("Determining version of Host: {0}", settings.Address);
var version = GetJsonVersion(settings);
_logger.Debug("Version is: {0}", version);
if (version == new XbmcVersion(0))
{
throw new InvalidXbmcVersionException("Version received from XBMC is invalid, please correct your settings.");
}
Notify(settings, "Test Notification", message);
}
catch (Exception ex)

Loading…
Cancel
Save