summaryrefslogtreecommitdiff
path: root/src/Libraries/MusicBrainz/MusicBrainz/MusicBrainzObject.cs
blob: d83261ed1df8ab916950018fe2d2dba995edd61f (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
// MusicBrainzObject.cs
//
// Copyright (c) 2008 Scott Peterson <lunchtimemama@gmail.com>
//
// 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.Collections.ObjectModel;
using System.IO;
using System.Net;
using System.Reflection;
using System.Text;
using System.Threading;
using System.Xml;

namespace MusicBrainz
{
    public abstract class MusicBrainzObject
    {

        #region Private Fields

        static DateTime last_accessed;
        static readonly TimeSpan min_interval = TimeSpan.FromSeconds (1);
        static readonly object server_mutex = new object ();
        static readonly string [] rels_params = new string [] {
            "artist-rels",
            "release-rels",
            "track-rels",
            "label-rels",
            "url-rels"
        };

        bool all_data_loaded;
        bool all_rels_loaded;

        string id;
        byte score;
        ReadOnlyCollection<Relation<Artist>> artist_rels;
        ReadOnlyCollection<Relation<Release>> release_rels;
        ReadOnlyCollection<Relation<Track>> track_rels;
        ReadOnlyCollection<Relation<Label>> label_rels;
        ReadOnlyCollection<UrlRelation> url_rels;

        #endregion

        #region Constructors

        internal MusicBrainzObject (string id, string parameters)
        {
            all_data_loaded = true;
            CreateFromId (id, parameters ?? CreateInc ());
        }

        internal MusicBrainzObject (XmlReader reader, bool all_rels_loaded)
        {
            this.all_rels_loaded = all_rels_loaded;
            CreateFromXml (reader);
        }

        #endregion

        #region Private Methods

        string CreateInc ()
        {
            StringBuilder builder = new StringBuilder ();
            CreateIncCore (builder);
            return builder.ToString ();
        }

        void CreateFromId (string id, string parameters)
        {
            XmlProcessingClosure (
                CreateUrl (UrlExtension, id, parameters),
                delegate (XmlReader reader) {
                    reader.ReadToFollowing ("metadata");
                    reader.Read ();
                    CreateFromXml (reader.ReadSubtree ());
                    reader.Close ();
                }
            );
        }

        void CreateFromXml (XmlReader reader)
        {
            reader.Read ();
            id = reader ["id"];
            byte.TryParse (reader ["ext:score"], out score);
            ProcessAttributes (reader);
            while (reader.Read () && reader.NodeType != XmlNodeType.EndElement) {
                if (reader.Name == "relation-list") {
                    all_rels_loaded = true;
                    switch (reader ["target-type"]) {
                    case "Artist":
                        artist_rels = CreateRelation<Artist> (reader.ReadSubtree ());
                        break;
                    case "Release":
                        release_rels = CreateRelation<Release> (reader.ReadSubtree ());
                        break;
                    case "Track":
                        track_rels = CreateRelation<Track> (reader.ReadSubtree ());
                        break;
                    case "Label":
                        label_rels = CreateRelation<Label> (reader.ReadSubtree ());
                        break;
                    case "Url":
                        url_rels = CreateUrlRelation (reader.ReadSubtree ());
                        break;
                    }
                } else
                    ProcessXml (reader.ReadSubtree ());
            }
            reader.Close ();
        }

        void ProcessXml (XmlReader reader)
        {
            reader.Read ();
            ProcessXmlCore (reader);
            reader.Close ();
        }

        #endregion

        #region Protected

        internal bool AllDataLoaded {
            get { return all_data_loaded; }
        }

        internal bool AllRelsLoaded {
            get { return all_rels_loaded; }
            set { all_rels_loaded = value; }
        }

        internal virtual void CreateIncCore (StringBuilder builder)
        {
            if (!all_rels_loaded)
                AppendIncParameters (builder, rels_params);
        }

        internal static void AppendIncParameters (StringBuilder builder, string parameter)
        {
            builder.Append (builder.Length == 0 ? "&inc=" : "+");
            builder.Append (parameter);
        }

        internal static void AppendIncParameters (StringBuilder builder, string parameter1, string parameter2)
        {
            builder.Append (builder.Length == 0 ? "&inc=" : "+");
            builder.Append (parameter1);
            builder.Append ('+');
            builder.Append (parameter2);
        }

        internal static void AppendIncParameters (StringBuilder builder, string [] parameters)
        {
            foreach (string parameter in parameters)
                AppendIncParameters (builder, parameter);
        }

        internal void LoadMissingData ()
        {
            if (!all_data_loaded) {
                LoadMissingDataCore ();
                all_data_loaded = true;
            }
        }

        internal void LoadMissingDataCore (MusicBrainzObject obj)
        {
            if (!all_rels_loaded) {
                artist_rels = obj.GetArtistRelations ();
                release_rels = obj.GetReleaseRelations ();
                track_rels = obj.GetTrackRelations ();
                label_rels = obj.GetLabelRelations ();
                url_rels = obj.GetUrlRelations ();
            }
        }

        internal T GetPropertyOrNull<T> (ref T field_reference) where T : class
        {
            if (field_reference == null) LoadMissingData ();
            return field_reference;
        }

        internal T GetPropertyOrDefault<T> (ref T? field_reference) where T : struct
        {
            return GetPropertyOrDefault (ref field_reference, default (T));
        }

        internal T GetPropertyOrDefault<T> (ref T? field_reference, T default_value) where T : struct
        {
            if (field_reference == null) LoadMissingData ();
            return field_reference ?? default_value;
        }

        internal ReadOnlyCollection<T> GetPropertyOrNew<T> (ref ReadOnlyCollection<T> field_reference)
        {
            return GetPropertyOrNew (ref field_reference, true);
        }

        internal ReadOnlyCollection<T> GetPropertyOrNew<T> (ref ReadOnlyCollection<T> field_reference, bool condition)
        {
            if (field_reference == null && condition) LoadMissingData ();
            return field_reference ?? new ReadOnlyCollection<T> (new T [0]);
        }

        internal virtual void ProcessXmlCore (XmlReader reader)
        {
            reader.Skip (); // FIXME this is a workaround for Mono bug 334752
        }

        internal virtual void ProcessAttributes (XmlReader reader)
        {
        }

        internal abstract void LoadMissingDataCore ();
        internal abstract string UrlExtension { get; }

        #endregion

        #region Public

        public virtual string Id {
            get { return id; }
        }

        public virtual byte Score {
            get { return score; }
        }

        public virtual ReadOnlyCollection<Relation<Artist>> GetArtistRelations ()
        {
            return GetPropertyOrNew (ref artist_rels, !all_rels_loaded);
        }

        public virtual ReadOnlyCollection<Relation<Release>> GetReleaseRelations ()
        {
            return GetPropertyOrNew (ref release_rels, !all_rels_loaded);
        }

        public virtual ReadOnlyCollection<Relation<Track>> GetTrackRelations ()
        {
            return GetPropertyOrNew (ref track_rels, !all_rels_loaded);
        }

        public virtual ReadOnlyCollection<Relation<Label>> GetLabelRelations ()
        {
            return GetPropertyOrNew (ref label_rels, !all_rels_loaded);
        }

        public virtual ReadOnlyCollection<UrlRelation> GetUrlRelations ()
        {
            return GetPropertyOrNew (ref url_rels, !all_rels_loaded);
        }

        public override bool Equals (object obj)
        {
            return this == obj as MusicBrainzObject;
        }

        public static bool operator ==(MusicBrainzObject obj1, MusicBrainzObject obj2)
        {
            if (Object.ReferenceEquals (obj1, null)) {
                return Object.ReferenceEquals (obj2, null);
            }
            return !Object.ReferenceEquals (obj2, null) && obj1.GetType () == obj2.GetType () && obj1.Id == obj2.Id;
        }

        public static bool operator !=(MusicBrainzObject obj1, MusicBrainzObject obj2)
        {
            return !(obj1 == obj2);
        }

        public override int GetHashCode ()
        {
            return (GetType ().Name + Id).GetHashCode ();
        }

        #endregion

        #region Static

        static ReadOnlyCollection<Relation<T>> CreateRelation<T> (XmlReader reader) where T : MusicBrainzObject
        {
            List<Relation<T>> relations = new List<Relation<T>> ();
            while (reader.ReadToFollowing ("relation")) {
                string type = reader ["type"];
                RelationDirection direction = RelationDirection.Forward;
                string direction_string = reader ["direction"];
                if (direction_string != null && direction_string == "backward")
                    direction = RelationDirection.Backward;
                string begin = reader ["begin"];
                string end = reader ["end"];
                string attributes_string = reader ["attributes"];
                string [] attributes = attributes_string == null
                    ? null : attributes_string.Split (' ');

                reader.Read ();
                relations.Add (new Relation<T> (
                    type,
                    ConstructMusicBrainzObjectFromXml<T> (reader.ReadSubtree ()),
                    direction,
                    begin,
                    end,
                    attributes));
            }
            reader.Close ();
            return relations.AsReadOnly ();
        }

        static ReadOnlyCollection<UrlRelation> CreateUrlRelation (XmlReader reader)
        {
            List<UrlRelation> url_rels = new List<UrlRelation> ();
            while (reader.ReadToDescendant ("relation")) {
                RelationDirection direction = RelationDirection.Forward;
                string direction_string = reader["direction"];
                if (direction_string != null && direction_string == "backward")
                    direction = RelationDirection.Backward;
                string attributes_string = reader["attributes"];
                string[] attributes = attributes_string == null
                    ? null : attributes_string.Split (' ');
                url_rels.Add (new UrlRelation (
                    reader["type"],
                    reader["target"],
                    direction,
                    reader["begin"],
                    reader["end"],
                    attributes));
            }
            return url_rels.AsReadOnly ();
        }

        static string CreateUrl (string url_extension, int limit, int offset, string parameters)
        {
            StringBuilder builder = new StringBuilder ();
            if (limit != 25) {
                builder.Append ("&limit=");
                builder.Append (limit);
            }
            if (offset != 0) {
                builder.Append ("&offset=");
                builder.Append (offset);
            }
            builder.Append (parameters);
            return CreateUrl (url_extension, string.Empty, builder.ToString ());
        }

        static string CreateUrl (string url_extension, string id, string parameters)
        {
            StringBuilder builder = new StringBuilder (
                MusicBrainzService.ServiceUrl.AbsoluteUri.Length + id.Length + parameters.Length + 9);
            builder.Append (MusicBrainzService.ServiceUrl.AbsoluteUri);
            builder.Append (url_extension);
            builder.Append ('/');
            builder.Append (id);
            builder.Append ("?type=xml");
            builder.Append (parameters);
            return builder.ToString ();
        }
        
        static bool? cache_implemented;

        static void XmlProcessingClosure (string url, XmlProcessingDelegate code)
        {
            Monitor.Enter (server_mutex);

            // Don't access the MB server twice within a second
            TimeSpan time = DateTime.Now - last_accessed;
            if (min_interval > time)
                Thread.Sleep ((min_interval - time).Milliseconds);

            var request = WebRequest.Create (url) as HttpWebRequest;
            request.UserAgent = MusicBrainzService.UserAgent;
            if (cache_implemented == null) {
                try {
                    request.CachePolicy = MusicBrainzService.CachePolicy;
                } catch (NotImplementedException) {
                    cache_implemented = false;
                }
            } else if (cache_implemented.Value == true) {
                request.CachePolicy = MusicBrainzService.CachePolicy;
            }

            HttpWebResponse response = null;

            try {
                response = (HttpWebResponse)request.GetResponse ();
            } catch (WebException e) {
                response = (HttpWebResponse)e.Response;
            }

            if (response == null) throw new MusicBrainzNotFoundException ();

            switch (response.StatusCode) {
            case HttpStatusCode.BadRequest:
                Monitor.Exit (server_mutex);
                throw new MusicBrainzInvalidParameterException ();
            case HttpStatusCode.Unauthorized:
                Monitor.Exit (server_mutex);
                throw new MusicBrainzUnauthorizedException ();
            case HttpStatusCode.NotFound:
                Monitor.Exit (server_mutex);
                throw new MusicBrainzNotFoundException ();
            }

            bool from_cache;
            if (cache_implemented == null) {
                try {
                    from_cache = response.IsFromCache;
                    cache_implemented = true;
                } catch (NotImplementedException) {
                    from_cache = false;
                    cache_implemented = false;
                }
            } else if (cache_implemented.Value) {
                from_cache = response.IsFromCache;
            } else {
                from_cache = false;
            }

            if (from_cache) Monitor.Exit (server_mutex);

            MusicBrainzService.OnXmlRequest (url, from_cache);

            code (new XmlTextReader (response.GetResponseStream ()));
            response.Close ();

            if (!from_cache) {
                last_accessed = DateTime.Now;
                Monitor.Exit (server_mutex);
            }
        }

        #endregion

        #region Query

        internal static string CreateLuceneParameter (string query)
        {
            StringBuilder builder = new StringBuilder (query.Length + 7);
            builder.Append ("&query=");
            Utils.PercentEncode (builder, query);
            return builder.ToString ();
        }

        internal static List<T> Query<T> (string url_extension,
                                          int limit, int offset,
                                          string parameters,
                                          out int? count) where T : MusicBrainzObject
        {
            int count_value = 0;
            List<T> results = new List<T> ();
            XmlProcessingClosure (
                CreateUrl (url_extension, limit, offset, parameters),
                delegate (XmlReader reader) {
                    reader.ReadToFollowing ("metadata");
                    reader.Read ();
                    int.TryParse (reader ["count"], out count_value);
                    while (reader.Read () && reader.NodeType == XmlNodeType.Element)
                        results.Add (ConstructMusicBrainzObjectFromXml<T> (reader.ReadSubtree ()));
                    reader.Close ();
                }
            );
            count = count_value == 0 ? results.Count : count_value;
            return results;
        }

        static T ConstructMusicBrainzObjectFromXml<T> (XmlReader reader) where T : MusicBrainzObject
        {
            ConstructorInfo constructor = typeof (T).GetConstructor (
                BindingFlags.NonPublic | BindingFlags.Instance,
                null,
                new Type [] { typeof (XmlReader) },
                null);
            return (T)constructor.Invoke (new object [] {reader});
        }

        #endregion

    }

    internal delegate void XmlProcessingDelegate (XmlReader reader);
}