OSDN Git Service

MapThumbクラスから直接ThumbnailInfoを返すGetThumbnailInfoAsyncメソッドを追加
[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 using OpenTween.Connection;
34
35 namespace OpenTween.Thumbnail.Services
36 {
37     class FoursquareCheckin : IThumbnailService
38     {
39         public static readonly Regex UrlPatternRegex =
40             new Regex(@"^https?://(?:foursquare\.com|www\.swarmapp\.com)/(?:c/|.+?/checkin/)(?<checkin_id>[0-9a-z]+)(?:\?s=(?<signature>[^&]+))?");
41
42         public static readonly string ApiBase = "https://api.foursquare.com/v2";
43
44         protected HttpClient http
45         {
46             get { return this.localHttpClient ?? Networking.Http; }
47         }
48         private readonly HttpClient localHttpClient;
49
50         public FoursquareCheckin()
51             : this(null)
52         {
53         }
54
55         public FoursquareCheckin(HttpClient http)
56         {
57             this.localHttpClient = http;
58         }
59
60         public override async Task<ThumbnailInfo> GetThumbnailInfoAsync(string url, PostClass post, CancellationToken token)
61         {
62             // ツイートに位置情報が付与されている場合は何もしない
63             if (post.PostGeo != null)
64                 return null;
65
66             var match = UrlPatternRegex.Match(url);
67
68             if (!match.Success)
69                 return null;
70
71             var checkinIdGroup = match.Groups["checkin_id"];
72             var signatureGroup = match.Groups["signature"];
73
74             try
75             {
76                 // Foursquare のベニュー情報を取得
77                 // 参照: https://developer.foursquare.com/docs/venues/venues
78
79                 var query = new Dictionary<string, string>
80                 {
81                     ["client_id"] = ApplicationSettings.FoursquareClientId,
82                     ["client_secret"] = ApplicationSettings.FoursquareClientSecret,
83                     ["v"] = "20140419", // https://developer.foursquare.com/overview/versioning
84                 };
85
86                 if (signatureGroup.Success)
87                     query["signature"] = signatureGroup.Value;
88
89                 var apiUrl = new Uri(ApiBase + "/checkins/" + checkinIdGroup.Value + "?" + MyCommon.BuildQueryString(query));
90
91                 using (var response = await this.http.GetAsync(apiUrl, token).ConfigureAwait(false))
92                 {
93                     response.EnsureSuccessStatusCode();
94
95                     var jsonBytes = await response.Content.ReadAsByteArrayAsync()
96                         .ConfigureAwait(false);
97
98                     var location = ParseIntoLocation(jsonBytes);
99                     if (location == null)
100                         return null;
101
102                     var map = MapThumb.GetDefaultInstance();
103
104                     return await map.GetThumbnailInfoAsync(new PostClass.StatusGeo(location.Longitude, location.Latitude))
105                         .ConfigureAwait(false);
106                 }
107             }
108             catch (HttpRequestException) { }
109
110             return null;
111         }
112
113         internal static GlobalLocation ParseIntoLocation(byte[] jsonBytes)
114         {
115             using (var jsonReader = JsonReaderWriterFactory.CreateJsonReader(jsonBytes, XmlDictionaryReaderQuotas.Max))
116             {
117                 var xElm = XElement.Load(jsonReader);
118
119                 var locationElm = xElm.XPathSelectElement("/response/checkin/venue/location");
120
121                 // 座標が得られなかった場合
122                 if (locationElm == null)
123                     return null;
124
125                 // 月など、地球以外の星の座標である場合
126                 var planetElm = locationElm.Element("planet");
127                 if (planetElm != null && planetElm.Value != "earth")
128                     return null;
129
130                 return new GlobalLocation
131                 {
132                     Latitude = double.Parse(locationElm.Element("lat").Value),
133                     Longitude = double.Parse(locationElm.Element("lng").Value),
134                 };
135             }
136         }
137     }
138 }