OSDN Git Service

HttpTwitter.SendDirectMessageメソッドをTwitterApiクラスに置き換え
[opentween/open-tween.git] / OpenTween / Connection / yfrog.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.Threading.Tasks;
34 using System.Xml;
35 using System.Xml.Linq;
36 using System.Xml.XPath;
37 using OpenTween.Api.DataModel;
38
39 namespace OpenTween.Connection
40 {
41     public class yfrog : IMediaUploadService
42     {
43         private readonly string[] pictureExt = new[] { ".jpg", ".jpeg", ".gif", ".png" };
44         private readonly long MaxFileSize = 5L * 1024 * 1024;
45
46         private readonly Twitter tw;
47         private readonly YfrogApi yfrogApi;
48
49         private TwitterConfiguration twitterConfig;
50
51         public yfrog(Twitter twitter, TwitterConfiguration twitterConfig)
52         {
53             this.tw = twitter;
54             this.twitterConfig = twitterConfig;
55
56             this.yfrogApi = new YfrogApi(twitter.AccessToken, twitter.AccessTokenSecret);
57         }
58
59         public int MaxMediaCount
60         {
61             get { return 1; }
62         }
63
64         public string SupportedFormatsStrForDialog
65         {
66             get
67             {
68                 return "Image Files(*.gif;*.jpg;*.jpeg;*.png)|*.gif;*.jpg;*.jpeg;*.png";
69             }
70         }
71
72         public bool CheckFileExtension(string fileExtension)
73         {
74             return this.pictureExt.Contains(fileExtension.ToLowerInvariant());
75         }
76
77         public bool CheckFileSize(string fileExtension, long fileSize)
78         {
79             var maxFileSize = this.GetMaxFileSize(fileExtension);
80             return maxFileSize == null || fileSize <= maxFileSize.Value;
81         }
82
83         public long? GetMaxFileSize(string fileExtension)
84         {
85             return MaxFileSize;
86         }
87
88         public async Task PostStatusAsync(string text, long? inReplyToStatusId, IMediaItem[] mediaItems)
89         {
90             if (mediaItems == null)
91                 throw new ArgumentNullException(nameof(mediaItems));
92
93             if (mediaItems.Length != 1)
94                 throw new ArgumentOutOfRangeException(nameof(mediaItems));
95
96             var item = mediaItems[0];
97
98             if (item == null)
99                 throw new ArgumentException("Err:Media not specified.");
100
101             if (!item.Exists)
102                 throw new ArgumentException("Err:Media not found.");
103
104             var xml = await this.yfrogApi.UploadFileAsync(item, text)
105                 .ConfigureAwait(false);
106
107             var imageUrlElm = xml.XPathSelectElement("/rsp/mediaurl");
108             if (imageUrlElm == null)
109                 throw new WebApiException("Invalid API response", xml.ToString());
110
111             var textWithImageUrl = text + " " + imageUrlElm.Value.Trim();
112
113             await this.tw.PostStatus(textWithImageUrl, inReplyToStatusId)
114                 .ConfigureAwait(false);
115         }
116
117         public int GetReservedTextLength(int mediaCount)
118         {
119             return this.twitterConfig.ShortUrlLength;
120         }
121
122         public void UpdateTwitterConfiguration(TwitterConfiguration config)
123         {
124             this.twitterConfig = config;
125         }
126
127         public class YfrogApi : HttpConnectionOAuthEcho
128         {
129             private static readonly Uri UploadEndpoint = new Uri("https://yfrog.com/api/xauth_upload");
130
131             public YfrogApi(string twitterAccessToken, string twitterAccessTokenSecret)
132                 : base(new Uri("http://api.twitter.com/"), new Uri("https://api.twitter.com/1.1/account/verify_credentials.xml"))
133             {
134                 this.Initialize(ApplicationSettings.TwitterConsumerKey, ApplicationSettings.TwitterConsumerSecret,
135                     twitterAccessToken, twitterAccessTokenSecret, "", "");
136
137                 this.InstanceTimeout = 60000;
138             }
139
140             /// <summary>
141             /// 画像のアップロードを行います
142             /// </summary>
143             /// <exception cref="WebApiException"/>
144             /// <exception cref="XmlException"/>
145             public async Task<XDocument> UploadFileAsync(IMediaItem item, string message)
146             {
147                 // 参照: http://twitter.yfrog.com/page/api#a1
148
149                 var param = new Dictionary<string, string>
150                 {
151                     ["key"] = ApplicationSettings.YfrogApiKey,
152                 };
153                 var paramFiles = new List<KeyValuePair<string, IMediaItem>>
154                 {
155                     new KeyValuePair<string, IMediaItem>("media", item),
156                 };
157                 var response = "";
158
159                 var uploadTask = Task.Run(() => this.GetContent(HttpConnection.PostMethod,
160                     UploadEndpoint, param, paramFiles, ref response, null, null));
161
162                 var ret = await uploadTask.ConfigureAwait(false);
163
164                 if (ret != HttpStatusCode.OK)
165                     throw new WebApiException("Err:" + ret, response);
166
167                 return XDocument.Parse(response);
168             }
169         }
170     }
171 }