Esempio n. 1
0
        private void OnTrackFinished(object o, AudioCdRipperTrackFinishedArgs args)
        {
            if (user_job == null || ripper == null)
            {
                return;
            }

            AudioCdTrackInfo track = (AudioCdTrackInfo)args.Track;

            ripped_duration    += track.Duration;
            track.PrimarySource = ServiceManager.SourceManager.MusicLibrary;
            track.Uri           = args.Uri;

            track.FileSize          = Banshee.IO.File.GetSize(track.Uri);
            track.FileModifiedStamp = Banshee.IO.File.GetModifiedTime(track.Uri);
            track.LastSyncedStamp   = DateTime.Now;

            using (var file = StreamTagger.ProcessUri(track.Uri)) {
                StreamTagger.TrackInfoMerge(track, file, true);
            }

            track.Save();

            source.UnlockTrack(track);
            RipNextTrack();
        }
        public static void Scan()
        {
            Hyena.Log.Debug("[RippedFileScanner] <Scan> Start");

            List <string> current_list = new List <string> ();

            GetFileNames(current_list, basepath);
            List <string> new_items = GetNewItems(previous_list, current_list);

            if (new_items != null && previous_list != null)
            {
                foreach (string item in new_items)
                {
                    DatabaseTrackInfo new_track = new DatabaseTrackInfo();

                    if (new_track != null)
                    {
                        StreamTagger.TrackInfoMerge(new_track, new SafeUri(item));
                        // I think here should be a check to database if track is unique
                        Hyena.Log.DebugFormat("[RippedFileScanner] <Scan> New track found! Artist: {0} Title: {1}", new_track.ArtistName, new_track.TrackTitle);
                        new_track.PrimarySource = Banshee.ServiceStack.ServiceManager.SourceManager.MusicLibrary;
                        new_track.Save();
                    }
                }
            }

            previous_list = current_list;
            Hyena.Log.Debug("[RippedFileScanner] <Scan> End");
        }
Esempio n. 3
0
        private void ChangeAndVerify(SafeUri uri, Action <TrackInfo> change, Action <TrackInfo> verify)
        {
            TagLib.File file  = StreamTagger.ProcessUri(uri);
            TrackInfo   track = new TrackInfo();

            StreamTagger.TrackInfoMerge(track, file);
            file.Dispose();

            // Make changes
            change(track);

            // Save changes
            bool saved = StreamTagger.SaveToFile(track, true, true, true);

            Assert.IsTrue(saved);

            // Read changes
            file  = StreamTagger.ProcessUri(uri);
            track = new TrackInfo();
            StreamTagger.TrackInfoMerge(track, file, false, true, true);
            file.Dispose();

            // Verify changes
            verify(track);
        }
Esempio n. 4
0
        public void Open(SafeUri uri)
        {
            // Check if the uri exists
            if (uri == null || !File.Exists(uri.AbsolutePath))
            {
                return;
            }

            bool found = false;

            if (ServiceManager.DbConnection != null)
            {
                // Try to find uri in the library
                int track_id = DatabaseTrackInfo.GetTrackIdForUri(uri);
                if (track_id > 0)
                {
                    DatabaseTrackInfo track_db = DatabaseTrackInfo.Provider.FetchSingle(track_id);
                    found = true;
                    Open(track_db);
                }
            }

            if (!found)
            {
                // Not in the library, get info from the file
                TrackInfo track = new TrackInfo();
                using (var file = StreamTagger.ProcessUri(uri)) {
                    StreamTagger.TrackInfoMerge(track, file, false);
                }
                Open(track);
            }
        }
Esempio n. 5
0
        public static void ImportPlaylistToLibrary(string path, PrimarySource source, DatabaseImportManager importer)
        {
            try {
                SafeUri        uri          = new SafeUri(path);
                PlaylistParser parser       = new PlaylistParser();
                string         relative_dir = System.IO.Path.GetDirectoryName(uri.LocalPath);
                if (relative_dir[relative_dir.Length - 1] != System.IO.Path.DirectorySeparatorChar)
                {
                    relative_dir = relative_dir + System.IO.Path.DirectorySeparatorChar;
                }
                parser.BaseUri = new Uri(relative_dir);
                if (parser.Parse(uri))
                {
                    List <string> uris = new List <string> ();
                    foreach (PlaylistElement element in parser.Elements)
                    {
                        uris.Add(element.Uri.LocalPath);
                    }

                    if (source == null)
                    {
                        if (uris.Count > 0)
                        {
                            // Get the media attribute of the 1st Uri in Playlist
                            // and then determine whether the playlist belongs to Video or Music
                            SafeUri uri1  = new SafeUri(uris[0]);
                            var     track = new TrackInfo();
                            StreamTagger.TrackInfoMerge(track, uri1);

                            if (track.HasAttribute(TrackMediaAttributes.VideoStream))
                            {
                                source = ServiceManager.SourceManager.VideoLibrary;
                            }
                            else
                            {
                                source = ServiceManager.SourceManager.MusicLibrary;
                            }
                        }
                    }

                    // Give source a fallback value - MusicLibrary when it's null
                    if (source == null)
                    {
                        source = ServiceManager.SourceManager.MusicLibrary;
                    }

                    // Only import an non-empty playlist
                    if (uris.Count > 0)
                    {
                        ImportPlaylistWorker worker = new ImportPlaylistWorker(
                            parser.Title,
                            uris.ToArray(), source, importer);
                        worker.Import();
                    }
                }
            } catch (Exception e) {
                Hyena.Log.Exception(e);
            }
        }
        public DatabaseTrackInfo ImportTrack(SafeUri uri)
        {
            if (!IsWhiteListedFile(uri.LocalPath))
            {
                return(null);
            }

            if (DatabaseTrackInfo.ContainsUri(uri, PrimarySourceIds))
            {
                // TODO add DatabaseTrackInfo.SyncedStamp property, and if the file has been
                // updated since the last sync, fetch its metadata into the db.
                return(null);
            }

            DatabaseTrackInfo track = null;

            // TODO note, there is deadlock potential here b/c of locking of shared commands and blocking
            // because of transactions.  Needs to be fixed in HyenaDatabaseConnection.
            ServiceManager.DbConnection.BeginTransaction();
            try {
                track     = new DatabaseTrackInfo();
                track.Uri = uri;
                StreamTagger.TrackInfoMerge(track, StreamTagger.ProcessUri(uri));

                track.PrimarySource = trackPrimarySourceChooser(track);

                bool save_track = true;
                if (track.PrimarySource is Banshee.Library.LibrarySource)
                {
                    save_track = track.CopyToLibraryIfAppropriate(force_copy);
                }

                if (save_track)
                {
                    track.Save(false);
                }

                ServiceManager.DbConnection.CommitTransaction();
            } catch (Exception) {
                ServiceManager.DbConnection.RollbackTransaction();
                throw;
            }

            counts[track.PrimarySourceId] = counts.ContainsKey(track.PrimarySourceId) ? counts[track.PrimarySourceId] + 1 : 1;

            // Reload every 20% or every 250 tracks, whatever is more (eg at most reload 5 times during an import)
            if (counts[track.PrimarySourceId] >= Math.Max(TotalCount / 5, 250))
            {
                counts[track.PrimarySourceId] = 0;
                track.PrimarySource.NotifyTracksAdded();
            }

            return(track);
        }
        protected override void IterateCore(HyenaDataReader reader)
        {
            DatabaseTrackInfo track = DatabaseTrackInfo.Provider.Load(reader.Reader);

            var write_delay = track.DateUpdated.AddSeconds(2) - DateTime.Now;

            if (write_delay.TotalMilliseconds > 0)
            {
                System.Threading.Thread.Sleep(write_delay);
                return;
            }

            bool wrote   = false;
            bool renamed = false;

            try {
                if (WriteMetadataEnabled || WriteRatingsAndPlayCountsEnabled)
                {
                    Hyena.Log.DebugFormat("Saving metadata for {0}", track);
                    wrote = StreamTagger.SaveToFile(track, WriteMetadataEnabled, WriteRatingsAndPlayCountsEnabled);
                }

                // Rename tracks only from the Music Library
                if (RenameEnabled &&
                    track.PrimarySource.Equals(musicLibrarySource))
                {
                    Hyena.Log.DebugFormat("Updating file name for {0}", track);
                    renamed = RenameFile(track);
                    if (renamed && !wrote)
                    {
                        track.LastSyncedStamp = DateTime.Now;
                    }
                }
            } catch (Exception) {
                Hyena.Log.ErrorFormat("Error writing to or renaming {0}", track);
            } finally {
                if (wrote || renamed)
                {
                    // Save the resulting changes to FileSize, LastSyncedStamp, possibly to Uri, etc
                    // Clear track model caches if URI changed
                    track.Save(renamed);
                }
                else
                {
                    if (update_synced_at == null)
                    {
                        update_synced_at = new HyenaSqliteCommand(
                            "UPDATE CoreTracks SET LastSyncedStamp = ? WHERE TrackID = ?");
                    }

                    ServiceManager.DbConnection.Execute(update_synced_at, DateTime.Now, track.TrackId);
                }
            }
        }
Esempio n. 8
0
        private void OnMetadataServiceHaveResult(object o, MetadataLookupResultArgs args)
        {
            if (CurrentTrack != null && CurrentTrack.TrackEqual(args.Track as TrackInfo))
            {
                foreach (StreamTag tag in args.ResultTags)
                {
                    StreamTagger.TrackInfoMerge(CurrentTrack, tag);
                }

                OnEngineEventChanged(new PlayerEventArgs(PlayerEvent.TrackInfoUpdated));
            }
        }
Esempio n. 9
0
        protected void OnTagFound (StreamTag tag)
        {
            if (tag.Equals (StreamTag.Zero) || current_track == null
                || (current_track.Uri != null && current_track.Uri.IsFile)) {
                return;
            }

            StreamTagger.TrackInfoMerge (current_track, tag);

            if (track_info_updated_timeout <= 0) {
                track_info_updated_timeout = Application.RunTimeout (250, OnTrackInfoUpdated);
            }
        }
        private void SaveToID3(TrackInfo track, string lyrics)
        {
            TagLib.File file = StreamTagger.ProcessUri(track.Uri);
            if (file == null || lyrics.Equals(file.Tag.Lyrics))
            {
                return;
            }

            file.Tag.Lyrics = lyrics;
            file.Save();

            track.FileSize          = Banshee.IO.File.GetSize(track.Uri);
            track.FileModifiedStamp = Banshee.IO.File.GetModifiedTime(track.Uri);
            track.LastSyncedStamp   = DateTime.Now;
        }
Esempio n. 11
0
 private string GetMetadataHash(QueueItem item)
 {
     if (item.ChangeType == WatcherChangeTypes.Created && item.MetadataHash == null)
     {
         var uri = new SafeUri(item.FullPath);
         if (DatabaseImportManager.IsWhiteListedFile(item.FullPath) && Banshee.IO.File.Exists(uri))
         {
             var track = new TrackInfo();
             using (var file = StreamTagger.ProcessUri(uri)) {
                 StreamTagger.TrackInfoMerge(track, file);
             }
             item.MetadataHash = track.MetadataHash;
         }
     }
     return(item.MetadataHash);
 }
Esempio n. 12
0
        public TagLib.File GetTaglibFile()
        {
            if (Uri.Scheme == "http" || Uri.Scheme == "https")
            {
                return(null);
            }

            try {
                return(StreamTagger.ProcessUri(Uri));
            } catch (Exception e) {
                if (Uri.Scheme == "file")
                {
                    Hyena.Log.Exception("Cannot load TagLib file", e);
                }
            }

            return(null);
        }
        protected override void IterateCore(HyenaDataReader reader)
        {
            DatabaseTrackInfo track = DatabaseTrackInfo.Provider.Load(reader.Reader);

            bool wrote   = false;
            bool renamed = false;

            try {
                if (WriteEnabled)
                {
                    Hyena.Log.DebugFormat("Saving metadata for {0}", track);
                    wrote = StreamTagger.SaveToFile(track);
                }

                if (RenameEnabled)
                {
                    Hyena.Log.DebugFormat("Updating file name for {0}", track);
                    renamed = RenameFile(track);
                    if (renamed && !wrote)
                    {
                        track.LastSyncedStamp = DateTime.Now;
                    }
                }
            } catch (Exception) {
                Hyena.Log.ErrorFormat("Error writing to or renaming {0}", track);
            } finally {
                if (wrote || renamed)
                {
                    // Save the resulting changes to FileSize, LastSyncedStamp, possibly to Uri, etc
                    // Clear track model caches if URI changed
                    track.Save(renamed);
                }
                else
                {
                    if (update_synced_at == null)
                    {
                        update_synced_at = new HyenaSqliteCommand(
                            "UPDATE CoreTracks SET LastSyncedStamp = ? WHERE TrackID = ?");
                    }

                    ServiceManager.DbConnection.Execute(update_synced_at, DateTime.Now, track.TrackId);
                }
            }
        }
Esempio n. 14
0
 private void UpdateTrack(string track)
 {
     using (var reader = ServiceManager.DbConnection.Query(
                DatabaseTrackInfo.Provider.CreateFetchCommand(
                    "CoreTracks.PrimarySourceID = ? AND CoreTracks.Uri = ? LIMIT 1"), library.DbId, new SafeUri(track).AbsoluteUri)) {
         if (reader.Read())
         {
             var track_info = DatabaseTrackInfo.Provider.Load(reader);
             if (Banshee.IO.File.GetModifiedTime(track_info.Uri) > track_info.FileModifiedStamp)
             {
                 using (var file = StreamTagger.ProcessUri(track_info.Uri)) {
                     StreamTagger.TrackInfoMerge(track_info, file, false);
                 }
                 track_info.LastSyncedStamp = DateTime.Now;
                 track_info.Save(false);
             }
         }
     }
 }
Esempio n. 15
0
 private void UpdateTrack(string track)
 {
     using (var reader = ServiceManager.DbConnection.Query(
                DatabaseTrackInfo.Provider.CreateFetchCommand(String.Format(
                                                                  "CoreTracks.PrimarySourceID = ? AND {0} = ? LIMIT 1",
                                                                  BansheeQuery.UriField.Column)),
                library.DbId, new SafeUri(track).AbsoluteUri)) {
         if (reader.Read())
         {
             var track_info = DatabaseTrackInfo.Provider.Load(reader);
             if (Banshee.IO.File.GetModifiedTime(track_info.Uri) > track_info.FileModifiedStamp)
             {
                 using (var file = StreamTagger.ProcessUri(track_info.Uri)) {
                     StreamTagger.TrackInfoMerge(track_info, file, false,
                                                 SaveTrackMetadataService.WriteRatingsEnabled.Value,
                                                 SaveTrackMetadataService.WritePlayCountsEnabled.Value);
                 }
                 track_info.LastSyncedStamp = DateTime.Now;
                 track_info.Save(false);
             }
         }
     }
 }
Esempio n. 16
0
 protected IPicture [] GetEmbeddedPictures(SafeUri uri)
 {
     TagLib.File file = StreamTagger.ProcessUri(uri);
     return(file == null ? null : file.Tag.Pictures);
 }
Esempio n. 17
0
 protected IPicture [] GetEmbeddedPictures(SafeUri uri)
 {
     using (var file = StreamTagger.ProcessUri(uri)) {
         return(file == null ? null : file.Tag.Pictures);
     }
 }
        private void RefreshMetadataThread(object state)
        {
            int total = ServiceManager.DbConnection.Query <int> ("SELECT count(*) FROM CoreTracks");

            if (total <= 0)
            {
                return;
            }

            UserJob job = new UserJob(Catalog.GetString("Refreshing Metadata"));

            job.SetResources(Resource.Cpu, Resource.Disk, Resource.Database);
            job.PriorityHints = PriorityHints.SpeedSensitive;
            job.Status        = Catalog.GetString("Scanning...");
            job.IconNames     = new string [] { "system-search", "gtk-find" };
            job.Register();

            HyenaSqliteCommand select_command = new HyenaSqliteCommand(
                String.Format(
                    "SELECT {0} FROM {1} WHERE {2}",
                    DatabaseTrackInfo.Provider.Select,
                    DatabaseTrackInfo.Provider.From,
                    DatabaseTrackInfo.Provider.Where
                    )
                );

            int count = 0;

            using (System.Data.IDataReader reader = ServiceManager.DbConnection.Query(select_command)) {
                while (reader.Read())
                {
                    DatabaseTrackInfo track = null;
                    try {
                        track = DatabaseTrackInfo.Provider.Load(reader);

                        if (track != null && track.Uri != null && track.Uri.IsFile)
                        {
                            try {
                                TagLib.File file = StreamTagger.ProcessUri(track.Uri);
                                StreamTagger.TrackInfoMerge(track, file, true);
                            } catch (Exception e) {
                                Log.Warning(String.Format("Failed to update metadata for {0}", track),
                                            e.GetType().ToString(), false);
                            }

                            track.Save(false);
                            track.Artist.Save();
                            track.Album.Save();

                            job.Status = String.Format("{0} - {1}", track.DisplayArtistName, track.DisplayTrackTitle);
                        }
                    } catch (Exception e) {
                        Log.Warning(String.Format("Failed to update metadata for {0}", track), e.ToString(), false);
                    }

                    job.Progress = (double)++count / (double)total;
                }
            }

            if (ServiceManager.DbConnection.Query <int> ("SELECT count(*) FROM CoreConfiguration WHERE Key = 'MetadataVersion'") == 0)
            {
                Execute(String.Format("INSERT INTO CoreConfiguration (EntryID, Key, Value) VALUES (null, 'MetadataVersion', {0})", CURRENT_METADATA_VERSION));
            }
            else
            {
                Execute(String.Format("UPDATE CoreConfiguration SET Value = {0} WHERE Key = 'MetadataVersion'", CURRENT_METADATA_VERSION));
            }

            job.Finish();
            ServiceManager.SourceManager.MusicLibrary.NotifyTracksChanged();
        }
Esempio n. 19
0
        public DatabaseTrackInfo ImportTrack(SafeUri uri)
        {
            if (!IsWhiteListedFile(uri.AbsoluteUri))
            {
                return(null);
            }

            if (DatabaseTrackInfo.ContainsUri(uri, PrimarySourceIds))
            {
                // TODO add DatabaseTrackInfo.SyncedStamp property, and if the file has been
                // updated since the last sync, fetch its metadata into the db.
                return(null);
            }

            if (!Banshee.IO.File.GetPermissions(uri).IsReadable)
            {
                throw new InvalidFileException(String.Format(
                                                   Catalog.GetString("File is not readable so it could not be imported: {0}"),
                                                   Path.GetFileName(uri.LocalPath)));
            }

            if (Banshee.IO.File.GetSize(uri) == 0)
            {
                throw new InvalidFileException(String.Format(
                                                   Catalog.GetString("File is empty so it could not be imported: {0}"),
                                                   Path.GetFileName(uri.LocalPath)));
            }

            DatabaseTrackInfo track = new DatabaseTrackInfo()
            {
                Uri = uri
            };

            using (var file = StreamTagger.ProcessUri(uri)) {
                StreamTagger.TrackInfoMerge(track, file, false, true, true);
            }

            track.Uri = uri;

            if (FindOutdatedDupe(track))
            {
                return(null);
            }

            track.PrimarySource = trackPrimarySourceChooser(track);

            // TODO note, there is deadlock potential here b/c of locking of shared commands and blocking
            // because of transactions.  Needs to be fixed in HyenaDatabaseConnection.
            ServiceManager.DbConnection.BeginTransaction();
            try {
                bool save_track = true;
                if (track.PrimarySource is Banshee.Library.LibrarySource)
                {
                    save_track = track.CopyToLibraryIfAppropriate(force_copy);
                }

                if (save_track)
                {
                    track.Save(false);
                }

                ServiceManager.DbConnection.CommitTransaction();
            } catch (Exception) {
                ServiceManager.DbConnection.RollbackTransaction();
                throw;
            }

            counts[track.PrimarySourceId] = counts.ContainsKey(track.PrimarySourceId) ? counts[track.PrimarySourceId] + 1 : 1;

            // Reload every 20% or every 250 tracks, whatever is more (eg at most reload 5 times during an import)
            if (counts[track.PrimarySourceId] >= Math.Max(TotalCount / 5, 250))
            {
                counts[track.PrimarySourceId] = 0;
                track.PrimarySource.NotifyTracksAdded();
            }

            return(track);
        }