Fixed several issues in GrowlService:

1) Calls to the growl SDK were not made in a thread safe manner

2) Loading the icon from a URL did not work in mono, and it made
   the GrowlService calls take exceptionally long

3) The result of the growl SDK calls was not checked

4) A bug in the growl for windows SDK caused the mono version
   on unix platforms to not work. A fixed version of the SDK is
   now included in the build (do not use the NuGet version, it's
   broken on unix). The bug was reported to growl for windows here:
   https://code.google.com/p/growl-for-windows/issues/detail?id=48

use var for locals

made requested changes from code review

Gave state class a better name
pull/4/head
Frank Riley 10 years ago
parent 75236118dd
commit e752e7f35d

Binary file not shown.

@ -2,11 +2,16 @@
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Drawing;
using System.Drawing.Imaging;
using FluentValidation.Results;
using Growl.CoreLibrary;
using Growl.Connector;
using NLog;
using NzbDrone.Common.Instrumentation;
using GrowlNotification = Growl.Connector.Notification;
using System.Reflection;
using System.IO;
namespace NzbDrone.Core.Notifications.Growl
{
@ -21,42 +26,121 @@ namespace NzbDrone.Core.Notifications.Growl
private readonly Logger _logger;
private readonly Application _growlApplication = new Application("NzbDrone");
private GrowlConnector _growlConnector;
private readonly List<NotificationType> _notificationTypes;
private readonly NotificationType[] _notificationTypes;
private class GrowlRequestState
{
private AutoResetEvent _autoEvent = new AutoResetEvent(false);
private bool _isError = false;
private int _code;
private string _description;
public void Wait(int timeoutMs)
{
try
{
if (!_autoEvent.WaitOne(timeoutMs))
{
throw new GrowlException(ErrorCode.TIMED_OUT, ErrorDescription.TIMED_OUT, null);
}
if (_isError)
{
throw new GrowlException(_code, _description, null);
}
}
finally
{
_autoEvent.Reset();
_isError = false;
_code = 0;
_description = null;
}
}
public void Update()
{
_autoEvent.Set();
}
public void Update(int code, string description)
{
_code = code;
_description = description;
_isError = true;
_autoEvent.Set();
}
}
public GrowlService(Logger logger)
{
_logger = logger;
_notificationTypes = GetNotificationTypes();
_growlApplication.Icon = "https://raw.github.com/NzbDrone/NzbDrone/master/Logo/64.png";
var icon = Properties.Resources.Icon64;
var stream = new MemoryStream();
icon.Save(stream, ImageFormat.Bmp);
_growlApplication.Icon = new BinaryData(stream.ToArray());
}
private GrowlConnector GetGrowlConnector(string hostname, int port, string password)
{
var growlConnector = new GrowlConnector(password, hostname, port);
growlConnector.OKResponse += GrowlOKResponse;
growlConnector.ErrorResponse += GrowlErrorResponse;
return growlConnector;
}
public void SendNotification(string title, string message, string notificationTypeName, string hostname, int port, string password)
{
_logger.Debug("Sending Notification to: {0}:{1}", hostname, port);
var notificationType = _notificationTypes.Single(n => n.Name == notificationTypeName);
var notification = new GrowlNotification("NzbDrone", notificationType.Name, DateTime.Now.Ticks.ToString(), title, message);
var notification = new GrowlNotification(_growlApplication.Name, notificationType.Name, DateTime.Now.Ticks.ToString(), title, message);
_growlConnector = new GrowlConnector(password, hostname, port);
var growlConnector = GetGrowlConnector(hostname, port, password);
_logger.Debug("Sending Notification to: {0}:{1}", hostname, port);
_growlConnector.Notify(notification);
var requestState = new GrowlRequestState();
growlConnector.Notify(notification, requestState);
requestState.Wait(5000);
}
private void Register(string host, int port, string password)
{
_logger.Debug("Registering NzbDrone with Growl host: {0}:{1}", host, port);
_growlConnector = new GrowlConnector(password, host, port);
_growlConnector.Register(_growlApplication, _notificationTypes.ToArray());
var growlConnector = GetGrowlConnector(host, port, password);
var requestState = new GrowlRequestState();
growlConnector.Register(_growlApplication, _notificationTypes, requestState);
requestState.Wait(5000);
}
private void GrowlErrorResponse(Response response, object state)
{
var requestState = state as GrowlRequestState;
if (requestState != null)
{
requestState.Update(response.ErrorCode, response.ErrorDescription);
}
}
private void GrowlOKResponse(Response response, object state)
{
var requestState = state as GrowlRequestState;
if (requestState != null)
{
requestState.Update();
}
}
private List<NotificationType> GetNotificationTypes()
private NotificationType[] GetNotificationTypes()
{
var notificationTypes = new List<NotificationType>();
notificationTypes.Add(new NotificationType("TEST", "Test"));
notificationTypes.Add(new NotificationType("GRAB", "Episode Grabbed"));
notificationTypes.Add(new NotificationType("DOWNLOAD", "Episode Complete"));
return notificationTypes;
return notificationTypes.ToArray();
}
public ValidationFailure Test(GrowlSettings settings)
@ -68,8 +152,6 @@ namespace NzbDrone.Core.Notifications.Growl
const string title = "Test Notification";
const string body = "This is a test message from NzbDrone";
Thread.Sleep(5000);
SendNotification(title, body, "TEST", settings.Host, settings.Port, settings.Password);
}
catch (Exception ex)

@ -52,6 +52,14 @@
<WarningLevel>4</WarningLevel>
</PropertyGroup>
<ItemGroup>
<Reference Include="Growl.Connector, Version=2.0.0.0, Culture=neutral, PublicKeyToken=980c2339411be384, processorArchitecture=MSIL">
<SpecificVersion>False</SpecificVersion>
<HintPath>..\Libraries\Growl.Connector.dll</HintPath>
</Reference>
<Reference Include="Growl.CoreLibrary, Version=2.0.0.0, Culture=neutral, PublicKeyToken=13e59d82e007b064, processorArchitecture=MSIL">
<SpecificVersion>False</SpecificVersion>
<HintPath>..\Libraries\Growl.CoreLibrary.dll</HintPath>
</Reference>
<Reference Include="System" />
<Reference Include="System.Core" />
<Reference Include="System.Data" />
@ -70,12 +78,6 @@
<Reference Include="FluentValidation">
<HintPath>..\packages\FluentValidation.5.0.0.1\lib\Net40\FluentValidation.dll</HintPath>
</Reference>
<Reference Include="Growl.Connector">
<HintPath>..\packages\Growl.0.6\lib\Growl.Connector.dll</HintPath>
</Reference>
<Reference Include="Growl.CoreLibrary">
<HintPath>..\packages\Growl.0.6\lib\Growl.CoreLibrary.dll</HintPath>
</Reference>
<Reference Include="MediaInfoDotNet">
<HintPath>..\packages\MediaInfoNet.0.3\lib\MediaInfoDotNet.dll</HintPath>
</Reference>
@ -661,6 +663,11 @@
<Compile Include="ProgressMessaging\CommandUpdatedEvent.cs" />
<Compile Include="ProgressMessaging\ProgressMessageTarget.cs" />
<Compile Include="Properties\AssemblyInfo.cs" />
<Compile Include="Properties\Resources.Designer.cs">
<AutoGen>True</AutoGen>
<DesignTime>True</DesignTime>
<DependentUpon>Resources.resx</DependentUpon>
</Compile>
<Compile Include="Qualities\QualitiesBelowCutoff.cs" />
<Compile Include="Qualities\Quality.cs" />
<Compile Include="Qualities\QualityDefinition.cs" />
@ -795,8 +802,14 @@
<Content Include="MediaInfo.dll">
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
</Content>
<None Include="Resources\64.png" />
</ItemGroup>
<ItemGroup>
<EmbeddedResource Include="Properties\Resources.resx">
<Generator>ResXFileCodeGenerator</Generator>
<LastGenOutput>Resources.Designer.cs</LastGenOutput>
</EmbeddedResource>
</ItemGroup>
<ItemGroup />
<Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" />
<PropertyGroup>
<PostBuildEvent>

@ -0,0 +1,73 @@
//------------------------------------------------------------------------------
// <auto-generated>
// This code was generated by a tool.
// Runtime Version:4.0.30319.18444
//
// Changes to this file may cause incorrect behavior and will be lost if
// the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------
namespace NzbDrone.Core.Properties {
using System;
/// <summary>
/// A strongly-typed resource class, for looking up localized strings, etc.
/// </summary>
// This class was auto-generated by the StronglyTypedResourceBuilder
// class via a tool like ResGen or Visual Studio.
// To add or remove a member, edit your .ResX file then rerun ResGen
// with the /str option, or rebuild your VS project.
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Resources.Tools.StronglyTypedResourceBuilder", "4.0.0.0")]
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
[global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()]
internal class Resources {
private static global::System.Resources.ResourceManager resourceMan;
private static global::System.Globalization.CultureInfo resourceCulture;
[global::System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")]
internal Resources() {
}
/// <summary>
/// Returns the cached ResourceManager instance used by this class.
/// </summary>
[global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)]
internal static global::System.Resources.ResourceManager ResourceManager {
get {
if (object.ReferenceEquals(resourceMan, null)) {
global::System.Resources.ResourceManager temp = new global::System.Resources.ResourceManager("NzbDrone.Core.Properties.Resources", typeof(Resources).Assembly);
resourceMan = temp;
}
return resourceMan;
}
}
/// <summary>
/// Overrides the current thread's CurrentUICulture property for all
/// resource lookups using this strongly typed resource class.
/// </summary>
[global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)]
internal static global::System.Globalization.CultureInfo Culture {
get {
return resourceCulture;
}
set {
resourceCulture = value;
}
}
/// <summary>
/// Looks up a localized resource of type System.Drawing.Bitmap.
/// </summary>
internal static System.Drawing.Bitmap Icon64 {
get {
object obj = ResourceManager.GetObject("Icon64", resourceCulture);
return ((System.Drawing.Bitmap)(obj));
}
}
}
}

@ -0,0 +1,124 @@
<?xml version="1.0" encoding="utf-8"?>
<root>
<!--
Microsoft ResX Schema
Version 2.0
The primary goals of this format is to allow a simple XML format
that is mostly human readable. The generation and parsing of the
various data types are done through the TypeConverter classes
associated with the data types.
Example:
... ado.net/XML headers & schema ...
<resheader name="resmimetype">text/microsoft-resx</resheader>
<resheader name="version">2.0</resheader>
<resheader name="reader">System.Resources.ResXResourceReader, System.Windows.Forms, ...</resheader>
<resheader name="writer">System.Resources.ResXResourceWriter, System.Windows.Forms, ...</resheader>
<data name="Name1"><value>this is my long string</value><comment>this is a comment</comment></data>
<data name="Color1" type="System.Drawing.Color, System.Drawing">Blue</data>
<data name="Bitmap1" mimetype="application/x-microsoft.net.object.binary.base64">
<value>[base64 mime encoded serialized .NET Framework object]</value>
</data>
<data name="Icon1" type="System.Drawing.Icon, System.Drawing" mimetype="application/x-microsoft.net.object.bytearray.base64">
<value>[base64 mime encoded string representing a byte array form of the .NET Framework object]</value>
<comment>This is a comment</comment>
</data>
There are any number of "resheader" rows that contain simple
name/value pairs.
Each data row contains a name, and value. The row also contains a
type or mimetype. Type corresponds to a .NET class that support
text/value conversion through the TypeConverter architecture.
Classes that don't support this are serialized and stored with the
mimetype set.
The mimetype is used for serialized objects, and tells the
ResXResourceReader how to depersist the object. This is currently not
extensible. For a given mimetype the value must be set accordingly:
Note - application/x-microsoft.net.object.binary.base64 is the format
that the ResXResourceWriter will generate, however the reader can
read any of the formats listed below.
mimetype: application/x-microsoft.net.object.binary.base64
value : The object must be serialized with
: System.Runtime.Serialization.Formatters.Binary.BinaryFormatter
: and then encoded with base64 encoding.
mimetype: application/x-microsoft.net.object.soap.base64
value : The object must be serialized with
: System.Runtime.Serialization.Formatters.Soap.SoapFormatter
: and then encoded with base64 encoding.
mimetype: application/x-microsoft.net.object.bytearray.base64
value : The object must be serialized into a byte array
: using a System.ComponentModel.TypeConverter
: and then encoded with base64 encoding.
-->
<xsd:schema id="root" xmlns="" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:msdata="urn:schemas-microsoft-com:xml-msdata">
<xsd:import namespace="http://www.w3.org/XML/1998/namespace" />
<xsd:element name="root" msdata:IsDataSet="true">
<xsd:complexType>
<xsd:choice maxOccurs="unbounded">
<xsd:element name="metadata">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" />
</xsd:sequence>
<xsd:attribute name="name" use="required" type="xsd:string" />
<xsd:attribute name="type" type="xsd:string" />
<xsd:attribute name="mimetype" type="xsd:string" />
<xsd:attribute ref="xml:space" />
</xsd:complexType>
</xsd:element>
<xsd:element name="assembly">
<xsd:complexType>
<xsd:attribute name="alias" type="xsd:string" />
<xsd:attribute name="name" type="xsd:string" />
</xsd:complexType>
</xsd:element>
<xsd:element name="data">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" msdata:Ordinal="1" />
<xsd:element name="comment" type="xsd:string" minOccurs="0" msdata:Ordinal="2" />
</xsd:sequence>
<xsd:attribute name="name" type="xsd:string" use="required" msdata:Ordinal="1" />
<xsd:attribute name="type" type="xsd:string" msdata:Ordinal="3" />
<xsd:attribute name="mimetype" type="xsd:string" msdata:Ordinal="4" />
<xsd:attribute ref="xml:space" />
</xsd:complexType>
</xsd:element>
<xsd:element name="resheader">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" msdata:Ordinal="1" />
</xsd:sequence>
<xsd:attribute name="name" type="xsd:string" use="required" />
</xsd:complexType>
</xsd:element>
</xsd:choice>
</xsd:complexType>
</xsd:element>
</xsd:schema>
<resheader name="resmimetype">
<value>text/microsoft-resx</value>
</resheader>
<resheader name="version">
<value>2.0</value>
</resheader>
<resheader name="reader">
<value>System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
</resheader>
<resheader name="writer">
<value>System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
</resheader>
<assembly alias="System.Windows.Forms" name="System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" />
<data name="Icon64" type="System.Resources.ResXFileRef, System.Windows.Forms">
<value>..\Resources\64.png;System.Drawing.Bitmap, System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a</value>
</data>
</root>

Binary file not shown.

After

Width:  |  Height:  |  Size: 3.5 KiB

@ -2,7 +2,6 @@
<packages>
<package id="FluentMigrator" version="1.1.1.0" targetFramework="net40" />
<package id="FluentValidation" version="5.0.0.1" targetFramework="net40" />
<package id="Growl" version="0.6" />
<package id="MediaInfoNet" version="0.3" targetFramework="net40" />
<package id="Newtonsoft.Json" version="5.0.8" targetFramework="net40" />
<package id="NLog" version="2.1.0" targetFramework="net40" />

Loading…
Cancel
Save