[banshee] Playlists: (refactoring) more progress towards immutability



commit e4b14cc3a0a94f9f59b828d7880883560d80e5b5
Author: Andrés G. Aragoneses <knocte gmail com>
Date:   Sat Apr 5 20:10:12 2014 +0200

    Playlists: (refactoring) more progress towards immutability
    
    PlaylistParser.Parse() was mutable (the result of its execution was
    available at one of the properties of its instance. This can be
    avoided by making Parse() static, and return the result instead
    of just a bool indicating its success (from now on, a null value
    returned means a failure to parse).
    
    To do this, the PlaylistParser class has to be split in two:
    - static class PlaylistParser
    - DTO class ParsedPlaylist
    
    This doesn't only make the code safer, it allows me to remove
    the lock{} inside Parse() method, and makes everything a bit
    more readable and maintainable.

 .../Banshee.Playlist/PlaylistFileUtil.cs           |    8 +-
 .../Banshee.Playlists.Formats/AsxPlaylistFormat.cs |    4 +-
 .../Banshee.Playlists.Formats/ParsedPlaylist.cs    |   47 ++++++
 .../Banshee.Playlists.Formats/PlaylistParser.cs    |  169 +++++++++-----------
 .../Tests/PlaylistFormatTests.cs                   |   14 +-
 src/Core/Banshee.Services/Banshee.Services.csproj  |    1 +
 .../Banshee.Streaming/RadioTrackInfo.cs            |    6 +-
 src/Core/Banshee.Services/Makefile.am              |    1 +
 8 files changed, 140 insertions(+), 110 deletions(-)
---
diff --git a/src/Core/Banshee.Services/Banshee.Playlist/PlaylistFileUtil.cs 
b/src/Core/Banshee.Services/Banshee.Playlist/PlaylistFileUtil.cs
index ee5005b..05fb9f3 100644
--- a/src/Core/Banshee.Services/Banshee.Playlist/PlaylistFileUtil.cs
+++ b/src/Core/Banshee.Services/Banshee.Playlist/PlaylistFileUtil.cs
@@ -177,10 +177,10 @@ namespace Banshee.Playlist
                     relative_dir = relative_dir + System.IO.Path.DirectorySeparatorChar;
                 }
 
-                var parser = new PlaylistParser (new Uri (relative_dir));
-                if (parser.Parse (uri)) {
+                var parsed_playlist = PlaylistParser.Parse (uri, new Uri (relative_dir));
+                if (parsed_playlist != null) {
                     List<string> uris = new List<string> ();
-                    foreach (PlaylistElement element in parser.Elements) {
+                    foreach (PlaylistElement element in parsed_playlist.Elements) {
                         if (element.Uri.IsFile) {
                             uris.Add (element.Uri.LocalPath);
                         } else {
@@ -211,7 +211,7 @@ namespace Banshee.Playlist
                     // Only import an non-empty playlist
                     if (uris.Count > 0) {
                         ImportPlaylistWorker worker = new ImportPlaylistWorker (
-                            parser.Title,
+                            parsed_playlist.Title,
                             uris.ToArray (), source, importer);
                         worker.Import ();
                     }
diff --git a/src/Core/Banshee.Services/Banshee.Playlists.Formats/AsxPlaylistFormat.cs 
b/src/Core/Banshee.Services/Banshee.Playlists.Formats/AsxPlaylistFormat.cs
index dcaca82..77acd4b 100644
--- a/src/Core/Banshee.Services/Banshee.Playlists.Formats/AsxPlaylistFormat.cs
+++ b/src/Core/Banshee.Services/Banshee.Playlists.Formats/AsxPlaylistFormat.cs
@@ -104,8 +104,8 @@ namespace Banshee.Playlists.Formats
                     case "entryref":
                         string href = xml_reader["HREF"] ?? xml_reader["href"];
                         if (href != null) {
-                            PlaylistParser secondary = new PlaylistParser ();
-                            if (secondary.Parse (new SafeUri (ResolveUri (href)))) {
+                            var secondary = PlaylistParser.Parse (new SafeUri (ResolveUri (href)));
+                            if (secondary != null) {
                                 // splice in Elements of secondary
                                 foreach (PlaylistElement e in secondary.Elements) {
                                     Elements.Add (e);
diff --git a/src/Core/Banshee.Services/Banshee.Playlists.Formats/ParsedPlaylist.cs 
b/src/Core/Banshee.Services/Banshee.Playlists.Formats/ParsedPlaylist.cs
new file mode 100644
index 0000000..53c7d08
--- /dev/null
+++ b/src/Core/Banshee.Services/Banshee.Playlists.Formats/ParsedPlaylist.cs
@@ -0,0 +1,47 @@
+//
+// ParsedPlaylist.cs
+//
+// Authors:
+//   Aaron Bockover <abockover novell com>
+//   Bertrand Lorentz <bertrand lorentz gmail com>
+//   Andrés G. Aragoneses <knocte gmail com>
+//
+// Copyright (C) 2007 Novell, Inc.
+// Copyright (C) 2014 Andrés G. Aragoneses
+//
+// 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.Collections.Generic;
+
+namespace Banshee.Playlists.Formats
+{
+    public class ParsedPlaylist
+    {
+        internal ParsedPlaylist (string title, List<PlaylistElement> elements)
+        {
+            Title = title;
+            Elements = elements;
+        }
+
+        public List<PlaylistElement> Elements { get; private set; }
+        public string Title { get; private set; }
+    }
+}
diff --git a/src/Core/Banshee.Services/Banshee.Playlists.Formats/PlaylistParser.cs 
b/src/Core/Banshee.Services/Banshee.Playlists.Formats/PlaylistParser.cs
index 36996eb..b8f840c 100644
--- a/src/Core/Banshee.Services/Banshee.Playlists.Formats/PlaylistParser.cs
+++ b/src/Core/Banshee.Services/Banshee.Playlists.Formats/PlaylistParser.cs
@@ -4,8 +4,10 @@
 // Authors:
 //   Aaron Bockover <abockover novell com>
 //   Bertrand Lorentz <bertrand lorentz gmail com>
+//   Andrés G. Aragoneses <knocte gmail com>
 //
 // Copyright (C) 2007 Novell, Inc.
+// Copyright (C) 2014 Andrés G. Aragoneses
 //
 // Permission is hereby granted, free of charge, to any person obtaining
 // a copy of this software and associated documentation files (the
@@ -30,13 +32,12 @@
 using System;
 using System.IO;
 using System.Net;
-using System.Collections.Generic;
 
 using Hyena;
 
 namespace Banshee.Playlists.Formats
 {
-    public class PlaylistParser
+    public static class PlaylistParser
     {
         private static PlaylistFormatDescription [] playlist_formats = new PlaylistFormatDescription [] {
             M3uPlaylistFormat.FormatDescription,
@@ -46,111 +47,104 @@ namespace Banshee.Playlists.Formats
             XspfPlaylistFormat.FormatDescription
         };
 
-        private List<PlaylistElement> elements;
-        private Uri base_uri = null;
-        private string title = null;
-        private readonly int HTTP_REQUEST_RETRIES = 3;
+        private static readonly int HTTP_REQUEST_RETRIES = 3;
 
-        public PlaylistParser (Uri baseUri)
+        public static ParsedPlaylist Parse (SafeUri uri)
         {
-            base_uri = baseUri;
+            return Parse (uri, null);
         }
 
-        public PlaylistParser ()
-        {
-            if (Environment.CurrentDirectory.Equals ("/")) {
-                // System.Uri doesn't like / as a value
-                base_uri = new Uri ("file:///");
-            } else {
-                base_uri = new Uri (Environment.CurrentDirectory);
-            }
-        }
-
-        public bool Parse (SafeUri uri)
+        public static ParsedPlaylist Parse (SafeUri uri, Uri baseUri)
         {
             ThreadAssist.AssertNotInMainThread ();
-            lock (this) {
-                elements = null;
-                HttpWebResponse response = null;
-                Stream stream = null;
-                Stream web_stream = null;
-                bool partial_read = false;
-                long saved_position = 0;
-
-                if (uri.Scheme == "file") {
-                    stream = Banshee.IO.File.OpenRead (uri);
-                } else if (uri.Scheme == "http") {
-                    response = Download (uri, HTTP_REQUEST_RETRIES);
-                    web_stream = response.GetResponseStream ();
-                    try {
-                        stream = new MemoryStream ();
-
-                        byte [] buffer = new byte[4096];
-                        int read;
-
-                        // If we haven't read the whole stream and if
-                        // it turns out to be a playlist, we'll read the rest
-                        read = web_stream.Read (buffer, 0, buffer.Length);
-                        stream.Write (buffer, 0, read);
-                        if ((read = web_stream.Read (buffer, 0, buffer.Length)) > 0) {
-                            partial_read = true;
-                            stream.Write (buffer, 0, read);
-                            saved_position = stream.Position;
-                        }
 
-                        stream.Position = 0;
-                    } finally {
-                        if (!partial_read) {
-                            web_stream.Close ();
-                            response.Close ();
-                        }
-                    }
+            if (baseUri == null) {
+                if (Environment.CurrentDirectory.Equals ("/")) {
+                    // System.Uri doesn't like / as a value
+                    baseUri = new Uri ("file:///");
                 } else {
-                    Hyena.Log.DebugFormat ("Not able to parse playlist at {0}", uri);
-                    return false;
+                    baseUri = new Uri (Environment.CurrentDirectory);
                 }
+            }
 
-                PlaylistFormatDescription matching_format = null;
+            HttpWebResponse response = null;
+            Stream stream = null;
+            Stream web_stream = null;
+            bool partial_read = false;
+            long saved_position = 0;
+
+            if (uri.Scheme == "file") {
+                stream = Banshee.IO.File.OpenRead (uri);
+            } else if (uri.Scheme == "http") {
+                response = Download (uri, HTTP_REQUEST_RETRIES);
+                web_stream = response.GetResponseStream ();
+                try {
+                    stream = new MemoryStream ();
 
-                foreach (PlaylistFormatDescription format in playlist_formats) {
-                    stream.Position = 0;
+                    byte [] buffer = new byte[4096];
+                    int read;
 
-                    if (format.MagicHandler (new StreamReader (stream))) {
-                        matching_format = format;
-                        break;
+                    // If we haven't read the whole stream and if
+                    // it turns out to be a playlist, we'll read the rest
+                    read = web_stream.Read (buffer, 0, buffer.Length);
+                    stream.Write (buffer, 0, read);
+                    if ((read = web_stream.Read (buffer, 0, buffer.Length)) > 0) {
+                        partial_read = true;
+                        stream.Write (buffer, 0, read);
+                        saved_position = stream.Position;
                     }
-                }
 
-                if (matching_format == null) {
-                    if (partial_read) {
+                    stream.Position = 0;
+                } finally {
+                    if (!partial_read) {
                         web_stream.Close ();
                         response.Close ();
                     }
-                    return false;
                 }
+            } else {
+                Hyena.Log.DebugFormat ("Not able to parse playlist at {0}", uri);
+                return null;
+            }
+
+            PlaylistFormatDescription matching_format = null;
 
+            foreach (PlaylistFormatDescription format in playlist_formats) {
+                stream.Position = 0;
+
+                if (format.MagicHandler (new StreamReader (stream))) {
+                    matching_format = format;
+                    break;
+                }
+            }
+
+            if (matching_format == null) {
                 if (partial_read) {
-                    try {
-                        stream.Position = saved_position;
-                        Banshee.IO.StreamAssist.Save (web_stream, stream, false);
-                    } finally {
-                        web_stream.Close ();
-                        response.Close ();
-                    }
+                    web_stream.Close ();
+                    response.Close ();
                 }
-                stream.Position = 0;
-                IPlaylistFormat playlist = (IPlaylistFormat)Activator.CreateInstance (matching_format.Type);
-                playlist.BaseUri = base_uri;
-                playlist.Load (stream, false);
-                stream.Dispose ();
-
-                elements = playlist.Elements;
-                Title = playlist.Title ?? Path.GetFileNameWithoutExtension (uri.LocalPath);
-                return true;
+                return null;
             }
+
+            if (partial_read) {
+                try {
+                    stream.Position = saved_position;
+                    Banshee.IO.StreamAssist.Save (web_stream, stream, false);
+                } finally {
+                    web_stream.Close ();
+                    response.Close ();
+                }
+            }
+            stream.Position = 0;
+            IPlaylistFormat playlist = (IPlaylistFormat)Activator.CreateInstance (matching_format.Type);
+            playlist.BaseUri = baseUri;
+            playlist.Load (stream, false);
+            stream.Dispose ();
+
+            var title = playlist.Title ?? Path.GetFileNameWithoutExtension (uri.LocalPath);
+            return new ParsedPlaylist (title, playlist.Elements);
         }
 
-        private HttpWebResponse Download (SafeUri uri, int nb_retries)
+        private static HttpWebResponse Download (SafeUri uri, int nb_retries)
         {
             Hyena.ThreadAssist.AssertNotInMainThread ();
 
@@ -193,14 +187,5 @@ namespace Banshee.Playlists.Formats
                 }
             }
         }
-
-        public List<PlaylistElement> Elements {
-            get { return elements; }
-        }
-
-        public string Title {
-            get { return title; }
-            set { title = value; }
-        }
     }
 }
diff --git a/src/Core/Banshee.Services/Banshee.Playlists.Formats/Tests/PlaylistFormatTests.cs 
b/src/Core/Banshee.Services/Banshee.Playlists.Formats/Tests/PlaylistFormatTests.cs
index 8c297db..0fbfe80 100644
--- a/src/Core/Banshee.Services/Banshee.Playlists.Formats/Tests/PlaylistFormatTests.cs
+++ b/src/Core/Banshee.Services/Banshee.Playlists.Formats/Tests/PlaylistFormatTests.cs
@@ -96,12 +96,10 @@ namespace Banshee.Playlists.Formats.Tests
         [Test]
         public void ReadAsxEntryRef ()
         {
-            var parser = new PlaylistParser (BaseUri);
-
-            parser.Parse (new SafeUri ("http://download.banshee.fm/test/remote.asx";));
+            var parsed_playlist = PlaylistParser.Parse (new SafeUri 
("http://download.banshee.fm/test/remote.asx";), BaseUri);
             IPlaylistFormat plref = LoadPlaylist (new AsxPlaylistFormat (), "entryref.asx");
             Assert.AreEqual (2, plref.Elements.Count);
-            AssertEqual (parser.Elements, plref.Elements);
+            AssertEqual (parsed_playlist.Elements, plref.Elements);
         }
 
         private void AssertEqual (List<PlaylistElement> l1, List<PlaylistElement> l2)
@@ -159,14 +157,12 @@ namespace Banshee.Playlists.Formats.Tests
         [Test]
         public void ReadDetectMagic ()
         {
-            var parser = new PlaylistParser (BaseUri);
-
             foreach (string path in Directory.GetFiles (playlists_dir)) {
-                parser.Parse (new SafeUri (Path.Combine (Environment.CurrentDirectory, path)));
+                PlaylistParser.Parse (new SafeUri (Path.Combine (Environment.CurrentDirectory, path)), 
BaseUri);
             }
 
-            parser.Parse (new SafeUri ("http://download.banshee.fm/test/extended.pls";));
-            AssertTest (parser.Elements, false);
+            var parsed_playlist = PlaylistParser.Parse (new SafeUri 
("http://download.banshee.fm/test/extended.pls";), BaseUri);
+            AssertTest (parsed_playlist.Elements, false);
         }
 
 #endregion
diff --git a/src/Core/Banshee.Services/Banshee.Services.csproj 
b/src/Core/Banshee.Services/Banshee.Services.csproj
index 48d2079..21faa33 100644
--- a/src/Core/Banshee.Services/Banshee.Services.csproj
+++ b/src/Core/Banshee.Services/Banshee.Services.csproj
@@ -321,6 +321,7 @@
     <Compile Include="Banshee.Sources\IBatchScrobblerSource.cs" />
     <Compile Include="Banshee.Playlists.Formats\PlaylistElement.cs" />
     <Compile Include="Banshee.Hardware\FileSystem.cs" />
+    <Compile Include="Banshee.Playlists.Formats\ParsedPlaylist.cs" />
   </ItemGroup>
   <ItemGroup>
     <EmbeddedResource Include="Banshee.Services.addin.xml">
diff --git a/src/Core/Banshee.Services/Banshee.Streaming/RadioTrackInfo.cs 
b/src/Core/Banshee.Services/Banshee.Streaming/RadioTrackInfo.cs
index cb7324d..74aff59 100644
--- a/src/Core/Banshee.Services/Banshee.Streaming/RadioTrackInfo.cs
+++ b/src/Core/Banshee.Services/Banshee.Streaming/RadioTrackInfo.cs
@@ -290,9 +290,9 @@ namespace Banshee.Streaming
         private void LoadStreamUri(string uri)
         {
             try {
-                PlaylistParser parser = new PlaylistParser();
-                if (parser.Parse(new SafeUri(uri))) {
-                    foreach (PlaylistElement element in parser.Elements) {
+                var parsed_playlist = PlaylistParser.Parse (new SafeUri (uri));
+                if (parsed_playlist != null) {
+                    foreach (PlaylistElement element in parsed_playlist.Elements) {
                         if (element.Uri != null) {
                             // mms can be a nested link
                             string element_uri = element.Uri.ToString ();
diff --git a/src/Core/Banshee.Services/Makefile.am b/src/Core/Banshee.Services/Makefile.am
index f2aac96..5ab43db 100644
--- a/src/Core/Banshee.Services/Makefile.am
+++ b/src/Core/Banshee.Services/Makefile.am
@@ -158,6 +158,7 @@ SOURCES =  \
        Banshee.Playlists.Formats/InvalidPlaylistException.cs \
        Banshee.Playlists.Formats/IPlaylistFormat.cs \
        Banshee.Playlists.Formats/M3uPlaylistFormat.cs \
+       Banshee.Playlists.Formats/ParsedPlaylist.cs \
        Banshee.Playlists.Formats/PlaylistElement.cs \
        Banshee.Playlists.Formats/PlaylistFormatBase.cs \
        Banshee.Playlists.Formats/PlaylistFormatDescription.cs \


[Date Prev][Date Next]   [Thread Prev][Thread Next]   [Thread Index] [Date Index] [Author Index]