summaryrefslogtreecommitdiff
path: root/src/Libraries/Lastfm/Lastfm/LastfmRequest.cs
blob: b59cfcf33f36524b91f15dc4a60e5108b180799e (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
//
// LastfmRequest.cs
//
// Authors:
//   Bertrand Lorentz <bertrand.lorentz@gmail.com>
//   Phil Trimble <philtrimble@gmail.com>
//
// Copyright (C) 2009 Bertrand Lorentz
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//

using System;
using System.Collections.Generic;
using System.IO;
using System.Net;
using System.Text;
using System.Text.RegularExpressions;
using System.Web;

using Hyena;
using Hyena.Json;

namespace Lastfm
{
    public enum RequestType {
        Read,
        SessionRequest, // Needs the signature, but we don't have the session key yet
        AuthenticatedRead,
        Write
    }

    public enum ResponseFormat {
        Json,
        Raw
    }

    public delegate void SendRequestHandler ();

    internal class WebRequestCreator : IWebRequestCreate
    {
        public WebRequest Create (Uri uri)
        {
            return (HttpWebRequest) HttpWebRequest.Create (uri);
        }
    }

    public class LastfmRequest
    {
        private const string API_ROOT = "http://ws.audioscrobbler.com/2.0/";

        private Dictionary<string, string> parameters = new Dictionary<string, string> ();
        private Stream response_stream;
        private string response_string;
        IWebRequestCreate web_request_creator;

        public LastfmRequest ()
        {}

        internal LastfmRequest (string method, RequestType request_type, ResponseFormat response_format, IWebRequestCreate web_request_creator)
            : this (method, request_type, response_format)
        {
            this.web_request_creator = web_request_creator;
        }

        public LastfmRequest (string method) : this (method, RequestType.Read, ResponseFormat.Json)
        {}

        public LastfmRequest (string method, RequestType request_type, ResponseFormat response_format)
        {
            this.method = method;
            this.request_type = request_type;
            this.response_format = response_format;
            if (this.web_request_creator == null) {
                this.web_request_creator = new WebRequestCreator ();
            }
        }

        private string method;

        private RequestType request_type;

        private ResponseFormat response_format;


        public void AddParameter (string param_name, string param_value)
        {
            parameters.Add (param_name, param_value);
        }

        public Stream GetResponseStream ()
        {
            return response_stream;
        }

        public void Send ()
        {
            if (method == null) {
                throw new InvalidOperationException ("The method name should be set");
            }

            if (response_format == ResponseFormat.Json) {
                AddParameter ("format", "json");
            } else if (response_format == ResponseFormat.Raw) {
                AddParameter ("raw", "true");
            }

            if (request_type == RequestType.Write) {
                response_stream = Post (API_ROOT, BuildPostData ());
            } else {
                response_stream = Get (BuildGetUrl ());
            }
        }

        public JsonObject GetResponseObject ()
        {
            if (response_stream == null) {
                return null;
            }

            SetResponseString ();

            Deserializer deserializer = new Deserializer (response_string);
            object obj = deserializer.Deserialize ();
            JsonObject json_obj = obj as Hyena.Json.JsonObject;

            if (json_obj == null) {
                throw new ApplicationException ("Lastfm invalid response : not a JSON object");
            }

            return json_obj;
        }

        public IAsyncResult BeginSend (AsyncCallback callback)
        {
            return BeginSend (callback, null);
        }

        private SendRequestHandler send_handler;
        public IAsyncResult BeginSend (AsyncCallback callback, object context)
        {
            send_handler = new SendRequestHandler (Send);

            return send_handler.BeginInvoke (callback, context);
        }

        public void EndSend (IAsyncResult result)
        {
            send_handler.EndInvoke (result);
        }

        public StationError GetError ()
        {
            StationError error = StationError.None;

            SetResponseString ();

            if (response_string == null) {
                return StationError.Unknown;
            }

            if (response_string.Contains ("<lfm status=\"failed\">")) {
                // XML reply indicates an error
                Match match = Regex.Match (response_string, "<error code=\"(\\d+)\">");
                if (match.Success) {
                    error = (StationError) Int32.Parse (match.Value);
                    Log.WarningFormat ("Lastfm error {0}", error);
                } else {
                    error = StationError.Unknown;
                }
            }
            if (response_format == ResponseFormat.Json && response_string.Contains ("\"error\":")) {
                // JSON reply indicates an error
                Deserializer deserializer = new Deserializer (response_string);
                JsonObject json = deserializer.Deserialize () as JsonObject;
                if (json != null && json.ContainsKey ("error")) {
                    error = (StationError) json["error"];
                    Log.WarningFormat ("Lastfm error {0} : {1}", error, (string)json["message"]);
                }
            }

            return error;
        }

        private string BuildGetUrl ()
        {
            if (request_type == RequestType.AuthenticatedRead) {
                parameters.Add ("sk", LastfmCore.Account.SessionKey);
            }

            StringBuilder url = new StringBuilder (API_ROOT);
            url.AppendFormat ("?method={0}", method);
            url.AppendFormat ("&api_key={0}", LastfmCore.ApiKey);
            foreach (KeyValuePair<string, string> param in parameters) {
                url.AppendFormat ("&{0}={1}", param.Key, Uri.EscapeDataString (param.Value));
            }
            if (request_type == RequestType.AuthenticatedRead || request_type == RequestType.SessionRequest) {
                url.AppendFormat ("&api_sig={0}", GetSignature ());
            }

            return url.ToString ();
        }

        private string BuildPostData ()
        {
            parameters.Add ("sk", LastfmCore.Account.SessionKey);

            StringBuilder data = new StringBuilder ();
            data.AppendFormat ("method={0}", method);
            data.AppendFormat ("&api_key={0}", LastfmCore.ApiKey);

            foreach (KeyValuePair<string, string> param in parameters) {
                data.AppendFormat ("&{0}={1}",
                                   param.Key, param.Value != null ? Uri.EscapeDataString (param.Value) : null);
            }

            data.AppendFormat ("&api_sig={0}", GetSignature ());

            return data.ToString ();
        }

        private string GetSignature ()
        {
            // We need to have trackNumber[0] before track[0], so we use StringComparer.Ordinal
            var sorted_params = new SortedDictionary<string, string> (parameters, StringComparer.Ordinal);

            if (!sorted_params.ContainsKey ("api_key")) {
                sorted_params.Add ("api_key", LastfmCore.ApiKey);
            }
            if (!sorted_params.ContainsKey ("method")) {
                sorted_params.Add ("method", method);
            }
            StringBuilder signature = new StringBuilder ();
            foreach (var parm in sorted_params) {
                if (parm.Key.Equals ("format")) {
                    continue;
                }
                signature.Append (parm.Key);
                signature.Append (parm.Value);
            }
            signature.Append (LastfmCore.ApiSecret);

            return Hyena.CryptoUtil.Md5Encode (signature.ToString (), Encoding.UTF8);
        }

        public override string ToString ()
        {
            StringBuilder sb = new StringBuilder ();

            sb.Append (method);
            foreach (KeyValuePair<string, string> param in parameters) {
                sb.AppendFormat ("\n\t{0}={1}", param.Key, param.Value);
            }
            return sb.ToString ();
        }

        private void SetResponseString ()
        {
            if (response_string == null && response_stream != null) {
                using (StreamReader sr = new StreamReader (response_stream)) {
                    response_string = sr.ReadToEnd ();
                }
            }
        }

#region HTTP helpers

        private Stream Get (string uri)
        {
            return Get (uri, null);
        }

        private Stream Get (string uri, string accept)
        {
            var request = (HttpWebRequest)web_request_creator.Create (new Uri (uri));
            if (accept != null) {
                request.Accept = accept;
            }
            request.UserAgent = LastfmCore.UserAgent;
            request.Timeout = 10000;
            request.KeepAlive = false;
            request.AllowAutoRedirect = true;

            HttpWebResponse response = null;
            try {
                response = (HttpWebResponse) request.GetResponse ();
            } catch (WebException e) {
                Log.DebugException (e);
                response = (HttpWebResponse)e.Response;
            }
            return response != null ? response.GetResponseStream () : null;
        }

        private Stream Post (string uri, string data)
        {
            // Do not trust docs : it doesn't work if parameters are in the request body
            var request = (HttpWebRequest)web_request_creator.Create (new Uri (String.Concat (uri, "?", data)));
            request.UserAgent = LastfmCore.UserAgent;
            request.Timeout = 10000;
            request.Method = "POST";
            request.KeepAlive = false;
            request.ContentType = "application/x-www-form-urlencoded";

            HttpWebResponse response = null;
            try {
                response = (HttpWebResponse) request.GetResponse ();
            } catch (WebException e) {
                Log.DebugException (e);
                response = (HttpWebResponse)e.Response;
            }
            return response != null ? response.GetResponseStream () : null;
        }

#endregion
    }
}