OSDN Git Service

b0cd858aad7281456746bab81c5dd8b304030168
[opentween/open-tween.git] / OpenTween / Growl.cs
1 // OpenTween - Client of Twitter
2 // Copyright (c) 2007-2011 kiri_feather (@kiri_feather) <kiri.feather@gmail.com>
3 //           (c) 2008-2011 Moz (@syo68k)
4 //           (c) 2008-2011 takeshik (@takeshik) <http://www.takeshik.org/>
5 //           (c) 2010-2011 anis774 (@anis774) <http://d.hatena.ne.jp/anis774/>
6 //           (c) 2010-2011 fantasticswallow (@f_swallow) <http://twitter.com/f_swallow>
7 //           (c) 2011      kim_upsilon (@kim_upsilon) <https://upsilo.net/~upsilon/>
8 // All rights reserved.
9 // 
10 // This file is part of OpenTween.
11 // 
12 // This program is free software; you can redistribute it and/or modify it
13 // under the terms of the GNU General public License as published by the Free
14 // Software Foundation; either version 3 of the License, or (at your option)
15 // any later version.
16 // 
17 // This program is distributed in the hope that it will be useful, but
18 // WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
19 // or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General public License
20 // for more details. 
21 // 
22 // You should have received a copy of the GNU General public License along
23 // with this program. If not, see <http://www.gnu.org/licenses/>, or write to
24 // the Free Software Foundation, Inc., 51 Franklin Street - Fifth Floor,
25 // Boston, MA 02110-1301, USA.
26
27 using System;
28 using System.Collections.Generic;
29 using System.Linq;
30 using System.Text;
31 using System.Reflection;
32 using System.IO;
33 using System.Drawing;
34 using System.Drawing.Imaging;
35 using System.Windows.Forms;
36 using System.ComponentModel;
37 using System.Collections;
38 using System.Globalization;
39
40 namespace OpenTween
41 {
42     public class GrowlHelper
43     {
44         private Assembly _connector = null;
45         private Assembly _core = null;
46
47         private object _growlNTreply;
48         private object _growlNTdm;
49         private object _growlNTnew;
50         private object _growlNTusevent;
51         private object _growlApp;
52
53         private object _targetConnector;
54         bool _initialized = false;
55
56         public class NotifyCallbackEventArgs : EventArgs
57         {
58             public long StatusId { get; set; }
59             public NotifyType NotifyType { get; set; }
60             public NotifyCallbackEventArgs(NotifyType notifyType, string statusId)
61             {
62                 if (statusId.Length > 1)
63                 {
64                     this.StatusId = long.Parse(statusId);
65                     this.NotifyType = notifyType;
66                 }
67             }
68         }
69
70         public event EventHandler<NotifyCallbackEventArgs> NotifyClicked;
71
72         public string AppName { get; }
73
74         public enum NotifyType
75         {
76             Reply = 0,
77             DirectMessage = 1,
78             Notify = 2,
79             UserStreamEvent = 3,
80         }
81
82         public GrowlHelper(string appName)
83             => this.AppName = appName;
84
85         public bool IsAvailable
86         {
87             get
88             {
89                 if (_connector == null || _core == null || !_initialized)
90                     return false;
91                 else
92                     return true;
93             }
94         }
95
96         private byte[] IconToByteArray(string filename)
97         {
98             using var ic = new Icon(filename);
99             return IconToByteArray(ic);
100         }
101
102         private byte[] IconToByteArray(Icon icondata)
103         {
104             using var ms = new MemoryStream();
105             using var ic = new Icon(icondata, 48, 48);
106             ic.ToBitmap().Save(ms, ImageFormat.Png);
107             return ms.ToArray();
108         }
109
110         public static bool IsDllExists
111         {
112             get
113             {
114                 var dir = Application.StartupPath;
115                 var connectorPath = Path.Combine(dir, "Growl.Connector.dll");
116                 var corePath = Path.Combine(dir, "Growl.CoreLibrary.dll");
117                 if (File.Exists(connectorPath) && File.Exists(corePath))
118                     return true;
119                 else
120                     return false;
121             }
122         }
123
124         public bool RegisterGrowl()
125         {
126             _initialized = false;
127             var dir = Application.StartupPath;
128             var connectorPath = Path.Combine(dir, "Growl.Connector.dll");
129             var corePath = Path.Combine(dir, "Growl.CoreLibrary.dll");
130
131             try
132             {
133                 if (!IsDllExists) return false;
134                 _connector = Assembly.LoadFile(connectorPath);
135                 _core = Assembly.LoadFile(corePath);
136             }
137             catch (Exception)
138             {
139                 return false;
140             }
141
142             try
143             {
144                 _targetConnector = _connector.CreateInstance("Growl.Connector.GrowlConnector");
145                 var _t = _connector.GetType("Growl.Connector.NotificationType");
146
147                 _growlNTreply = _t.InvokeMember(null,
148                     BindingFlags.CreateInstance, null, null, new object[] { "REPLY", "Reply" }, CultureInfo.InvariantCulture);
149
150                 _growlNTdm = _t.InvokeMember(null,
151                     BindingFlags.CreateInstance, null, null, new object[] { "DIRECT_MESSAGE", "DirectMessage" }, CultureInfo.InvariantCulture);
152
153                 _growlNTnew = _t.InvokeMember(null,
154                     BindingFlags.CreateInstance, null, null, new object[] { "NOTIFY", "新着通知" }, CultureInfo.InvariantCulture);
155
156                 _growlNTusevent = _t.InvokeMember(null,
157                     BindingFlags.CreateInstance, null, null, new object[] { "USERSTREAM_EVENT", "UserStream Event" }, CultureInfo.InvariantCulture);
158
159                 var encryptType =
160                         _connector.GetType("Growl.Connector.Cryptography+SymmetricAlgorithmType").InvokeMember(
161                             "PlainText", BindingFlags.GetField, null, null, null, CultureInfo.InvariantCulture);
162                 _targetConnector.GetType().InvokeMember("EncryptionAlgorithm", BindingFlags.SetProperty, null, _targetConnector, new object[] { encryptType }, CultureInfo.InvariantCulture);
163
164                 _growlApp = _connector.CreateInstance(
165                     "Growl.Connector.Application", false, BindingFlags.Default, null, new object[] { AppName }, null, null);
166
167
168                 if (File.Exists(Path.Combine(Application.StartupPath, "Icons\\Tween.png")))
169                 {
170                     // Icons\Tween.pngを使用
171                     var ci = _core.GetType(
172                         "Growl.CoreLibrary.Resource").GetConstructor(
173                         BindingFlags.NonPublic | BindingFlags.Instance,
174                         null, new Type[] { typeof(string) }, null);
175
176                     var data = ci.Invoke(new object[] { Path.Combine(Application.StartupPath, "Icons\\Tween.png") });
177                     var pi = _growlApp.GetType().GetProperty("Icon");
178                     pi.SetValue(_growlApp, data, null);
179
180                 }
181                 else if (File.Exists(Path.Combine(Application.StartupPath, "Icons\\MIcon.ico")))
182                 {
183                     // アイコンセットにMIcon.icoが存在する場合それを使用
184                     var cibd = _core.GetType(
185                         "Growl.CoreLibrary.BinaryData").GetConstructor(
186                         BindingFlags.Public | BindingFlags.Instance,
187                         null, new Type[] { typeof(byte[]) }, null);
188                     var bdata = cibd.Invoke(
189                         new object[] { IconToByteArray(Path.Combine(Application.StartupPath, "Icons\\MIcon.ico")) });
190
191                     var ciRes = _core.GetType(
192                         "Growl.CoreLibrary.Resource").GetConstructor(
193                         BindingFlags.NonPublic | BindingFlags.Instance,
194                         null, new Type[] { bdata.GetType() }, null);
195
196                     var data = ciRes.Invoke(new object[] { bdata });
197                     var pi = _growlApp.GetType().GetProperty("Icon");
198                     pi.SetValue(_growlApp, data, null);
199                 }
200                 else
201                 {
202                     //内蔵アイコンリソースを使用
203                     var cibd = _core.GetType(
204                         "Growl.CoreLibrary.BinaryData").GetConstructor(
205                         BindingFlags.Public | BindingFlags.Instance,
206                         null, new Type[] { typeof(byte[]) }, null);
207                     var bdata = cibd.Invoke(
208                         new object[] { IconToByteArray(Properties.Resources.MIcon) });
209
210                     var ciRes = _core.GetType(
211                         "Growl.CoreLibrary.Resource").GetConstructor(
212                         BindingFlags.NonPublic | BindingFlags.Instance,
213                         null, new Type[] { bdata.GetType() }, null);
214
215                     var data = ciRes.Invoke(new object[] { bdata });
216                     var pi = _growlApp.GetType().GetProperty("Icon");
217                     pi.SetValue(_growlApp, data, null);
218                 }
219
220                 var mi = _targetConnector.GetType().GetMethod("Register", new Type[] { _growlApp.GetType(), _connector.GetType("Growl.Connector.NotificationType[]") });
221
222                 _t = _connector.GetType("Growl.Connector.NotificationType");
223
224                 var arglist = new ArrayList
225                 {
226                     _growlNTreply,
227                     _growlNTdm,
228                     _growlNTnew,
229                     _growlNTusevent,
230                 };
231
232                 mi.Invoke(_targetConnector, new object[] { _growlApp, arglist.ToArray(_t) });
233
234                 // コールバックメソッドの登録
235                 var tGrowlConnector = _connector.GetType("Growl.Connector.GrowlConnector");
236                 var evNotificationCallback = tGrowlConnector.GetEvent("NotificationCallback");
237                 var tDelegate = evNotificationCallback.EventHandlerType;
238                 var miHandler = typeof(GrowlHelper).GetMethod("GrowlCallbackHandler", BindingFlags.NonPublic | BindingFlags.Instance);
239                 var d = Delegate.CreateDelegate(tDelegate, this, miHandler);
240                 var miAddHandler = evNotificationCallback.GetAddMethod();
241                 object[] addHandlerArgs = { d };
242                 miAddHandler.Invoke(_targetConnector, addHandlerArgs);
243
244                 _initialized = true;
245             }
246             catch (Exception)
247             {
248                 _initialized = false;
249                 return false;
250             }
251
252             return true;
253         }
254
255         public void Notify(NotifyType notificationType, string id, string title, string text, Image icon = null, string url = "")
256         {
257             if (!_initialized) return;
258             var notificationName = "";
259             switch (notificationType)
260             {
261                 case NotifyType.Reply:
262                     notificationName = "REPLY";
263                     break;
264                 case NotifyType.DirectMessage:
265                     notificationName = "DIRECT_MESSAGE";
266                     break;
267                 case NotifyType.Notify:
268                     notificationName = "NOTIFY";
269                     break;
270                 case NotifyType.UserStreamEvent:
271                     notificationName = "USERSTREAM_EVENT";
272                     break;
273             }
274             object n;
275             if (icon != null || !string.IsNullOrEmpty(url))
276             {
277                 var gCore = _core.GetType("Growl.CoreLibrary.Resource");
278                 object res;
279                 if (icon != null)
280                 {
281                     res = gCore.InvokeMember("op_Implicit",
282                                              BindingFlags.Public | BindingFlags.Static | BindingFlags.InvokeMethod,
283                                              null,
284                                              null,
285                                              new object[] { icon },
286                                              CultureInfo.InvariantCulture);
287                 }
288                 else
289                 {
290                     res = gCore.InvokeMember("op_Implicit",
291                                              BindingFlags.Public | BindingFlags.Static | BindingFlags.InvokeMethod,
292                                              null,
293                                              null,
294                                              new object[] { url },
295                                              CultureInfo.InvariantCulture);
296                 }
297                 var priority =
298                         _connector.GetType("Growl.Connector.Priority").InvokeMember(
299                             "Normal", BindingFlags.GetField, null, null, null, CultureInfo.InvariantCulture);
300                 n = _connector.GetType("Growl.Connector.Notification").InvokeMember(
301                         "Notification",
302                         BindingFlags.CreateInstance,
303                         null,
304                         _connector,
305                         new object[] {AppName,
306                                       notificationName,
307                                       id,
308                                       title,
309                                       text,
310                                       res,
311                                       false,
312                                       priority,
313                                       "aaa"},
314                         CultureInfo.InvariantCulture);
315             }
316             else
317             {
318                 n = _connector.GetType("Growl.Connector.Notification").InvokeMember(
319                         "Notification",
320                         BindingFlags.CreateInstance,
321                         null,
322                         _connector,
323                         new object[] {AppName,
324                                       notificationName,
325                                       id,
326                                       title,
327                                       text},
328                         CultureInfo.InvariantCulture);
329             }
330             //_targetConnector.GetType.InvokeMember("Notify", BindingFlags.InvokeMethod, null, _targetConnector, new object[] {n});
331             var cc = _connector.GetType("Growl.Connector.CallbackContext").InvokeMember(
332                 null, BindingFlags.CreateInstance, null, _connector,
333                 new object[] { "some fake information", notificationName },
334                 CultureInfo.InvariantCulture);
335             _targetConnector.GetType().InvokeMember("Notify", BindingFlags.InvokeMethod, null, _targetConnector, new object[] { n, cc }, CultureInfo.InvariantCulture);
336         }
337
338         private void GrowlCallbackHandler(object response, object callbackData, object state)
339         {
340             try
341             {
342                 // 定数取得
343                 var vCLICK =
344                 _core.GetType("Growl.CoreLibrary.CallbackResult").GetField(
345                             "CLICK",
346                            BindingFlags.Public | BindingFlags.Static).GetRawConstantValue();
347                 // 実際の値
348                 var vResult = callbackData.GetType().GetProperty(
349                             "Result",
350                             BindingFlags.Public | BindingFlags.Instance).GetGetMethod().Invoke(callbackData, null);
351                 vResult = (int)vResult;
352                 var notifyId = (string)callbackData.GetType().GetProperty("NotificationID").GetGetMethod().Invoke(callbackData, null);
353                 var notifyName = (string)callbackData.GetType().GetProperty("Type").GetGetMethod().Invoke(callbackData, null);
354                 if (vCLICK.Equals(vResult))
355                 {
356                     NotifyType nt;
357                     switch (notifyName)
358                     {
359                         case "REPLY":
360                             nt = NotifyType.Reply;
361                             break;
362                         case "DIRECT_MESSAGE":
363                             nt = NotifyType.DirectMessage;
364                             break;
365                         case "NOTIFY":
366                             nt = NotifyType.Notify;
367                             break;
368                         case "USERSTREAM_EVENT":
369                             nt = NotifyType.UserStreamEvent;
370                             break;
371                         default:
372                             return;
373                     }
374
375                     NotifyClicked?.Invoke(this, new NotifyCallbackEventArgs(nt, notifyId));
376                 }
377             }
378             catch (Exception)
379             {
380                 return;
381             }
382         }
383     }
384 }