OSDN Git Service

Merge branch 'dotnet4.5.1'
[opentween/open-tween.git] / OpenTween / MyCommon.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      Egtra (@egtra) <http://dev.activebasic.com/egtra/>
8 //           (c) 2011      kim_upsilon (@kim_upsilon) <https://upsilo.net/~upsilon/>
9 // All rights reserved.
10 // 
11 // This file is part of OpenTween.
12 // 
13 // This program is free software; you can redistribute it and/or modify it
14 // under the terms of the GNU General public License as published by the Free
15 // Software Foundation; either version 3 of the License, or (at your option)
16 // any later version.
17 // 
18 // This program is distributed in the hope that it will be useful, but
19 // WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
20 // or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General public License
21 // for more details. 
22 // 
23 // You should have received a copy of the GNU General public License along
24 // with this program. if not, see <http://www.gnu.org/licenses/>, or write to
25 // the Free Software Foundation, Inc., 51 Franklin Street - Fifth Floor,
26 // Boston, MA 02110-1301, USA.
27
28 using System;
29 using System.Collections.Generic;
30 using System.Linq;
31 using System.Text;
32 using System.IO;
33 using System.Windows.Forms;
34 using System.Web;
35 using System.Globalization;
36 using System.Security.Cryptography;
37 using System.Drawing;
38 using System.Drawing.Imaging;
39 using System.Collections;
40 using System.Security.Principal;
41 using System.Runtime.Serialization.Json;
42 using System.Reflection;
43 using System.Diagnostics;
44 using System.Text.RegularExpressions;
45 using System.Net;
46 using System.Net.Http;
47 using System.Net.NetworkInformation;
48 using System.Runtime.InteropServices;
49 using OpenTween.Api;
50
51 namespace OpenTween
52 {
53     public sealed class MyCommon
54     {
55         private static readonly object LockObj = new object();
56         public static bool _endingFlag;        //終了フラグ
57         public static string cultureStr = null;
58         public static string settingPath;
59
60         public enum IconSizes
61         {
62             IconNone = 0,
63             Icon16 = 1,
64             Icon24 = 2,
65             Icon48 = 3,
66             Icon48_2 = 4,
67         }
68
69         public enum NameBalloonEnum
70         {
71             None,
72             UserID,
73             NickName,
74         }
75
76         public enum DispTitleEnum
77         {
78             None,
79             Ver,
80             Post,
81             UnreadRepCount,
82             UnreadAllCount,
83             UnreadAllRepCount,
84             UnreadCountAllCount,
85             OwnStatus,
86         }
87
88         public enum LogUnitEnum
89         {
90             Minute,
91             Hour,
92             Day,
93         }
94
95         public enum UploadFileType
96         {
97             Invalid,
98             Picture,
99             MultiMedia,
100         }
101
102         public enum UrlConverter
103         {
104             TinyUrl,
105             Isgd,
106             Twurl,
107             Bitly,
108             Jmp,
109             Uxnu,
110             //特殊
111             Nicoms,
112             //廃止
113             Unu = -1,
114         }
115
116         public enum HITRESULT
117         {
118             None,
119             Copy,
120             CopyAndMark,
121             Move,
122             Exclude,
123         }
124
125         public enum HttpTimeOut
126         {
127             MinValue = 10,
128             MaxValue = 120,
129             DefaultValue = 20,
130         }
131
132         //Backgroundworkerへ処理種別を通知するための引数用enum
133         public enum WORKERTYPE
134         {
135             Timeline,                //タイムライン取得
136             Reply,                   //返信取得
137             DirectMessegeRcv,        //受信DM取得
138             DirectMessegeSnt,        //送信DM取得
139             PostMessage,             //発言POST
140             FavAdd,                  //Fav追加
141             FavRemove,               //Fav削除
142             Follower,                //Followerリスト取得
143             Favorites,               //Fav取得
144             Retweet,                 //Retweetする
145             PublicSearch,            //公式検索
146             List,                    //Lists
147             Related,                 //関連発言
148             UserStream,              //UserStream
149             UserTimeline,            //UserTimeline
150             BlockIds,                //Blocking/ids
151             Configuration,           //Twitter Configuration読み込み
152             NoRetweetIds,            //RT非表示ユーザー取得
153             //////
154             ErrorState,              //エラー表示のみで後処理終了(認証エラー時など)
155         }
156
157         public static class DEFAULTTAB
158         {
159             public const string RECENT = "Recent";
160             public const string REPLY = "Reply";
161             public const string DM = "Direct";
162             public const string FAV = "Favorites";
163
164             //private string dummy;
165
166             //private object ReferenceEquals()
167             //{
168             //    return new object();
169             //}
170             //private object Equals()
171             //{
172             //    return new object();
173             //}
174         }
175
176         public static readonly object Block = null;
177         public static bool TraceFlag = false;
178
179 #if DEBUG
180         public static bool DebugBuild = true;
181 #else
182         public static bool DebugBuild = false;
183 #endif
184
185         public enum ACCOUNT_STATE
186         {
187             Valid,
188             Invalid,
189         }
190
191         public enum REPLY_ICONSTATE
192         {
193             None,
194             StaticIcon,
195             BlinkIcon,
196         }
197
198         [FlagsAttribute()]
199         public enum EVENTTYPE
200         {
201             None = 0,
202             Favorite = 1,
203             Unfavorite = 2,
204             Follow = 4,
205             ListMemberAdded = 8,
206             ListMemberRemoved = 16,
207             Block = 32,
208             Unblock = 64,
209             UserUpdate = 128,
210             Deleted = 256,
211             ListCreated = 512,
212             ListUpdated = 1024,
213             Unfollow = 2048,
214             ListUserSubscribed = 4096,
215             ListUserUnsubscribed = 8192,
216             ListDestroyed = 16384,
217
218             All = (None | Favorite | Unfavorite | Follow | ListMemberAdded | ListMemberRemoved |
219                    Block | Unblock | UserUpdate | Deleted | ListCreated | ListUpdated | Unfollow |
220                    ListUserSubscribed | ListUserUnsubscribed | ListDestroyed),
221         }
222
223         public static string GetErrorLogPath()
224         {
225             return Path.Combine(Path.GetDirectoryName(MyCommon.EntryAssembly.Location), "ErrorLogs");
226         }
227
228         public static void TraceOut(WebApiException ex)
229         {
230             var message = ExceptionOutMessage(ex);
231
232             if (ex.ResponseText != null)
233                 message += Environment.NewLine + "------- Response Data -------" + Environment.NewLine + ex.ResponseText;
234
235             TraceOut(TraceFlag, message);
236         }
237
238         public static void TraceOut(Exception ex, string Message)
239         {
240             var buf = ExceptionOutMessage(ex);
241             TraceOut(TraceFlag, Message + Environment.NewLine + buf);
242         }
243
244         public static void TraceOut(string Message)
245         {
246             TraceOut(TraceFlag, Message);
247         }
248
249         public static void TraceOut(bool OutputFlag, string Message)
250         {
251             lock (LockObj)
252             {
253                 if (!OutputFlag) return;
254
255                 var logPath = MyCommon.GetErrorLogPath();
256                 if (!Directory.Exists(logPath))
257                     Directory.CreateDirectory(logPath);
258
259                 var now = DateTime.Now;
260                 var fileName = string.Format("{0}Trace-{1:0000}{2:00}{3:00}-{4:00}{5:00}{6:00}.log", GetAssemblyName(), now.Year, now.Month, now.Day, now.Hour, now.Minute, now.Second);
261                 fileName = Path.Combine(logPath, fileName);
262
263                 using (var writer = new StreamWriter(fileName))
264                 {
265                     writer.WriteLine("**** TraceOut: {0} ****", DateTime.Now.ToString());
266                     writer.WriteLine(Properties.Resources.TraceOutText1, ApplicationSettings.FeedbackEmailAddress);
267                     writer.WriteLine(Properties.Resources.TraceOutText2, ApplicationSettings.FeedbackTwitterName);
268                     writer.WriteLine();
269                     writer.WriteLine(Properties.Resources.TraceOutText3);
270                     writer.WriteLine(Properties.Resources.TraceOutText4, Environment.OSVersion.VersionString);
271                     writer.WriteLine(Properties.Resources.TraceOutText5, Environment.Version.ToString());
272                     writer.WriteLine(Properties.Resources.TraceOutText6, MyCommon.GetAssemblyName(), fileVersion);
273                     writer.WriteLine(Message);
274                     writer.WriteLine();
275                 }
276             }
277         }
278
279         // エラー内容をバッファに書き出し
280         // 注意:最終的にファイル出力されるエラーログに記録されるため次の情報は書き出さない
281         // 文頭メッセージ、権限、動作環境
282         // Dataプロパティにある終了許可フラグのパースもここで行う
283
284         public static string ExceptionOutMessage(Exception ex)
285         {
286             bool IsTerminatePermission = true;
287             return ExceptionOutMessage(ex, ref IsTerminatePermission);
288         }
289
290         public static string ExceptionOutMessage(Exception ex, ref bool IsTerminatePermission)
291         {
292             if (ex == null) return "";
293
294             var buf = new StringBuilder();
295
296             buf.AppendFormat(Properties.Resources.UnhandledExceptionText8, ex.GetType().FullName, ex.Message);
297             buf.AppendLine();
298             if (ex.Data != null)
299             {
300                 var needHeader = true;
301                 foreach (DictionaryEntry dt in ex.Data)
302                 {
303                     if (needHeader)
304                     {
305                         buf.AppendLine();
306                         buf.AppendLine("-------Extra Information-------");
307                         needHeader = false;
308                     }
309                     buf.AppendFormat("{0}  :  {1}", dt.Key, dt.Value);
310                     buf.AppendLine();
311                     if (dt.Key.Equals("IsTerminatePermission"))
312                     {
313                         IsTerminatePermission = (bool)dt.Value;
314                     }
315                 }
316                 if (!needHeader)
317                 {
318                     buf.AppendLine("-----End Extra Information-----");
319                 }
320             }
321             buf.AppendLine(ex.StackTrace);
322             buf.AppendLine();
323
324             //InnerExceptionが存在する場合書き出す
325             var _ex = ex.InnerException;
326             var nesting = 0;
327             while (_ex != null)
328             {
329                 buf.AppendFormat("-----InnerException[{0}]-----\r\n", nesting);
330                 buf.AppendLine();
331                 buf.AppendFormat(Properties.Resources.UnhandledExceptionText8, _ex.GetType().FullName, _ex.Message);
332                 buf.AppendLine();
333                 if (_ex.Data != null)
334                 {
335                     var needHeader = true;
336
337                     foreach (DictionaryEntry dt in _ex.Data)
338                     {
339                         if (needHeader)
340                         {
341                             buf.AppendLine();
342                             buf.AppendLine("-------Extra Information-------");
343                             needHeader = false;
344                         }
345                         buf.AppendFormat("{0}  :  {1}", dt.Key, dt.Value);
346                         if (dt.Key.Equals("IsTerminatePermission"))
347                         {
348                             IsTerminatePermission = (bool)dt.Value;
349                         }
350                     }
351                     if (!needHeader)
352                     {
353                         buf.AppendLine("-----End Extra Information-----");
354                     }
355                 }
356                 buf.AppendLine(_ex.StackTrace);
357                 buf.AppendLine();
358                 nesting++;
359                 _ex = _ex.InnerException;
360             }
361             return buf.ToString();
362         }
363
364         public static bool ExceptionOut(Exception ex)
365         {
366             lock (LockObj)
367             {
368                 var IsTerminatePermission = true;
369
370                 var logPath = MyCommon.GetErrorLogPath();
371                 if (!Directory.Exists(logPath))
372                     Directory.CreateDirectory(logPath);
373
374                 var now = DateTime.Now;
375                 var fileName = string.Format("{0}-{1:0000}{2:00}{3:00}-{4:00}{5:00}{6:00}.log", GetAssemblyName(), now.Year, now.Month, now.Day, now.Hour, now.Minute, now.Second);
376                 fileName = Path.Combine(logPath, fileName);
377
378                 using (var writer = new StreamWriter(fileName))
379                 {
380                     var ident = WindowsIdentity.GetCurrent();
381                     var princ = new WindowsPrincipal(ident);
382
383                     writer.WriteLine(Properties.Resources.UnhandledExceptionText1, DateTime.Now.ToString());
384                     writer.WriteLine(Properties.Resources.UnhandledExceptionText2, ApplicationSettings.FeedbackEmailAddress);
385                     writer.WriteLine(Properties.Resources.UnhandledExceptionText3, ApplicationSettings.FeedbackTwitterName);
386                     // 権限書き出し
387                     writer.WriteLine(Properties.Resources.UnhandledExceptionText11 + princ.IsInRole(WindowsBuiltInRole.Administrator).ToString());
388                     writer.WriteLine(Properties.Resources.UnhandledExceptionText12 + princ.IsInRole(WindowsBuiltInRole.User).ToString());
389                     writer.WriteLine();
390                     // OSVersion,AppVersion書き出し
391                     writer.WriteLine(Properties.Resources.UnhandledExceptionText4);
392                     writer.WriteLine(Properties.Resources.UnhandledExceptionText5, Environment.OSVersion.VersionString);
393                     writer.WriteLine(Properties.Resources.UnhandledExceptionText6, Environment.Version.ToString());
394                     writer.WriteLine(Properties.Resources.UnhandledExceptionText7, MyCommon.GetAssemblyName(), fileVersion);
395
396                     writer.Write(ExceptionOutMessage(ex, ref IsTerminatePermission));
397                     writer.Flush();
398                 }
399
400                 switch (MessageBox.Show(MyCommon.ReplaceAppName(string.Format(Properties.Resources.UnhandledExceptionText9, fileName, ApplicationSettings.FeedbackEmailAddress, ApplicationSettings.FeedbackTwitterName, Environment.NewLine)),
401                                    Properties.Resources.UnhandledExceptionText10, MessageBoxButtons.YesNoCancel, MessageBoxIcon.Error))
402                 {
403                     case DialogResult.Yes:
404                         Process.Start(fileName);
405                         return false;
406                     case DialogResult.No:
407                         return false;
408                     case DialogResult.Cancel:
409                         return IsTerminatePermission;
410                     default:
411                         throw new Exception("");
412                 }
413             }
414         }
415
416         /// <summary>
417         /// URLに含まれているマルチバイト文字列を%xx形式でエンコードします。
418         /// <newpara>
419         /// マルチバイト文字のコードはUTF-8またはUnicodeで自動的に判断します。
420         /// </newpara>
421         /// </summary>
422         /// <param name="_input">エンコード対象のURL</param>
423         /// <returns>マルチバイト文字の部分をUTF-8/%xx形式でエンコードした文字列を返します。</returns>
424
425         public static string urlEncodeMultibyteChar(string _input)
426         {
427             Uri uri = null;
428             var sb = new StringBuilder(256);
429             var result = "";
430             var c_ = 'd';
431             foreach (var c in _input)
432             {
433                 c_ = c;
434                 if (Convert.ToInt32(c) > 127 || c == '%') break;
435             }
436             if (Convert.ToInt32(c_) <= 127 && c_ != '%') return _input;
437
438             var input = Uri.UnescapeDataString(_input);
439         retry:
440             foreach (char c in input)
441             {
442                 if (Convert.ToInt32(c) > 255)
443                 {
444                     // Unicodeの場合(1charが複数のバイトで構成されている)
445                     // Uriクラスをnewして再構成し、入力をPathAndQueryのみとしてやり直す
446                     foreach (var b in Encoding.UTF8.GetBytes(c.ToString()))
447                     {
448                         sb.AppendFormat("%{0:X2}", b);
449                     }
450                 }
451                 else if (Convert.ToInt32(c) > 127 || c == '%')
452                 {
453                     // UTF-8の場合
454                     // Uriクラスをnewして再構成し、入力をinputからAuthority部分を除去してやり直す
455                     if (uri == null)
456                     {
457                         uri = new Uri(input);
458                         input = input.Remove(0, uri.GetLeftPart(UriPartial.Authority).Length);
459                         sb.Length = 0;
460                         goto retry;
461                     }
462                     else
463                     {
464                         sb.Append("%" + Convert.ToInt16(c).ToString("X2").ToUpper());
465                     }
466                 }
467                 else
468                 {
469                     sb.Append(c);
470                 }
471             }
472
473             if (uri == null)
474             {
475                 result = sb.ToString();
476             }
477             else
478             {
479                 result = uri.GetLeftPart(UriPartial.Authority) + sb.ToString();
480             }
481
482             return result;
483         }
484
485         /// <summary>
486         /// URLのドメイン名をPunycode展開します。
487         /// <para>
488         /// ドメイン名がIDNでない場合はそのまま返します。
489         /// ドメインラベルの区切り文字はFULLSTOP(.、U002E)に置き換えられます。
490         /// </para>
491         /// </summary>
492         /// <param name="input">展開対象のURL</param>
493         /// <returns>IDNが含まれていた場合はPunycodeに展開したURLをを返します。Punycode展開時にエラーが発生した場合はnullを返します。</returns>
494         public static string IDNEncode(string inputUrl)
495         {
496             try
497             {
498                 var uriBuilder = new UriBuilder(inputUrl);
499
500                 var idnConverter = new IdnMapping();
501                 uriBuilder.Host = idnConverter.GetAscii(uriBuilder.Host);
502
503                 return uriBuilder.Uri.ToString();
504             }
505             catch (Exception)
506             {
507                 return null;
508             }
509         }
510
511         public static string IDNDecode(string inputUrl)
512         {
513             try
514             {
515                 var uriBuilder = new UriBuilder(inputUrl);
516
517                 if (uriBuilder.Host != null)
518                 {
519                     var idnConverter = new IdnMapping();
520                     uriBuilder.Host = idnConverter.GetUnicode(uriBuilder.Host);
521                 }
522
523                 return uriBuilder.Uri.ToString();
524             }
525             catch (Exception)
526             {
527                 return null;
528             }
529         }
530
531         /// <summary>
532         /// URL を画面上で人間に読みやすい文字列に変換する(エスケープ解除など)
533         /// </summary>
534         public static string ConvertToReadableUrl(string inputUrl)
535         {
536             try
537             {
538                 var outputUrl = inputUrl;
539
540                 // Punycodeをデコードする
541                 outputUrl = MyCommon.IDNDecode(outputUrl);
542                 if (outputUrl == null)
543                     return inputUrl;
544
545                 // URL内で特殊な意味を持つ記号は元の文字に変換されることを避けるために二重エスケープする
546                 // 参考: Firefoxの losslessDecodeURI() 関数
547                 //   http://hg.mozilla.org/mozilla-central/annotate/FIREFOX_AURORA_27_BASE/browser/base/content/browser.js#l2128
548                 outputUrl = Regex.Replace(outputUrl, @"%(2[3456BCF]|3[ABDF]|40)", @"%25$1", RegexOptions.IgnoreCase);
549
550                 // エスケープを解除する
551                 outputUrl = Uri.UnescapeDataString(outputUrl);
552
553                 return outputUrl;
554             }
555             catch (UriFormatException)
556             {
557                 return inputUrl;
558             }
559         }
560
561         public static void MoveArrayItem(int[] values, int idx_fr, int idx_to)
562         {
563             var moved_value = values[idx_fr];
564             var num_moved = Math.Abs(idx_fr - idx_to);
565
566             if (idx_to < idx_fr)
567             {
568                 Array.Copy(values, idx_to, values,
569                     idx_to + 1, num_moved);
570             }
571             else
572             {
573                 Array.Copy(values, idx_fr + 1, values,
574                     idx_fr, num_moved);
575             }
576
577             values[idx_to] = moved_value;
578         }
579
580         public static string EncryptString(string str)
581         {
582             if (string.IsNullOrEmpty(str)) return "";
583
584             //文字列をバイト型配列にする
585             var bytesIn = Encoding.UTF8.GetBytes(str);
586
587             //DESCryptoServiceProviderオブジェクトの作成
588             using (var des = new DESCryptoServiceProvider())
589             {
590                 //共有キーと初期化ベクタを決定
591                 //パスワードをバイト配列にする
592                 var bytesKey = Encoding.UTF8.GetBytes("_tween_encrypt_key_");
593                 //共有キーと初期化ベクタを設定
594                 des.Key = ResizeBytesArray(bytesKey, des.Key.Length);
595                 des.IV = ResizeBytesArray(bytesKey, des.IV.Length);
596
597                 MemoryStream msOut = null;
598                 ICryptoTransform desdecrypt = null;
599
600                 try
601                 {
602                     //暗号化されたデータを書き出すためのMemoryStream
603                     msOut = new MemoryStream();
604
605                     //DES暗号化オブジェクトの作成
606                     desdecrypt = des.CreateEncryptor();
607
608                     //書き込むためのCryptoStreamの作成
609                     using (CryptoStream cryptStream = new CryptoStream(msOut, desdecrypt, CryptoStreamMode.Write))
610                     {
611                         //Disposeが重複して呼ばれないようにする
612                         MemoryStream msTmp = msOut;
613                         msOut = null;
614                         desdecrypt = null;
615
616                         //書き込む
617                         cryptStream.Write(bytesIn, 0, bytesIn.Length);
618                         cryptStream.FlushFinalBlock();
619                         //暗号化されたデータを取得
620                         var bytesOut = msTmp.ToArray();
621
622                         //Base64で文字列に変更して結果を返す
623                         return Convert.ToBase64String(bytesOut);
624                     }
625                 }
626                 finally
627                 {
628                     if (msOut != null) msOut.Dispose();
629                     if (desdecrypt != null) desdecrypt.Dispose();
630                 }
631             }
632         }
633
634         public static string DecryptString(string str)
635         {
636             if (string.IsNullOrEmpty(str)) return "";
637
638             //DESCryptoServiceProviderオブジェクトの作成
639             using (var des = new System.Security.Cryptography.DESCryptoServiceProvider())
640             {
641                 //共有キーと初期化ベクタを決定
642                 //パスワードをバイト配列にする
643                 var bytesKey = Encoding.UTF8.GetBytes("_tween_encrypt_key_");
644                 //共有キーと初期化ベクタを設定
645                 des.Key = ResizeBytesArray(bytesKey, des.Key.Length);
646                 des.IV = ResizeBytesArray(bytesKey, des.IV.Length);
647
648                 //Base64で文字列をバイト配列に戻す
649                 var bytesIn = Convert.FromBase64String(str);
650
651                 MemoryStream msIn = null;
652                 ICryptoTransform desdecrypt = null;
653                 CryptoStream cryptStreem = null;
654
655                 try
656                 {
657                     //暗号化されたデータを読み込むためのMemoryStream
658                     msIn = new MemoryStream(bytesIn);
659                     //DES復号化オブジェクトの作成
660                     desdecrypt = des.CreateDecryptor();
661                     //読み込むためのCryptoStreamの作成
662                     cryptStreem = new CryptoStream(msIn, desdecrypt, CryptoStreamMode.Read);
663
664                     //Disposeが重複して呼ばれないようにする
665                     msIn = null;
666                     desdecrypt = null;
667
668                     //復号化されたデータを取得するためのStreamReader
669                     using (StreamReader srOut = new StreamReader(cryptStreem, Encoding.UTF8))
670                     {
671                         //Disposeが重複して呼ばれないようにする
672                         cryptStreem = null;
673
674                         //復号化されたデータを取得する
675                         var result = srOut.ReadToEnd();
676
677                         return result;
678                     }
679                 }
680                 finally
681                 {
682                     if (msIn != null) msIn.Dispose();
683                     if (desdecrypt != null) desdecrypt.Dispose();
684                     if (cryptStreem != null) cryptStreem.Dispose();
685                 }
686             }
687         }
688
689         public static byte[] ResizeBytesArray(byte[] bytes,
690                                     int newSize)
691         {
692             var newBytes = new byte[newSize];
693             if (bytes.Length <= newSize)
694             {
695                 foreach (var i in Enumerable.Range(0, bytes.Length))
696                 {
697                     newBytes[i] = bytes[i];
698                 }
699             }
700             else
701             {
702                 var pos = 0;
703                 foreach (var i in Enumerable.Range(0, bytes.Length))
704                 {
705                     newBytes[pos] = unchecked((byte)(newBytes[pos] ^ bytes[i]));
706                     pos++;
707                     if (pos >= newBytes.Length)
708                     {
709                         pos = 0;
710                     }
711                 }
712             }
713             return newBytes;
714         }
715
716         public static bool IsNT6()
717         {
718             //NT6 kernelかどうか検査
719             return Environment.OSVersion.Platform == PlatformID.Win32NT && Environment.OSVersion.Version.Major == 6;
720         }
721
722         [FlagsAttribute()]
723         public enum TabUsageType
724         {
725             Undefined = 0,
726             Home = 1,      //Unique
727             Mentions = 2,     //Unique
728             DirectMessage = 4,   //Unique
729             Favorites = 8,       //Unique
730             UserDefined = 16,
731             LocalQuery = 32,      //Pin(no save/no save query/distribute/no update(normal update))
732             Profile = 64,         //Pin(save/no distribute/manual update)
733             PublicSearch = 128,    //Pin(save/no distribute/auto update)
734             Lists = 256,
735             Related = 512,
736             UserTimeline = 1024,
737             //RTMyTweet
738             //RTByOthers
739             //RTByMe
740         }
741
742         public static string fileVersion = "";
743
744         public static string GetUserAgentString(bool fakeMSIE = false)
745         {
746             if (string.IsNullOrEmpty(fileVersion))
747             {
748                 throw new Exception("fileversion is not Initialized.");
749             }
750
751             if (fakeMSIE)
752                 return GetAssemblyName() + "/" + fileVersion + " (compatible; MSIE 10.0)";
753             else
754                 return GetAssemblyName() + "/" + fileVersion;
755         }
756
757         public static TwitterApiStatus TwitterApiInfo = new TwitterApiStatus();
758
759         public static bool IsAnimatedGif(string filename)
760         {
761             Image img = null;
762             try
763             {
764                 img = Image.FromFile(filename);
765                 if (img == null) return false;
766                 if (img.RawFormat.Guid == ImageFormat.Gif.Guid)
767                 {
768                     var fd = new FrameDimension(img.FrameDimensionsList[0]);
769                     var fd_count = img.GetFrameCount(fd);
770                     if (fd_count > 1)
771                     {
772                         return true;
773                     }
774                     else
775                     {
776                         return false;
777                     }
778                 }
779                 return false;
780             }
781             catch (Exception)
782             {
783                 return false;
784             }
785             finally
786             {
787                 if (img != null) img.Dispose();
788             }
789         }
790
791         public static DateTime DateTimeParse(string input)
792         {
793             DateTime rslt;
794             string[] format = {
795                 "ddd MMM dd HH:mm:ss zzzz yyyy",
796                 "ddd, d MMM yyyy HH:mm:ss zzzz",
797             };
798             foreach (var fmt in format)
799             {
800                 if (DateTime.TryParseExact(input,
801                                           fmt,
802                                           DateTimeFormatInfo.InvariantInfo,
803                                           DateTimeStyles.None,
804                                           out rslt))
805                 {
806                     return rslt;
807                 }
808                 else
809                 {
810                     continue;
811                 }
812             }
813             TraceOut("Parse Error(DateTimeFormat) : " + input);
814             return new DateTime();
815         }
816
817         public static T CreateDataFromJson<T>(string content)
818         {
819             T data;
820             var buf = Encoding.Unicode.GetBytes(content);
821             using (var stream = new MemoryStream(buf))
822             {
823                 data = (T)((new DataContractJsonSerializer(typeof(T))).ReadObject(stream));
824             }
825             return data;
826         }
827
828         public static bool IsNetworkAvailable()
829         {
830             try
831             {
832                 return NetworkInterface.GetIsNetworkAvailable();
833             }
834             catch(Exception)
835             {
836                 return false;
837             }
838         }
839
840         public static bool IsValidEmail(string strIn)
841         {
842             // Return true if strIn is in valid e-mail format.
843             return Regex.IsMatch(strIn,
844                    @"^(?("")("".+?""@)|(([0-9a-zA-Z]((\.(?!\.))|[-!#\$%&'\*\+/=\?\^`\{\}\|~\w])*)(?<=[0-9a-zA-Z])@))" +
845                    @"(?(\[)(\[(\d{1,3}\.){3}\d{1,3}\])|(([0-9a-zA-Z][-\w]*[0-9a-zA-Z]\.)+[a-zA-Z]{2,6}))$");
846         }
847
848         /// <summary>
849         /// 指定された修飾キーが押されている状態かを取得します。
850         /// </summary>
851         /// <param name="keys">状態を調べるキー</param>
852         /// <returns><paramref name="keys"/> で指定された修飾キーがすべて押されている状態であれば true。それ以外であれば false。</returns>
853         public static bool IsKeyDown(params Keys[] keys)
854         {
855             return MyCommon._IsKeyDown(Control.ModifierKeys, keys);
856         }
857
858         internal static bool _IsKeyDown(Keys modifierKeys, Keys[] targetKeys)
859         {
860             foreach (Keys key in targetKeys)
861             {
862                 if ((modifierKeys & key) != key)
863                 {
864                     return false;
865                 }
866             }
867             return true;
868         }
869
870         /// <summary>
871         /// アプリケーションのアセンブリ名を取得します。
872         /// </summary>
873         /// <remarks>
874         /// VB.NETの<code>My.Application.Info.AssemblyName</code>と(ほぼ)同じ動作をします。
875         /// </remarks>
876         /// <returns>アプリケーションのアセンブリ名</returns>
877         public static string GetAssemblyName()
878         {
879             return MyCommon.EntryAssembly.GetName().Name;
880         }
881
882         internal static _Assembly EntryAssembly = Assembly.GetEntryAssembly();
883
884         /// <summary>
885         /// 文字列中に含まれる %AppName% をアプリケーション名に置換する
886         /// </summary>
887         /// <param name="orig">対象となる文字列</param>
888         /// <returns>置換後の文字列</returns>
889         public static string ReplaceAppName(string orig)
890         {
891             return MyCommon.ReplaceAppName(orig, Application.ProductName);
892         }
893
894         /// <summary>
895         /// 文字列中に含まれる %AppName% をアプリケーション名に置換する
896         /// </summary>
897         /// <param name="orig">対象となる文字列</param>
898         /// <param name="appname">アプリケーション名</param>
899         /// <returns>置換後の文字列</returns>
900         public static string ReplaceAppName(string orig, string appname)
901         {
902             return orig.Replace("%AppName%", appname);
903         }
904
905         /// <summary>
906         /// 表示用のバージョン番号の文字列を生成する
907         /// </summary>
908         /// <remarks>
909         /// バージョン1.0.0.1のように末尾が0でない(=開発版)の場合は「1.0.1-beta1」が出力される
910         /// </remarks>
911         /// <returns>
912         /// 生成されたバージョン番号の文字列
913         /// </returns>
914         public static string GetReadableVersion(string versionStr = null)
915         {
916             if (versionStr == null)
917             {
918                 if (MyCommon.fileVersion == null)
919                     return null;
920
921                 versionStr = MyCommon.fileVersion;
922             }
923
924             return GetReadableVersion(Version.Parse(versionStr));
925         }
926
927         /// <summary>
928         /// 表示用のバージョン番号の文字列を生成する
929         /// </summary>
930         /// <remarks>
931         /// バージョン1.0.0.1のように末尾が0でない(=開発版)の場合は「1.0.1-beta1」が出力される
932         /// </remarks>
933         /// <returns>
934         /// 生成されたバージョン番号の文字列
935         /// </returns>
936         public static string GetReadableVersion(Version version)
937         {
938             var versionNum = new[] { version.Major, version.Minor, version.Build, version.Revision };
939
940             if (versionNum[3] == 0)
941             {
942                 return string.Format("{0}.{1}.{2}", versionNum[0], versionNum[1], versionNum[2]);
943             }
944             else
945             {
946                 versionNum[2] = versionNum[2] + 1;
947
948                 // 10を越えたら桁上げ
949                 if (versionNum[2] >= 10)
950                 {
951                     versionNum[1] += versionNum[2] / 10;
952                     versionNum[2] %= 10;
953
954                     if (versionNum[1] >= 10)
955                     {
956                         versionNum[0] += versionNum[1] / 10;
957                         versionNum[1] %= 10;
958                     }
959                 }
960
961                 return string.Format("{0}.{1}.{2}-beta{3}", versionNum[0], versionNum[1], versionNum[2], versionNum[3]);
962             }
963         }
964
965         public const string TwitterUrl = "https://twitter.com/";
966
967         public static string GetStatusUrl(PostClass post)
968         {
969             if (post.RetweetedId == null)
970                 return GetStatusUrl(post.ScreenName, post.StatusId);
971             else
972                 return GetStatusUrl(post.ScreenName, post.RetweetedId.Value);
973         }
974
975         public static string GetStatusUrl(string screenName, long statusId)
976         {
977             return TwitterUrl + screenName + "/status/" + statusId.ToString();
978         }
979
980         /// <summary>
981         /// OpenTween 内で共通して使う設定を施した HttpClient インスタンスを作成します
982         /// </summary>
983         public static HttpClient CreateHttpClient()
984         {
985             return CreateHttpClient(new HttpClientHandler());
986         }
987
988         /// <summary>
989         /// OpenTween 内で共通して使う設定を施した HttpClient インスタンスを作成します
990         /// </summary>
991         public static HttpClient CreateHttpClient(HttpClientHandler handler)
992         {
993             switch (HttpConnection.proxyKind)
994             {
995                 case HttpConnection.ProxyType.None:
996                     handler.UseProxy = false;
997                     break;
998                 case HttpConnection.ProxyType.Specified:
999                     handler.UseProxy = true;
1000                     handler.Proxy = HttpConnection.proxy;
1001                     break;
1002                 case HttpConnection.ProxyType.IE:
1003                 default:
1004                     handler.UseProxy = true;
1005                     handler.Proxy = WebRequest.GetSystemWebProxy();
1006                     break;
1007             }
1008
1009             var client = new HttpClient(handler);
1010             client.DefaultRequestHeaders.Add("User-Agent", MyCommon.GetUserAgentString());
1011
1012             return client;
1013         }
1014     }
1015 }