OSDN Git Service

冗長な記述を削除 (不要な .ToString(), 括弧など)
[opentween/open-tween.git] / OpenTween / Connection / imgly.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      spinor (@tplantd) <http://d.hatena.ne.jp/spinor/>
8 //           (c) 2014      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.IO;
31 using System.Linq;
32 using System.Net;
33 using System.Net.Http;
34 using System.Threading.Tasks;
35 using System.Xml;
36 using System.Xml.Linq;
37 using System.Xml.XPath;
38 using OpenTween.Api;
39 using OpenTween.Api.DataModel;
40
41 namespace OpenTween.Connection
42 {
43     public class imgly : IMediaUploadService
44     {
45         private readonly string[] pictureExt = { ".jpg", ".jpeg", ".gif", ".png" };
46         private readonly long MaxFileSize = 4L * 1024 * 1024;
47
48         private readonly Twitter tw;
49         private readonly ImglyApi imglyApi;
50
51         private TwitterConfiguration twitterConfig;
52
53         public imgly(Twitter twitter, TwitterConfiguration twitterConfig)
54         {
55             this.tw = twitter;
56             this.twitterConfig = twitterConfig;
57
58             this.imglyApi = new ImglyApi(twitter.Api);
59         }
60
61         public int MaxMediaCount
62         {
63             get { return 1; }
64         }
65
66         public string SupportedFormatsStrForDialog
67         {
68             get
69             {
70                 return "Image Files(*.gif;*.jpg;*.jpeg;*.png)|*.gif;*.jpg;*.jpeg;*.png";
71             }
72         }
73
74         public bool CanUseAltText => false;
75
76         public bool CheckFileExtension(string fileExtension)
77         {
78             return this.pictureExt.Contains(fileExtension.ToLowerInvariant());
79         }
80
81         public bool CheckFileSize(string fileExtension, long fileSize)
82         {
83             var maxFileSize = this.GetMaxFileSize(fileExtension);
84             return maxFileSize == null || fileSize <= maxFileSize.Value;
85         }
86
87         public long? GetMaxFileSize(string fileExtension)
88         {
89             return MaxFileSize;
90         }
91
92         public async Task PostStatusAsync(string text, long? inReplyToStatusId, IMediaItem[] mediaItems)
93         {
94             if (mediaItems == null)
95                 throw new ArgumentNullException(nameof(mediaItems));
96
97             if (mediaItems.Length != 1)
98                 throw new ArgumentOutOfRangeException(nameof(mediaItems));
99
100             var item = mediaItems[0];
101
102             if (item == null)
103                 throw new ArgumentException("Err:Media not specified.");
104
105             if (!item.Exists)
106                 throw new ArgumentException("Err:Media not found.");
107
108             var xml = await this.imglyApi.UploadFileAsync(item, text)
109                 .ConfigureAwait(false);
110
111             var imageUrlElm = xml.XPathSelectElement("/image/url");
112             if (imageUrlElm == null)
113                 throw new WebApiException("Invalid API response", xml.ToString());
114
115             var textWithImageUrl = text + " " + imageUrlElm.Value.Trim();
116
117             await this.tw.PostStatus(textWithImageUrl, inReplyToStatusId)
118                 .ConfigureAwait(false);
119         }
120
121         public int GetReservedTextLength(int mediaCount)
122         {
123             return this.twitterConfig.ShortUrlLength;
124         }
125
126         public void UpdateTwitterConfiguration(TwitterConfiguration config)
127         {
128             this.twitterConfig = config;
129         }
130
131         public class ImglyApi
132         {
133             private readonly HttpClient http;
134
135             private static readonly Uri UploadEndpoint = new Uri("http://img.ly/api/2/upload.xml");
136
137             private static readonly Uri OAuthRealm = new Uri("http://api.twitter.com/");
138             private static readonly Uri AuthServiceProvider = new Uri("https://api.twitter.com/1.1/account/verify_credentials.json");
139
140             public ImglyApi(TwitterApi twitterApi)
141             {
142                 var handler = twitterApi.CreateOAuthEchoHandler(AuthServiceProvider, OAuthRealm);
143
144                 this.http = Networking.CreateHttpClient(handler);
145                 this.http.Timeout = TimeSpan.FromMinutes(1);
146             }
147
148             /// <summary>
149             /// 画像のアップロードを行います
150             /// </summary>
151             /// <exception cref="WebApiException"/>
152             /// <exception cref="XmlException"/>
153             public async Task<XDocument> UploadFileAsync(IMediaItem item, string message)
154             {
155                 // 参照: http://img.ly/api
156
157                 using (var request = new HttpRequestMessage(HttpMethod.Post, UploadEndpoint))
158                 using (var multipart = new MultipartFormDataContent())
159                 {
160                     request.Content = multipart;
161
162                     using (var messageContent = new StringContent(message))
163                     using (var mediaStream = item.OpenRead())
164                     using (var mediaContent = new StreamContent(mediaStream))
165                     {
166                         multipart.Add(messageContent, "message");
167                         multipart.Add(mediaContent, "media", item.Name);
168
169                         using (var response = await this.http.SendAsync(request).ConfigureAwait(false))
170                         {
171                             var responseText = await response.Content.ReadAsStringAsync()
172                                 .ConfigureAwait(false);
173
174                             if (!response.IsSuccessStatusCode)
175                                 throw new WebApiException(response.StatusCode.ToString(), responseText);
176
177                             return XDocument.Parse(responseText);
178                         }
179                     }
180                 }
181             }
182         }
183     }
184 }