OSDN Git Service

string.IsNullOrEmpty の nullable annotation あり版のメソッドを追加
[opentween/open-tween.git] / OpenTween / TweetFormatter.cs
1 // OpenTween - Client of Twitter
2 // Copyright (c) 2014 kim_upsilon (@kim_upsilon) <https://upsilo.net/~upsilon/>
3 // All rights reserved.
4 //
5 // This file is part of OpenTween.
6 //
7 // This program is free software; you can redistribute it and/or modify it
8 // under the terms of the GNU General Public License as published by the Free
9 // Software Foundation; either version 3 of the License, or (at your option)
10 // any later version.
11 //
12 // This program is distributed in the hope that it will be useful, but
13 // WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
14 // or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
15 // for more details.
16 //
17 // You should have received a copy of the GNU General Public License along
18 // with this program. If not, see <http://www.gnu.org/licenses/>, or write to
19 // the Free Software Foundation, Inc., 51 Franklin Street - Fifth Floor,
20 // Boston, MA 02110-1301, USA.
21
22 #nullable enable
23
24 using System;
25 using System.Collections.Generic;
26 using System.Globalization;
27 using System.Linq;
28 using System.Text;
29 using System.Text.RegularExpressions;
30 using OpenTween.Api.DataModel;
31 using OpenTween.Setting;
32
33 namespace OpenTween
34 {
35     /// <summary>
36     /// ツイートの Entity 情報をもとにリンク化などを施すクラス
37     /// </summary>
38     public static class TweetFormatter
39     {
40         public static string AutoLinkHtml(string text, IEnumerable<TwitterEntity>? entities, bool keepTco = false)
41         {
42             if (entities == null)
43                 entities = Enumerable.Empty<TwitterEntity>();
44
45             var entitiesQuery = entities
46                 .Where(x => x != null)
47                 .Where(x => x.Indices != null && x.Indices.Length == 2);
48
49             return string.Concat(AutoLinkHtmlInternal(text, entitiesQuery, keepTco));
50         }
51
52         private static IEnumerable<string> AutoLinkHtmlInternal(string text, IEnumerable<TwitterEntity> entities, bool keepTco)
53         {
54             var curIndex = 0;
55
56             foreach (var entity in FixEntityIndices(text, entities))
57             {
58                 var startIndex = entity.Indices[0];
59                 var endIndex = entity.Indices[1];
60
61                 if (curIndex > startIndex)
62                     continue; // 区間が重複する不正なエンティティを無視する
63
64                 if (startIndex > endIndex)
65                     continue; // 区間が不正なエンティティを無視する
66
67                 if (startIndex > text.Length || endIndex > text.Length)
68                     continue; // 区間が文字列長を越えている不正なエンティティを無視する
69
70                 if (curIndex != startIndex)
71                     yield return t(e(text.Substring(curIndex, startIndex - curIndex)));
72
73                 var targetText = text.Substring(startIndex, endIndex - startIndex);
74
75                 if (entity is TwitterEntityUrl urlEntity)
76                     yield return FormatUrlEntity(targetText, urlEntity, keepTco);
77                 else if (entity is TwitterEntityHashtag hashtagEntity)
78                     yield return FormatHashtagEntity(targetText, hashtagEntity);
79                 else if (entity is TwitterEntityMention mentionEntity)
80                     yield return FormatMentionEntity(targetText, mentionEntity);
81                 else if (entity is TwitterEntityEmoji emojiEntity)
82                     yield return FormatEmojiEntity(targetText, emojiEntity);
83                 else
84                     yield return t(e(targetText));
85
86                 curIndex = endIndex;
87             }
88
89             if (curIndex != text.Length)
90                 yield return t(e(text.Substring(curIndex)));
91         }
92
93         /// <summary>
94         /// エンティティの Indices をサロゲートペアを考慮して調整します
95         /// </summary>
96         private static IEnumerable<TwitterEntity> FixEntityIndices(string text, IEnumerable<TwitterEntity> entities)
97         {
98             var curIndex = 0;
99             var indexOffset = 0; // サロゲートペアによる indices のズレを表す
100
101             foreach (var entity in entities.OrderBy(x => x.Indices[0]))
102             {
103                 var startIndex = entity.Indices[0];
104                 var endIndex = entity.Indices[1];
105
106                 for (var i = curIndex; i < (startIndex + indexOffset); i++)
107                     if (i + 1 < text.Length && char.IsSurrogatePair(text[i], text[i + 1]))
108                         indexOffset++;
109
110                 startIndex += indexOffset;
111                 curIndex = startIndex;
112
113                 for (var i = curIndex; i < (endIndex + indexOffset); i++)
114                     if (i + 1 < text.Length && char.IsSurrogatePair(text[i], text[i + 1]))
115                         indexOffset++;
116
117                 endIndex += indexOffset;
118                 curIndex = endIndex;
119
120                 entity.Indices[0] = startIndex;
121                 entity.Indices[1] = endIndex;
122
123                 yield return entity;
124             }
125         }
126
127         private static string FormatUrlEntity(string targetText, TwitterEntityUrl entity, bool keepTco)
128         {
129             string expandedUrl;
130
131             // 過去に存在した壊れたエンティティの対策
132             // 参照: https://dev.twitter.com/discussions/12628
133             if (entity.DisplayUrl == null)
134             {
135                 expandedUrl = MyCommon.ConvertToReadableUrl(targetText);
136                 return "<a href=\"" + e(entity.Url) + "\" title=\"" + e(expandedUrl) + "\">" + t(e(targetText)) + "</a>";
137             }
138
139             var linkUrl = entity.Url;
140
141             expandedUrl = keepTco ? linkUrl : MyCommon.ConvertToReadableUrl(entity.ExpandedUrl);
142
143             var mediaEntity = entity as TwitterEntityMedia;
144
145             var titleText = mediaEntity?.AltText ?? expandedUrl;
146
147             // twitter.com へのリンクは t.co を経由せずに直接リンクする (但し pic.twitter.com はそのまま)
148             if (mediaEntity == null)
149             {
150                 if (entity.ExpandedUrl.StartsWith("https://twitter.com/", StringComparison.Ordinal) ||
151                     entity.ExpandedUrl.StartsWith("http://twitter.com/", StringComparison.Ordinal))
152                 {
153                     linkUrl = entity.ExpandedUrl;
154                 }
155             }
156
157             return "<a href=\"" + e(linkUrl) + "\" title=\"" + e(titleText) + "\">" + t(e(entity.DisplayUrl)) + "</a>";
158         }
159
160         private static string FormatHashtagEntity(string targetText, TwitterEntityHashtag entity)
161             => "<a class=\"hashtag\" href=\"https://twitter.com/search?q=%23" + eu(entity.Text) + "\">" + t(e(targetText)) + "</a>";
162
163         private static string FormatMentionEntity(string targetText, TwitterEntityMention entity)
164             => "<a class=\"mention\" href=\"https://twitter.com/" + eu(entity.ScreenName) + "\">" + t(e(targetText)) + "</a>";
165
166         private static string FormatEmojiEntity(string targetText, TwitterEntityEmoji entity)
167         {
168             if (!SettingManager.Local.UseTwemoji)
169                 return t(e(targetText));
170
171             if (MyCommon.IsNullOrEmpty(entity.Url))
172                 return "";
173
174             return "<img class=\"emoji\" src=\"" + e(entity.Url) + "\" alt=\"" + e(entity.Text) + "\" />";
175         }
176
177         // 長いのでエイリアスとして e(...), eu(...), t(...) でエスケープできるようにする
178         private static readonly Func<string, string> e = EscapeHtml;
179         private static readonly Func<string, string> eu = Uri.EscapeDataString;
180         private static readonly Func<string, string> t = FilterText;
181
182         private static string EscapeHtml(string text)
183         {
184             // Twitter API は "<" ">" "&" だけ中途半端にエスケープした状態のテキストを返すため、
185             // これらの文字だけ一旦エスケープを解除する
186             text = text.Replace("&lt;", "<").Replace("&gt;", ">").Replace("&amp;", "&");
187
188             var result = new StringBuilder(100);
189             foreach (var c in text)
190             {
191                 // 「<」「>」「&」「"」「'」についてエスケープ処理を施す
192                 // 参照: http://d.hatena.ne.jp/ockeghem/20070510/1178813849
193                 switch (c)
194                 {
195                     case '<':
196                         result.Append("&lt;");
197                         break;
198                     case '>':
199                         result.Append("&gt;");
200                         break;
201                     case '&':
202                         result.Append("&amp;");
203                         break;
204                     case '"':
205                         result.Append("&quot;");
206                         break;
207                     case '\'':
208                         result.Append("&#39;");
209                         break;
210                     default:
211                         result.Append(c);
212                         break;
213                 }
214             }
215
216             return result.ToString();
217         }
218
219         /// <summary>
220         /// HTML の属性値ではない、通常のテキストに対するフィルタ処理
221         /// </summary>
222         private static string FilterText(string text)
223         {
224             text = text.Replace("\n", "<br>");
225             text = Regex.Replace(text, "  ", " &nbsp;");
226
227             return text;
228         }
229     }
230 }