OSDN Git Service

クエリの構築に HttpUtility.ParseQueryString() を使用している箇所を MyCommon.BuildQueryString() に置き換え...
[opentween/open-tween.git] / OpenTween / Thumbnail / Services / FoursquareCheckin.cs
1 // OpenTween - Client of Twitter
2 // Copyright (c) 2012 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 using System;
23 using System.Collections.Generic;
24 using System.Net.Http;
25 using System.Runtime.Serialization.Json;
26 using System.Text.RegularExpressions;
27 using System.Threading;
28 using System.Threading.Tasks;
29 using System.Web;
30 using System.Xml;
31 using System.Xml.Linq;
32 using System.Xml.XPath;
33
34 namespace OpenTween.Thumbnail.Services
35 {
36     class FoursquareCheckin : IThumbnailService
37     {
38         public static readonly Regex UrlPatternRegex =
39             new Regex(@"^https?://foursquare\.com/.+?/checkin/(?<checkin_id>[0-9a-z]+)(?:\?s=(?<signature>[^&]+))?");
40
41         public static readonly string ApiBase = "https://api.foursquare.com/v2";
42
43         protected readonly HttpClient http;
44
45         public FoursquareCheckin(HttpClient http)
46         {
47             this.http = http;
48         }
49
50         public override async Task<ThumbnailInfo> GetThumbnailInfoAsync(string url, PostClass post, CancellationToken token)
51         {
52             // ツイートに位置情報が付与されている場合は何もしない
53             if (post.PostGeo.Lat != 0 || post.PostGeo.Lng != 0)
54                 return null;
55
56             var match = UrlPatternRegex.Match(url);
57
58             if (!match.Success)
59                 return null;
60
61             var checkinIdGroup = match.Groups["checkin_id"];
62             var signatureGroup = match.Groups["signature"];
63
64             try
65             {
66                 // Foursquare のベニュー情報を取得
67                 // 参照: https://developer.foursquare.com/docs/venues/venues
68
69                 var query = new Dictionary<string, string>
70                 {
71                     {"client_id", ApplicationSettings.FoursquareClientId},
72                     {"client_secret", ApplicationSettings.FoursquareClientSecret},
73                     {"v", "20140419"}, // https://developer.foursquare.com/overview/versioning
74                 };
75
76                 if (signatureGroup.Success)
77                     query["signature"] = signatureGroup.Value;
78
79                 var apiUrl = new Uri(ApiBase + "/checkins/" + checkinIdGroup.Value + "?" + MyCommon.BuildQueryString(query));
80
81                 using (var response = await this.http.GetAsync(apiUrl, token).ConfigureAwait(false))
82                 {
83                     response.EnsureSuccessStatusCode();
84
85                     var jsonBytes = await response.Content.ReadAsByteArrayAsync()
86                         .ConfigureAwait(false);
87
88                     var location = ParseIntoLocation(jsonBytes);
89                     if (location == null)
90                         return null;
91
92                     var map = MapThumb.GetDefaultInstance();
93
94                     return new ThumbnailInfo
95                     {
96                         ImageUrl = map.CreateMapLinkUrl(location.Latitude, location.Longitude),
97                         ThumbnailUrl = map.CreateStaticMapUrl(location.Latitude, location.Longitude),
98                         TooltipText = null,
99                     };
100                 }
101             }
102             catch (HttpRequestException) { }
103
104             return null;
105         }
106
107         internal static GlobalLocation ParseIntoLocation(byte[] jsonBytes)
108         {
109             using (var jsonReader = JsonReaderWriterFactory.CreateJsonReader(jsonBytes, XmlDictionaryReaderQuotas.Max))
110             {
111                 var xElm = XElement.Load(jsonReader);
112
113                 var locationElm = xElm.XPathSelectElement("/response/checkin/venue/location");
114
115                 // 座標が得られなかった場合
116                 if (locationElm == null)
117                     return null;
118
119                 // 月など、地球以外の星の座標である場合
120                 var planetElm = locationElm.Element("planet");
121                 if (planetElm != null && planetElm.Value != "earth")
122                     return null;
123
124                 return new GlobalLocation
125                 {
126                     Latitude = double.Parse(locationElm.Element("lat").Value),
127                     Longitude = double.Parse(locationElm.Element("lng").Value),
128                 };
129             }
130         }
131     }
132 }