aboutsummaryrefslogtreecommitdiff
path: root/MediaBrowser.ApiInteraction.Portable/ApiClient.cs
blob: b41572cd36435c908eb3632443eaaf0ca203efab (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
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
using MediaBrowser.Model.Authentication;
using MediaBrowser.Model.Configuration;
using MediaBrowser.Model.DTO;
using MediaBrowser.Model.Weather;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;

namespace MediaBrowser.ApiInteraction.Portable
{
    public class ApiClient : BaseApiClient
    {
        private HttpWebRequest GetNewRequest(string url)
        {
            return HttpWebRequest.CreateHttp(url);
        }

        /// <summary>
        /// Gets an image stream based on a url
        /// </summary>
        public void GetImageStreamAsync(string url, Action<Stream> callback)
        {
            GetStreamAsync(url, callback);
        }

        /// <summary>
        /// Gets an image stream based on a url
        /// </summary>
        private void GetStreamAsync(string url, Action<Stream> callback)
        {
            HttpWebRequest request = GetNewRequest(url);

            request.BeginGetResponse(new AsyncCallback(result =>
            {
                using (WebResponse response = (result.AsyncState as HttpWebRequest).EndGetResponse(result))
                {
                    Stream stream = response.GetResponseStream();
                    callback(stream);
                }

            }), request);
        }

        /// <summary>
        /// Gets a BaseItem
        /// </summary>
        public void GetItemAsync(Guid id, Guid userId, Action<DTOBaseItem> callback)
        {
            string url = ApiUrl + "/item?userId=" + userId.ToString();

            if (id != Guid.Empty)
            {
                url += "&id=" + id.ToString();
            }

            GetDataAsync(url, callback);
        }

        /// <summary>
        /// Gets all users
        /// </summary>
        public void GetAllUsersAsync(Action<DTOUser[]> callback)
        {
            string url = ApiUrl + "/users";

            GetDataAsync(url, callback);
        }

        /// <summary>
        /// Gets all Genres
        /// </summary>
        public void GetAllGenresAsync(Guid userId, Action<IBNItem[]> callback)
        {
            string url = ApiUrl + "/genres?userId=" + userId.ToString();

            GetDataAsync(url, callback);
        }

        /// <summary>
        /// Gets in-progress items
        /// </summary>
        /// <param name="userId">The user id.</param>
        /// <param name="folderId">(Optional) Specify a folder Id to localize the search to a specific folder.</param>
        public void GetInProgressItemsItemsAsync(Guid userId, Action<DTOBaseItem[]> callback, Guid? folderId = null)
        {
            string url = ApiUrl + "/itemlist?listtype=inprogressitems&userId=" + userId.ToString();

            if (folderId.HasValue)
            {
                url += "&id=" + folderId.ToString();
            }

            GetDataAsync(url, callback);
        }

        /// <summary>
        /// Gets recently added items
        /// </summary>
        /// <param name="userId">The user id.</param>
        /// <param name="folderId">(Optional) Specify a folder Id to localize the search to a specific folder.</param>
        public void GetRecentlyAddedItemsAsync(Guid userId, Action<DTOBaseItem[]> callback, Guid? folderId = null)
        {
            string url = ApiUrl + "/itemlist?listtype=recentlyaddeditems&userId=" + userId.ToString();

            if (folderId.HasValue)
            {
                url += "&id=" + folderId.ToString();
            }

            GetDataAsync(url, callback);
        }

        /// <summary>
        /// Gets favorite items
        /// </summary>
        /// <param name="userId">The user id.</param>
        /// <param name="folderId">(Optional) Specify a folder Id to localize the search to a specific folder.</param>
        public void GetFavoriteItemsAsync(Guid userId, Action<DTOBaseItem[]> callback, Guid? folderId = null)
        {
            string url = ApiUrl + "/itemlist?listtype=favorites&userId=" + userId.ToString();

            if (folderId.HasValue)
            {
                url += "&id=" + folderId.ToString();
            }

            GetDataAsync(url, callback);
        }

        /// <summary>
        /// Gets recently added items that are unplayed.
        /// </summary>
        /// <param name="userId">The user id.</param>
        /// <param name="folderId">(Optional) Specify a folder Id to localize the search to a specific folder.</param>
        public void GetRecentlyAddedUnplayedItemsAsync(Guid userId, Action<DTOBaseItem[]> callback, Guid? folderId = null)
        {
            string url = ApiUrl + "/itemlist?listtype=recentlyaddedunplayeditems&userId=" + userId.ToString();

            if (folderId.HasValue)
            {
                url += "&id=" + folderId.ToString();
            }

            GetDataAsync(url, callback);
        }

        /// <summary>
        /// Gets all Years
        /// </summary>
        public void GetAllYearsAsync(Guid userId, Action<IBNItem[]> callback)
        {
            string url = ApiUrl + "/years?userId=" + userId.ToString();

            GetDataAsync(url, callback);
        }

        /// <summary>
        /// Gets all items that contain a given Year
        /// </summary>
        public void GetItemsWithYearAsync(string name, Guid userId, Action<DTOBaseItem[]> callback, Guid? folderId = null)
        {
            string url = ApiUrl + "/itemlist?listtype=itemswithyear&userId=" + userId.ToString() + "&name=" + name;

            if (folderId.HasValue)
            {
                url += "&id=" + folderId.ToString();
            }

            GetDataAsync(url, callback);
        }

        /// <summary>
        /// Gets all items that contain a given Genre
        /// </summary>
        public void GetItemsWithGenreAsync(string name, Guid userId, Action<DTOBaseItem[]> callback, Guid? folderId = null)
        {
            string url = ApiUrl + "/itemlist?listtype=itemswithgenre&userId=" + userId.ToString() + "&name=" + name;

            if (folderId.HasValue)
            {
                url += "&id=" + folderId.ToString();
            }

            GetDataAsync(url, callback);
        }

        /// <summary>
        /// Gets all items that contain a given Person
        /// </summary>
        public void GetItemsWithPersonAsync(string name, Guid userId, Action<DTOBaseItem[]> callback, Guid? folderId = null)
        {
            string url = ApiUrl + "/itemlist?listtype=itemswithperson&userId=" + userId.ToString() + "&name=" + name;

            if (folderId.HasValue)
            {
                url += "&id=" + folderId.ToString();
            }
            
            GetDataAsync(url, callback);
        }

        /// <summary>
        /// Gets all items that contain a given Person
        /// </summary>
        public void GetItemsWithPersonAsync(string name, string personType, Guid userId, Action<DTOBaseItem[]> callback, Guid? folderId = null)
        {
            string url = ApiUrl + "/itemlist?listtype=itemswithperson&userId=" + userId.ToString() + "&name=" + name;

            if (folderId.HasValue)
            {
                url += "&id=" + folderId.ToString();
            }
            
            url += "&persontype=" + personType;

            GetDataAsync(url, callback);
        }

        /// <summary>
        /// Gets all studious
        /// </summary>
        public void GetAllStudiosAsync(Guid userId, Action<IBNItem[]> callback)
        {
            string url = ApiUrl + "/studios?userId=" + userId.ToString();

            GetDataAsync(url, callback);
        }

        /// <summary>
        /// Gets all items that contain a given Studio
        /// </summary>
        public void GetItemsWithStudioAsync(string name, Guid userId, Action<DTOBaseItem[]> callback, Guid? folderId = null)
        {
            string url = ApiUrl + "/itemlist?listtype=itemswithstudio&userId=" + userId.ToString() + "&name=" + name;

            if (folderId.HasValue)
            {
                url += "&id=" + folderId.ToString();
            }

            GetDataAsync(url, callback);
        }

        /// <summary>
        /// Gets a studio
        /// </summary>
        public void GetStudioAsync(Guid userId, string name, Action<IBNItem> callback)
        {
            string url = ApiUrl + "/studio?userId=" + userId.ToString() + "&name=" + name;

            GetDataAsync(url, callback);
        }

        /// <summary>
        /// Gets a genre
        /// </summary>
        public void GetGenreAsync(Guid userId, string name, Action<IBNItem> callback)
        {
            string url = ApiUrl + "/genre?userId=" + userId.ToString() + "&name=" + name;

            GetDataAsync(url, callback);
        }

        /// <summary>
        /// Gets a person
        /// </summary>
        public void GetPersonAsync(Guid userId, string name, Action<IBNItem> callback)
        {
            string url = ApiUrl + "/person?userId=" + userId.ToString() + "&name=" + name;

            GetDataAsync(url, callback);
        }

        /// <summary>
        /// Gets a year
        /// </summary>
        public void GetYearAsync(Guid userId, int year, Action<IBNItem> callback)
        {
            string url = ApiUrl + "/year?userId=" + userId.ToString() + "&year=" + year;

            GetDataAsync(url, callback);
        }

        /// <summary>
        /// Gets a list of plugins installed on the server
        /// </summary>
        public void GetInstalledPluginsAsync(Action<PluginInfo[]> callback)
        {
            string url = ApiUrl + "/plugins";

            GetDataAsync(url, callback);
        }

        /// <summary>
        /// Gets a list of plugins installed on the server
        /// </summary>
        public void GetPluginAssemblyAsync(PluginInfo plugin, Action<Stream> callback)
        {
            string url = ApiUrl + "/pluginassembly?assemblyfilename=" + plugin.AssemblyFileName;

            GetStreamAsync(url, callback);
        }

        /// <summary>
        /// Gets the current server configuration
        /// </summary>
        public void GetServerConfigurationAsync(Action<ServerConfiguration> callback)
        {
            string url = ApiUrl + "/ServerConfiguration";

            GetDataAsync(url, callback);
        }

        /// <summary>
        /// Gets weather information for the default location as set in configuration
        /// </summary>
        public void GetPluginConfigurationAsync(PluginInfo plugin, Type configurationType, Action<object> callback)
        {
            string url = ApiUrl + "/PluginConfiguration?assemblyfilename=" + plugin.AssemblyFileName;

            // At the moment this can't be retrieved in protobuf format
            SerializationFormats format = DataSerializer.CanDeSerializeJsv ? SerializationFormats.Jsv : SerializationFormats.Json;

            GetDataAsync(url, callback, configurationType, format);
        }

        /// <summary>
        /// Gets the default user
        /// </summary>
        public void GetDefaultUserAsync(Action<DTOUser> callback)
        {
            string url = ApiUrl + "/user";

            GetDataAsync(url, callback);
        }

        /// <summary>
        /// Gets a user by id
        /// </summary>
        public void GetUserAsync(Guid id, Action<DTOUser> callback)
        {
            string url = ApiUrl + "/user?id=" + id.ToString();

            GetDataAsync(url, callback);
        }

        /// <summary>
        /// Gets weather information for the default location as set in configuration
        /// </summary>
        public void GetWeatherInfoAsync(Action<WeatherInfo> callback)
        {
            string url = ApiUrl + "/weather";

            GetDataAsync(url, callback);
        }

        /// <summary>
        /// Gets weather information for a specific zip code
        /// </summary>
        public void GetWeatherInfoAsync(string zipCode, Action<WeatherInfo> callback)
        {
            string url = ApiUrl + "/weather?zipcode=" + zipCode;

            GetDataAsync(url, callback);
        }

        /// <summary>
        /// Gets special features for a Movie
        /// </summary>
        public void GetMovieSpecialFeaturesAsync(Guid itemId, Guid userId, Action<DTOBaseItem[]> callback)
        {
            string url = ApiUrl + "/MovieSpecialFeatures?id=" + itemId;
            url += "&userid=" + userId;

            GetDataAsync(url, callback);
        }

        /// <summary>
        /// Authenticates a user and returns the result
        /// </summary>
        public void AuthenticateUserAsync(Guid userId, string password, Action<AuthenticationResult> callback)
        {
            string url = ApiUrl + "/UserAuthentication?dataformat=" + SerializationFormat.ToString();

            Dictionary<string, string> formValues = new Dictionary<string, string>();

            formValues["userid"] = userId.ToString();

            if (!string.IsNullOrEmpty(password))
            {
                formValues["password"] = password;
            }

            PostDataAsync(url, formValues, callback, SerializationFormat);
        }

        /// <summary>
        /// Updates a user's favorite status for an item and returns the updated UserItemData object.
        /// </summary>
        public void UpdateFavoriteStatusAsync(Guid itemId, Guid userId, bool isFavorite, Action<DTOUserItemData> callback)
        {
            string url = ApiUrl + "/favoritestatus?id=" + itemId;

            url += "&userid=" + userId;
            url += "&isfavorite=" + (isFavorite ? "1" : "0");

            GetDataAsync(url, callback);
        }

        /// <summary>
        /// Updates played status for an item
        /// </summary>
        public void UpdatePlayedStatusAsync(Guid itemId, Guid userId, bool wasPlayed, Action<DTOUserItemData> callback)
        {
            string url = ApiUrl + "/PlayedStatus?id=" + itemId;

            url += "&userid=" + userId;
            url += "&played=" + (wasPlayed ? "1" : "0");

            GetDataAsync(url, callback);
        }

        /// <summary>
        /// Clears a user's rating for an item
        /// </summary>
        public void ClearUserItemRatingAsync(Guid itemId, Guid userId, Action<DTOUserItemData> callback)
        {
            string url = ApiUrl + "/UserItemRating?id=" + itemId;

            url += "&userid=" + userId;
            url += "&clear=1";

            GetDataAsync(url, callback);
        }

        /// <summary>
        /// Updates a user's rating for an item, based on likes or dislikes
        /// </summary>
        public void UpdateUserItemRatingAsync(Guid itemId, Guid userId, bool likes, Action<DTOUserItemData> callback)
        {
            string url = ApiUrl + "/UserItemRating?id=" + itemId;

            url += "&userid=" + userId;
            url += "&likes=" + (likes ? "1" : "0");

            GetDataAsync(url, callback);
        }

        /// <summary>
        /// Performs a GET request, and deserializes the response stream to an object of Type T
        /// </summary>
        private void GetDataAsync<T>(string url, Action<T> callback)
            where T : class
        {
            GetDataAsync<T>(url, callback, SerializationFormat);
        }

        /// <summary>
        /// Performs a GET request, and deserializes the response stream to an object of Type T
        /// </summary>
        private void GetDataAsync<T>(string url, Action<T> callback, SerializationFormats serializationFormat)
            where T : class
        {
            if (url.IndexOf('?') == -1)
            {
                url += "?dataformat=" + serializationFormat.ToString();
            }
            else
            {
                url += "&dataformat=" + serializationFormat.ToString();
            }

            HttpWebRequest request = GetNewRequest(url);

            request.BeginGetResponse(new AsyncCallback(result =>
            {
                T value;

                using (WebResponse response = (result.AsyncState as HttpWebRequest).EndGetResponse(result))
                {
                    using (Stream stream = response.GetResponseStream())
                    {
                        value = DeserializeFromStream<T>(stream);
                    }
                }

                callback(value);

            }), request);
        }

        /// <summary>
        /// Performs a GET request, and deserializes the response stream to an object of Type T
        /// </summary>
        private void GetDataAsync(string url, Action<object> callback, Type type, SerializationFormats serializationFormat)
        {
            if (url.IndexOf('?') == -1)
            {
                url += "?dataformat=" + serializationFormat.ToString();
            }
            else
            {
                url += "&dataformat=" + serializationFormat.ToString();
            }

            HttpWebRequest request = GetNewRequest(url);

            request.BeginGetResponse(new AsyncCallback(result =>
            {
                object value;

                using (WebResponse response = (result.AsyncState as HttpWebRequest).EndGetResponse(result))
                {
                    using (Stream stream = response.GetResponseStream())
                    {
                        value = DataSerializer.DeserializeFromStream(stream, serializationFormat, type);
                    }
                }

                callback(value);

            }), request);
        }

        /// <summary>
        /// Performs a POST request, and deserializes the response stream to an object of Type T
        /// </summary>
        private void PostDataAsync<T>(string url, Dictionary<string, string> formValues, Action<T> callback, SerializationFormats serializationFormat)
            where T : class
        {
            if (url.IndexOf('?') == -1)
            {
                url += "?dataformat=" + serializationFormat.ToString();
            }
            else
            {
                url += "&dataformat=" + serializationFormat.ToString();
            }

            HttpWebRequest request = GetNewRequest(url);

            request.Method = "POST";
            request.ContentType = "application/x-www-form-urlencoded";

            // Begin getting request stream
            request.BeginGetRequestStream(new AsyncCallback(beginGetRequestStreamResult =>
            {
                // Once we have the request stream, write the post data
                using (Stream requestStream = request.EndGetRequestStream(beginGetRequestStreamResult))
                {
                    // Construct the body
                    string postBody = string.Join("&", formValues.Keys.Select(s => string.Format("{0}={1}", s, formValues[s])).ToArray());

                    // Convert the string into a byte array. 
                    byte[] byteArray = Encoding.UTF8.GetBytes(postBody);

                    // Write to the request stream.
                    requestStream.Write(byteArray, 0, byteArray.Length);
                }

                // Begin getting response stream
                request.BeginGetResponse(new AsyncCallback(result =>
                {
                    // Once we have it, deserialize the data and execute the callback
                    T value;

                    using (WebResponse response = request.EndGetResponse(result))
                    {
                        using (Stream responseStream = response.GetResponseStream())
                        {
                            value = DeserializeFromStream<T>(responseStream);
                        }
                    }

                    callback(value);

                }), null);

            }), null);
        }
    }
}