OSDN Git Service

画像共有サービスに使用するインタフェースを設計し直し
[opentween/open-tween.git] / OpenTween / Connection / TwitPic.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;
38
39 namespace OpenTween.Connection
40 {
41     public class TwitPic : IMediaUploadService
42     {
43         private readonly string[] pictureExt = new[] { ".jpg", ".jpeg", ".gif", ".png" };
44
45         private readonly string[] multimediaExt = new[] { ".avi", ".wmv", ".flv", ".m4v", ".mov", ".mp4", ".rm", ".mpeg", ".mpg", ".3gp", ".3g2" };
46
47         private readonly long MaxFileSize = 10L * 1024 * 1024; // Image only
48         // Multimedia filesize limit unknown. But length limit is 1:30.
49
50         private readonly Twitter tw;
51         private readonly TwitpicApi twitpicApi;
52
53         private TwitterConfiguration twitterConfig;
54
55         public TwitPic(Twitter twitter, TwitterConfiguration twitterConfig)
56         {
57             this.tw = twitter;
58             this.twitterConfig = twitterConfig;
59
60             this.twitpicApi = new TwitpicApi(twitter.AccessToken, twitter.AccessTokenSecret);
61         }
62
63         public int MaxMediaCount
64         {
65             get { return 1; }
66         }
67
68         public string SupportedFormatsStrForDialog
69         {
70             get
71             {
72                 return "Image Files(*" + string.Join(";*", this.pictureExt) + ")|*" + string.Join(";*", this.pictureExt)
73                     + "|Videos(*" + string.Join(";*", this.multimediaExt) + ")|*" + string.Join(";*", this.multimediaExt);
74             }
75         }
76
77         public bool CheckFileExtension(string fileExtension)
78         {
79             fileExtension = fileExtension.ToLower();
80
81             return this.pictureExt.Contains(fileExtension) ||
82                 this.multimediaExt.Contains(fileExtension);
83         }
84
85         public bool CheckFileSize(string fileExtension, long fileSize)
86         {
87             var maxFileSize = this.GetMaxFileSize(fileExtension);
88             return maxFileSize == null || fileSize <= maxFileSize.Value;
89         }
90
91         public long? GetMaxFileSize(string fileExtension)
92         {
93             if (this.multimediaExt.Contains(fileExtension))
94                 return null; // Multimedia : no check
95
96             return MaxFileSize;
97         }
98
99         public async Task PostStatusAsync(string text, long? inReplyToStatusId, string[] filePaths)
100         {
101             if (filePaths.Length != 1)
102                 throw new ArgumentOutOfRangeException("filePaths");
103
104             var file = new FileInfo(filePaths[0]);
105
106             if (!file.Exists)
107                 throw new ArgumentException("Err:File isn't exists.", "filePaths[0]");
108
109             var xml = await this.twitpicApi.UploadFileAsync(file, text)
110                 .ConfigureAwait(false);
111
112             var imageUrlElm = xml.XPathSelectElement("/image/url");
113             if (imageUrlElm == null)
114                 throw new WebApiException("Invalid API response", xml.ToString());
115
116             var textWithImageUrl = text + " " + imageUrlElm.Value.Trim();
117
118             await Task.Run(() => this.tw.PostStatus(textWithImageUrl, inReplyToStatusId))
119                 .ConfigureAwait(false);
120         }
121
122         public int GetReservedTextLength(int mediaCount)
123         {
124             return this.twitterConfig.ShortUrlLength;
125         }
126
127         public void UpdateTwitterConfiguration(TwitterConfiguration config)
128         {
129             this.twitterConfig = config;
130         }
131
132         public class TwitpicApi : HttpConnectionOAuthEcho
133         {
134             private static readonly Uri UploadEndpoint = new Uri("http://api.twitpic.com/2/upload.xml");
135
136             public TwitpicApi(string twitterAccessToken, string twitterAccessTokenSecret)
137                 : base(new Uri("http://api.twitter.com/"), new Uri("https://api.twitter.com/1.1/account/verify_credentials.json"))
138             {
139                 this.Initialize(ApplicationSettings.TwitterConsumerKey, ApplicationSettings.TwitterConsumerSecret,
140                     twitterAccessToken, twitterAccessTokenSecret, "", "");
141
142                 this.InstanceTimeout = 120000;
143             }
144
145             /// <summary>
146             /// 画像のアップロードを行います
147             /// </summary>
148             /// <exception cref="WebApiException"/>
149             /// <exception cref="XmlException"/>
150             public async Task<XDocument> UploadFileAsync(FileInfo file, string message)
151             {
152                 // 参照: http://dev.twitpic.com/docs/2/upload/
153
154                 var param = new Dictionary<string, string>
155                 {
156                     {"key", ApplicationSettings.TwitpicApiKey},
157                     {"message", message},
158                 };
159                 var paramFiles = new List<KeyValuePair<string, FileInfo>>
160                 {
161                     new KeyValuePair<string, FileInfo>("media", file),
162                 };
163                 var response = "";
164
165                 var uploadTask = Task.Run(() => this.GetContent(HttpConnection.PostMethod,
166                     UploadEndpoint, param, paramFiles, ref response, null, null));
167
168                 var ret = await uploadTask.ConfigureAwait(false);
169
170                 if (ret != HttpStatusCode.OK)
171                     throw new WebApiException("Err:" + ret, response);
172
173                 return XDocument.Parse(response);
174             }
175         }
176     }
177 }