OSDN Git Service

PostClass.CreatedAtの型をDateTimeUtcに変更
[opentween/open-tween.git] / OpenTween / MyCommon.cs
index 23ce50d..1ed1596 100644 (file)
@@ -42,17 +42,20 @@ using System.Runtime.Serialization.Json;
 using System.Reflection;
 using System.Diagnostics;
 using System.Text.RegularExpressions;
+using System.Net;
+using System.Net.Http;
 using System.Net.NetworkInformation;
 using System.Runtime.InteropServices;
 using OpenTween.Api;
+using OpenTween.Models;
+using OpenTween.Setting;
 
 namespace OpenTween
 {
-    public sealed class MyCommon
+    public static class MyCommon
     {
         private static readonly object LockObj = new object();
         public static bool _endingFlag;        //終了フラグ
-        public static string cultureStr = null;
         public static string settingPath;
 
         public enum IconSizes
@@ -111,12 +114,6 @@ namespace OpenTween
             Unu = -1,
         }
 
-        public enum OutputzUrlmode
-        {
-            twittercom,
-            twittercomWithUsername,
-        }
-
         public enum HITRESULT
         {
             None,
@@ -129,7 +126,7 @@ namespace OpenTween
         public enum HttpTimeOut
         {
             MinValue = 10,
-            MaxValue = 120,
+            MaxValue = 1000,
             DefaultValue = 20,
         }
 
@@ -164,6 +161,7 @@ namespace OpenTween
             public const string REPLY = "Reply";
             public const string DM = "Direct";
             public const string FAV = "Favorites";
+            public static readonly string MUTE = Properties.Resources.MuteTabName;
 
             //private string dummy;
 
@@ -199,7 +197,7 @@ namespace OpenTween
             BlinkIcon,
         }
 
-        [FlagsAttribute()]
+        [Flags]
         public enum EVENTTYPE
         {
             None = 0,
@@ -217,10 +215,29 @@ namespace OpenTween
             Unfollow = 2048,
             ListUserSubscribed = 4096,
             ListUserUnsubscribed = 8192,
+            ListDestroyed = 16384,
+            Mute = 32768,
+            Unmute = 65536,
+            QuotedTweet = 131072,
+            Retweet = 262144,
 
             All = (None | Favorite | Unfavorite | Follow | ListMemberAdded | ListMemberRemoved |
                    Block | Unblock | UserUpdate | Deleted | ListCreated | ListUpdated | Unfollow |
-                   ListUserSubscribed | ListUserUnsubscribed),
+                   ListUserSubscribed | ListUserUnsubscribed | ListDestroyed |
+                   Mute | Unmute | QuotedTweet | Retweet),
+        }
+
+        public static _Assembly EntryAssembly { get; internal set; }
+        public static string FileVersion { get; internal set; }
+
+        static MyCommon()
+        {
+            var assembly = Assembly.GetExecutingAssembly();
+            MyCommon.EntryAssembly = assembly;
+
+            var fileVersionAttribute = (AssemblyFileVersionAttribute)assembly
+                .GetCustomAttributes(typeof(AssemblyFileVersionAttribute)).First();
+            MyCommon.FileVersion = fileVersionAttribute.Version;
         }
 
         public static string GetErrorLogPath()
@@ -265,14 +282,14 @@ namespace OpenTween
 
                 using (var writer = new StreamWriter(fileName))
                 {
-                    writer.WriteLine("**** TraceOut: {0} ****", DateTime.Now.ToString());
+                    writer.WriteLine("**** TraceOut: {0} ****", DateTime.Now);
                     writer.WriteLine(Properties.Resources.TraceOutText1, ApplicationSettings.FeedbackEmailAddress);
                     writer.WriteLine(Properties.Resources.TraceOutText2, ApplicationSettings.FeedbackTwitterName);
                     writer.WriteLine();
                     writer.WriteLine(Properties.Resources.TraceOutText3);
                     writer.WriteLine(Properties.Resources.TraceOutText4, Environment.OSVersion.VersionString);
-                    writer.WriteLine(Properties.Resources.TraceOutText5, Environment.Version.ToString());
-                    writer.WriteLine(Properties.Resources.TraceOutText6, MyCommon.GetAssemblyName(), fileVersion);
+                    writer.WriteLine(Properties.Resources.TraceOutText5, Environment.Version);
+                    writer.WriteLine(Properties.Resources.TraceOutText6, MyCommon.GetAssemblyName(), FileVersion);
                     writer.WriteLine(Message);
                     writer.WriteLine();
                 }
@@ -370,49 +387,72 @@ namespace OpenTween
             {
                 var IsTerminatePermission = true;
 
+                var ident = WindowsIdentity.GetCurrent();
+                var princ = new WindowsPrincipal(ident);
+
+                var errorReport = string.Join(Environment.NewLine,
+                    string.Format(Properties.Resources.UnhandledExceptionText1, DateTime.Now),
+
+                    // 権限書き出し
+                    string.Format(Properties.Resources.UnhandledExceptionText11 + princ.IsInRole(WindowsBuiltInRole.Administrator)),
+                    string.Format(Properties.Resources.UnhandledExceptionText12 + princ.IsInRole(WindowsBuiltInRole.User)),
+                    "",
+
+                    // OSVersion,AppVersion書き出し
+                    string.Format(Properties.Resources.UnhandledExceptionText4),
+                    string.Format(Properties.Resources.UnhandledExceptionText5, Environment.OSVersion.VersionString),
+                    string.Format(Properties.Resources.UnhandledExceptionText6, Environment.Version),
+                    string.Format(Properties.Resources.UnhandledExceptionText7, MyCommon.GetAssemblyName(), FileVersion),
+
+                    ExceptionOutMessage(ex, ref IsTerminatePermission));
+
                 var logPath = MyCommon.GetErrorLogPath();
                 if (!Directory.Exists(logPath))
                     Directory.CreateDirectory(logPath);
 
                 var now = DateTime.Now;
                 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);
-                fileName = Path.Combine(logPath, fileName);
-
-                using (var writer = new StreamWriter(fileName))
+                using (var writer = new StreamWriter(Path.Combine(logPath, fileName)))
                 {
-                    var ident = WindowsIdentity.GetCurrent();
-                    var princ = new WindowsPrincipal(ident);
+                    writer.Write(errorReport);
+                }
 
-                    writer.WriteLine(Properties.Resources.UnhandledExceptionText1, DateTime.Now.ToString());
-                    writer.WriteLine(Properties.Resources.UnhandledExceptionText2, ApplicationSettings.FeedbackEmailAddress);
-                    writer.WriteLine(Properties.Resources.UnhandledExceptionText3, ApplicationSettings.FeedbackTwitterName);
-                    // 権限書き出し
-                    writer.WriteLine(Properties.Resources.UnhandledExceptionText11 + princ.IsInRole(WindowsBuiltInRole.Administrator).ToString());
-                    writer.WriteLine(Properties.Resources.UnhandledExceptionText12 + princ.IsInRole(WindowsBuiltInRole.User).ToString());
-                    writer.WriteLine();
-                    // OSVersion,AppVersion書き出し
-                    writer.WriteLine(Properties.Resources.UnhandledExceptionText4);
-                    writer.WriteLine(Properties.Resources.UnhandledExceptionText5, Environment.OSVersion.VersionString);
-                    writer.WriteLine(Properties.Resources.UnhandledExceptionText6, Environment.Version.ToString());
-                    writer.WriteLine(Properties.Resources.UnhandledExceptionText7, MyCommon.GetAssemblyName(), fileVersion);
+                var settings = SettingManager.Common;
+                var mainForm = Application.OpenForms.OfType<TweenMain>().FirstOrDefault();
 
-                    writer.Write(ExceptionOutMessage(ex, ref IsTerminatePermission));
-                    writer.Flush();
-                }
+                ErrorReport report;
+                if (mainForm != null && !mainForm.IsDisposed)
+                    report = new ErrorReport(mainForm.TwitterInstance, errorReport);
+                else
+                    report = new ErrorReport(errorReport);
 
-                switch (MessageBox.Show(MyCommon.ReplaceAppName(string.Format(Properties.Resources.UnhandledExceptionText9, fileName, ApplicationSettings.FeedbackEmailAddress, ApplicationSettings.FeedbackTwitterName, Environment.NewLine)),
-                                   Properties.Resources.UnhandledExceptionText10, MessageBoxButtons.YesNoCancel, MessageBoxIcon.Error))
+                report.AnonymousReport = settings.ErrorReportAnonymous;
+
+                OpenErrorReportDialog(mainForm, report);
+
+                // ダイアログ内で設定が変更されていれば保存する
+                if (settings.ErrorReportAnonymous != report.AnonymousReport)
                 {
-                    case DialogResult.Yes:
-                        Process.Start(fileName);
-                        return false;
-                    case DialogResult.No:
-                        return false;
-                    case DialogResult.Cancel:
-                        return IsTerminatePermission;
-                    default:
-                        throw new Exception("");
+                    settings.ErrorReportAnonymous = report.AnonymousReport;
+                    settings.Save();
                 }
+
+                return false;
+            }
+        }
+
+        private static void OpenErrorReportDialog(Form owner, ErrorReport report)
+        {
+            if (owner != null && owner.InvokeRequired)
+            {
+                owner.Invoke((Action)(() => OpenErrorReportDialog(owner, report)));
+                return;
+            }
+
+            using (var dialog = new SendErrorReportForm())
+            {
+                dialog.ErrorReport = report;
+                dialog.ShowDialog(owner);
             }
         }
 
@@ -464,7 +504,7 @@ namespace OpenTween
                     }
                     else
                     {
-                        sb.Append("%" + Convert.ToInt16(c).ToString("X2").ToUpper());
+                        sb.Append("%" + Convert.ToInt16(c).ToString("X2").ToUpperInvariant());
                     }
                 }
                 else
@@ -479,43 +519,86 @@ namespace OpenTween
             }
             else
             {
-                result = uri.GetLeftPart(UriPartial.Authority) + sb.ToString();
+                result = uri.GetLeftPart(UriPartial.Authority) + sb;
             }
 
             return result;
         }
 
-        ////// <summary>
-        ////// URLのドメイン名をPunycode展開します。
-        ////// <para>
-        ////// ドメイン名がIDNでない場合はそのまま返します。
-        ////// ドメインラベルの区切り文字はFULLSTOP(.、U002E)に置き換えられます。
-        ////// </para>
-        ////// </summary>
-        ////// <param name="input">展開対象のURL</param>
-        ////// <returns>IDNが含まれていた場合はPunycodeに展開したURLをを返します。Punycode展開時にエラーが発生した場合はnullを返します。</returns>
-
-        public static string IDNDecode(string input)
+        /// <summary>
+        /// URLのドメイン名をPunycode展開します。
+        /// <para>
+        /// ドメイン名がIDNでない場合はそのまま返します。
+        /// ドメインラベルの区切り文字はFULLSTOP(.、U002E)に置き換えられます。
+        /// </para>
+        /// </summary>
+        /// <param name="inputUrl">展開対象のURL</param>
+        /// <returns>IDNが含まれていた場合はPunycodeに展開したURLをを返します。Punycode展開時にエラーが発生した場合はnullを返します。</returns>
+        public static string IDNEncode(string inputUrl)
         {
-            var IDNConverter = new IdnMapping();
+            try
+            {
+                var uriBuilder = new UriBuilder(inputUrl);
 
-            if (!input.Contains("://")) return null;
+                var idnConverter = new IdnMapping();
+                uriBuilder.Host = idnConverter.GetAscii(uriBuilder.Host);
 
-            // ドメイン名をPunycode展開
-            string Domain;
-            string AsciiDomain;
+                return uriBuilder.Uri.AbsoluteUri;
+            }
+            catch (Exception)
+            {
+                return null;
+            }
+        }
 
+        public static string IDNDecode(string inputUrl)
+        {
             try
             {
-                Domain = input.Split('/')[2];
-                AsciiDomain = IDNConverter.GetAscii(Domain);
+                var uriBuilder = new UriBuilder(inputUrl);
+
+                if (uriBuilder.Host != null)
+                {
+                    var idnConverter = new IdnMapping();
+                    uriBuilder.Host = idnConverter.GetUnicode(uriBuilder.Host);
+                }
+
+                return uriBuilder.Uri.AbsoluteUri;
             }
             catch (Exception)
             {
                 return null;
             }
+        }
 
-            return input.Replace("://" + Domain, "://" + AsciiDomain);
+        /// <summary>
+        /// URL を画面上で人間に読みやすい文字列に変換する(エスケープ解除など)
+        /// </summary>
+        public static string ConvertToReadableUrl(string inputUrl)
+        {
+            try
+            {
+                var outputUrl = inputUrl;
+
+                // Punycodeをデコードする
+                outputUrl = MyCommon.IDNDecode(outputUrl);
+                if (outputUrl == null)
+                    return inputUrl;
+
+                // URL内で特殊な意味を持つ記号は元の文字に変換されることを避けるために二重エスケープする
+                // 参考: Firefoxの losslessDecodeURI() 関数
+                //   http://hg.mozilla.org/mozilla-central/annotate/FIREFOX_AURORA_27_BASE/browser/base/content/browser.js#l2128
+                outputUrl = Regex.Replace(outputUrl, @"%(2[3456BCF]|3[ABDF]|40)", @"%25$1", RegexOptions.IgnoreCase);
+
+                // エスケープを解除する
+                outputUrl = Uri.UnescapeDataString(outputUrl);
+
+                return outputUrl;
+            }
+            catch (UriFormatException)
+            {
+                return inputUrl;
+            }
         }
 
         public static void MoveArrayItem(int[] values, int idx_fr, int idx_to)
@@ -585,8 +668,8 @@ namespace OpenTween
                 }
                 finally
                 {
-                    if (msOut != null) msOut.Dispose();
-                    if (desdecrypt != null) desdecrypt.Dispose();
+                    msOut?.Dispose();
+                    desdecrypt?.Dispose();
                 }
             }
         }
@@ -639,9 +722,9 @@ namespace OpenTween
                 }
                 finally
                 {
-                    if (msIn != null) msIn.Dispose();
-                    if (desdecrypt != null) desdecrypt.Dispose();
-                    if (cryptStreem != null) cryptStreem.Dispose();
+                    msIn?.Dispose();
+                    desdecrypt?.Dispose();
+                    cryptStreem?.Dispose();
                 }
             }
         }
@@ -673,13 +756,7 @@ namespace OpenTween
             return newBytes;
         }
 
-        public static bool IsNT6()
-        {
-            //NT6 kernelかどうか検査
-            return Environment.OSVersion.Platform == PlatformID.Win32NT && Environment.OSVersion.Version.Major == 6;
-        }
-
-        [FlagsAttribute()]
+        [Flags]
         public enum TabUsageType
         {
             Undefined = 0,
@@ -694,22 +771,13 @@ namespace OpenTween
             Lists = 256,
             Related = 512,
             UserTimeline = 1024,
+            Mute = 2048,
+            SearchResults = 4096,
             //RTMyTweet
             //RTByOthers
             //RTByMe
         }
 
-        public static string fileVersion = "";
-
-        public static string GetUserAgentString()
-        {
-            if (string.IsNullOrEmpty(fileVersion))
-            {
-                throw new Exception("fileversion is not Initialized.");
-            }
-            return GetAssemblyName() + "/" + fileVersion;
-        }
-
         public static TwitterApiStatus TwitterApiInfo = new TwitterApiStatus();
 
         public static bool IsAnimatedGif(string filename)
@@ -740,13 +808,12 @@ namespace OpenTween
             }
             finally
             {
-                if (img != null) img.Dispose();
+                img?.Dispose();
             }
         }
 
         public static DateTime DateTimeParse(string input)
         {
-            DateTime rslt;
             string[] format = {
                 "ddd MMM dd HH:mm:ss zzzz yyyy",
                 "ddd, d MMM yyyy HH:mm:ss zzzz",
@@ -757,7 +824,7 @@ namespace OpenTween
                                           fmt,
                                           DateTimeFormatInfo.InvariantInfo,
                                           DateTimeStyles.None,
-                                          out rslt))
+                                          out var rslt))
                 {
                     return rslt;
                 }
@@ -776,7 +843,11 @@ namespace OpenTween
             var buf = Encoding.Unicode.GetBytes(content);
             using (var stream = new MemoryStream(buf))
             {
-                data = (T)((new DataContractJsonSerializer(typeof(T))).ReadObject(stream));
+                var settings = new DataContractJsonSerializerSettings
+                {
+                    UseSimpleDictionaryFormat = true,
+                };
+                data = (T)((new DataContractJsonSerializer(typeof(T), settings)).ReadObject(stream));
             }
             return data;
         }
@@ -835,8 +906,6 @@ namespace OpenTween
             return MyCommon.EntryAssembly.GetName().Name;
         }
 
-        internal static _Assembly EntryAssembly = Assembly.GetEntryAssembly();
-
         /// <summary>
         /// 文字列中に含まれる %AppName% をアプリケーション名に置換する
         /// </summary>
@@ -867,43 +936,51 @@ namespace OpenTween
         /// <returns>
         /// 生成されたバージョン番号の文字列
         /// </returns>
-        public static string GetReadableVersion(string fileVersion = null)
+        public static string GetReadableVersion(string versionStr = null)
         {
-            if (fileVersion == null)
-            {
-                fileVersion = MyCommon.fileVersion;
-            }
+            var version = Version.Parse(versionStr ?? MyCommon.FileVersion);
 
-            if (string.IsNullOrEmpty(fileVersion))
-            {
-                return null;
-            }
+            return GetReadableVersion(version);
+        }
 
-            int[] version = fileVersion.Split('.')
-                .Select(x => int.Parse(x)).ToArray();
+        /// <summary>
+        /// 表示用のバージョン番号の文字列を生成する
+        /// </summary>
+        /// <remarks>
+        /// バージョン1.0.0.1のように末尾が0でない(=開発版)の場合は「1.0.1-dev」のように出力される
+        /// </remarks>
+        /// <returns>
+        /// 生成されたバージョン番号の文字列
+        /// </returns>
+        public static string GetReadableVersion(Version version)
+        {
+            var versionNum = new[] { version.Major, version.Minor, version.Build, version.Revision };
 
-            if (version[3] == 0)
+            if (versionNum[3] == 0)
             {
-                return string.Format("{0}.{1}.{2}", version[0], version[1], version[2]);
+                return string.Format("{0}.{1}.{2}", versionNum[0], versionNum[1], versionNum[2]);
             }
             else
             {
-                version[2] = version[2] + 1;
+                versionNum[2] = versionNum[2] + 1;
 
                 // 10を越えたら桁上げ
-                if (version[2] >= 10)
+                if (versionNum[2] >= 10)
                 {
-                    version[1] += version[2] / 10;
-                    version[2] %= 10;
+                    versionNum[1] += versionNum[2] / 10;
+                    versionNum[2] %= 10;
 
-                    if (version[1] >= 10)
+                    if (versionNum[1] >= 10)
                     {
-                        version[0] += version[1] / 10;
-                        version[1] %= 10;
+                        versionNum[0] += versionNum[1] / 10;
+                        versionNum[1] %= 10;
                     }
                 }
 
-                return string.Format("{0}.{1}.{2}-beta{3}", version[0], version[1], version[2], version[3]);
+                if (versionNum[3] == 1)
+                    return string.Format("{0}.{1}.{2}-dev", versionNum[0], versionNum[1], versionNum[2]);
+                else
+                    return string.Format("{0}.{1}.{2}-dev (Build {3})", versionNum[0], versionNum[1], versionNum[2], versionNum[3]);
             }
         }
 
@@ -919,7 +996,134 @@ namespace OpenTween
 
         public static string GetStatusUrl(string screenName, long statusId)
         {
-            return TwitterUrl + screenName + "/status/" + statusId.ToString();
+            return TwitterUrl + screenName + "/status/" + statusId;
+        }
+
+        /// <summary>
+        /// 指定された IDictionary を元にクエリ文字列を生成します
+        /// </summary>
+        /// <param name="param">生成するクエリの key-value コレクション</param>
+        public static string BuildQueryString(IEnumerable<KeyValuePair<string, string>> param)
+        {
+            if (param == null)
+                return string.Empty;
+
+            var query = param
+                .Where(x => x.Value != null)
+                .Select(x => EscapeQueryString(x.Key) + '=' + EscapeQueryString(x.Value));
+
+            return string.Join("&", query);
+        }
+
+        // .NET 4.5+: Reserved characters のうち、Uriクラスによってエスケープ強制解除されてしまうものも最初から Unreserved として扱う
+        private static readonly HashSet<char> UnreservedChars =
+            new HashSet<char>("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-_.~!'()*:");
+
+        /// <summary>
+        /// 2バイト文字も考慮したクエリ用エンコード
+        /// </summary>
+        /// <param name="stringToEncode">エンコードする文字列</param>
+        /// <returns>エンコード結果文字列</returns>
+        public static string EscapeQueryString(string stringToEncode)
+        {
+            var sb = new StringBuilder(stringToEncode.Length * 2);
+
+            foreach (var b in Encoding.UTF8.GetBytes(stringToEncode))
+            {
+                if (UnreservedChars.Contains((char)b))
+                    sb.Append((char)b);
+                else
+                    sb.AppendFormat("%{0:X2}", b);
+            }
+
+            return sb.ToString();
+        }
+
+        /// <summary>
+        /// 指定された範囲の整数を昇順に列挙します
+        /// </summary>
+        /// <remarks>
+        /// start, start + 1, start + 2, ..., end の範囲の数列を生成します
+        /// </remarks>
+        /// <param name="from">数列の先頭の値 (最小値)</param>
+        /// <param name="to">数列の末尾の値 (最大値)</param>
+        /// <returns>整数を列挙する IEnumerable インスタンス</returns>
+        public static IEnumerable<int> CountUp(int from, int to)
+        {
+            if (from > to)
+                return Enumerable.Empty<int>();
+
+            return Enumerable.Range(from, to - from + 1);
+        }
+
+        /// <summary>
+        /// 指定された範囲の整数を降順に列挙します
+        /// </summary>
+        /// <remarks>
+        /// start, start - 1, start - 2, ..., end の範囲の数列を生成します
+        /// </remarks>
+        /// <param name="from">数列の先頭の値 (最大値)</param>
+        /// <param name="to">数列の末尾の値 (最小値)</param>
+        /// <returns>整数を列挙する IEnumerable インスタンス</returns>
+        public static IEnumerable<int> CountDown(int from, int to)
+        {
+            for (var i = from; i >= to; i--)
+                yield return i;
+        }
+
+        public static IEnumerable<int> CircularCountUp(int length, int startIndex)
+        {
+            if (length < 1)
+                throw new ArgumentOutOfRangeException(nameof(length));
+            if (startIndex < 0 || startIndex >= length)
+                throw new ArgumentOutOfRangeException(nameof(startIndex));
+
+            // startindex ... 末尾
+            var indices = MyCommon.CountUp(startIndex, length - 1);
+
+            // 先頭 ... (startIndex - 1)
+            if (startIndex != 0)
+                indices = indices.Concat(MyCommon.CountUp(0, startIndex - 1));
+
+            return indices;
+        }
+
+        public static IEnumerable<int> CircularCountDown(int length, int startIndex)
+        {
+            if (length < 1)
+                throw new ArgumentOutOfRangeException(nameof(length));
+            if (startIndex < 0 || startIndex >= length)
+                throw new ArgumentOutOfRangeException(nameof(startIndex));
+
+            // startIndex ... 先頭
+            var indices = MyCommon.CountDown(startIndex, 0);
+
+            // 末尾 ... (startIndex + 1)
+            if (startIndex != length - 1)
+                indices = indices.Concat(MyCommon.CountDown(length - 1, startIndex + 1));
+
+            return indices;
+        }
+
+        /// <summary>
+        /// 2バイト文字も考慮したUrlエンコード
+        /// </summary>
+        /// <param name="stringToEncode">エンコードする文字列</param>
+        /// <returns>エンコード結果文字列</returns>
+        public static string UrlEncode(string stringToEncode)
+        {
+            const string UnreservedChars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-_.~";
+            StringBuilder sb = new StringBuilder();
+            byte[] bytes = Encoding.UTF8.GetBytes(stringToEncode);
+
+            foreach (byte b in bytes)
+            {
+                if (UnreservedChars.IndexOf((char)b) != -1)
+                    sb.Append((char)b);
+                else
+                    sb.AppendFormat("%{0:X2}", b);
+            }
+            return sb.ToString();
         }
     }
 }