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"); }
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); } } }
private void OnArtistAdditionResponse(object o, ResponseArgs args) { ArtistAdder editor = (ArtistAdder)o; bool destroy = true; try { if (args.ResponseId == ResponseType.Ok) { if (String.IsNullOrEmpty(editor.ArtistName)) { destroy = false; editor.ErrorMessage = Catalog.GetString("Please provide a artist name"); } else { JsonArray results = IO.MakeRequest("people", editor.ArtistName); foreach (JsonObject artist in results) { string artist_name = (string)artist["username"]; if (artist_name == editor.ArtistName) { //SC.log(artist.ToString()); JsonArray tracks = IO.MakeRequest("getalltracks", (int)artist["id"]); //SC.log(tracks.ToString()); SC.log(String.Format("Artist: {0}, Track Count: {1}", artist_name, tracks.Count)); foreach (JsonObject t in tracks) { DatabaseTrackInfo track = IO.makeTrackInfo(t); track.PrimarySource = this; track.IsLive = true; track.Save(); SC.log(" added track: " + track.TrackTitle); } } } // If all is well, set the window to close. destroy = true; } } } finally { if (destroy) { // Remove response-handler reference. editor.Response -= OnArtistAdditionResponse; editor.Destroy(); } } }
public DatabaseTrackInfo ImportPodcast(string uri) { DatabaseTrackInfo track = null; track = ImportTrack(uri); if (track != null) { track.MediaAttributes |= TrackMediaAttributes.Podcast; track.Save(); } return(track); }
/*public override void CopyTrackTo (DatabaseTrackInfo track, SafeUri uri, UserJob job) * { * Banshee.IO.File.Copy (track.Uri, uri, false); * }*/ protected override void AddTrack(DatabaseTrackInfo track) { // Ignore if already have it if (track.PrimarySourceId == DbId) { return; } PrimarySource source = track.PrimarySource; // If it's from a local primary source, change its PrimarySource if (source.IsLocal || source is LibrarySource) { track.PrimarySource = this; if (!(source is LibrarySource)) { track.CopyToLibraryIfAppropriate(false); } track.Save(false); // TODO optimize, remove this? I think it makes moving items // between local libraries very slow. //source.NotifyTracksChanged (); } else { // Figure out where we should put it if were to copy it var pattern = this.PathPattern ?? MusicLibrarySource.MusicFileNamePattern; string path = pattern.BuildFull(BaseDirectory, track); SafeUri uri = new SafeUri(path); // Make sure it's not already in the library // TODO optimize - no need to recreate this int [] every time if (DatabaseTrackInfo.ContainsUri(uri, new int [] { DbId })) { return; } // Since it's not, copy it and create a new TrackInfo object track.PrimarySource.CopyTrackTo(track, uri, AddTrackJob); // Create a new entry in CoreTracks for the copied file DatabaseTrackInfo new_track = new DatabaseTrackInfo(track); new_track.Uri = uri; new_track.PrimarySource = this; new_track.Save(false); } }
/// <summary> /// Adds the currently selected item(s) of the active source to the internet radio source /// as new stations. Any session data (as in live365 with activated user login) will previously /// be cleared. /// </summary> /// <param name="o"> /// A <see cref="System.Object"/> -- not used /// </param> /// <param name="e"> /// A <see cref="EventArgs"/> -- not used /// </param> protected void OnAddToInternetRadio(object o, EventArgs e) { PrimarySource internet_radio_source = GetInternetRadioSource(); PrimarySource current_source = ServiceManager.SourceManager.ActiveSource as PrimarySource; if (current_source == null) { Log.Debug("[LiveRadioSource]<OnAddToInternetRadio> ActiveSource not Primary"); return; } if (internet_radio_source == null) { Log.Debug("[LiveRadioSource]<OnAddToInternetRadio> Internet Radio not found"); return; } ITrackModelSource active_track_model_source = (ITrackModelSource)current_source; if (active_track_model_source.TrackModel.SelectedItems == null || active_track_model_source.TrackModel.SelectedItems.Count <= 0) { return; } ILiveRadioPlugin current_plugin = null; foreach (ILiveRadioPlugin plugin in plugins) { if (plugin.PluginSource != null && plugin.PluginSource.Equals(current_source)) { current_plugin = plugin; } } foreach (TrackInfo track in active_track_model_source.TrackModel.SelectedItems) { DatabaseTrackInfo station_track = new DatabaseTrackInfo(track as DatabaseTrackInfo); if (station_track != null) { station_track.PrimarySource = internet_radio_source; if (current_plugin != null) { station_track.Uri = current_plugin.CleanUpUrl(station_track.Uri); } station_track.Save(); } } }
private void OnItemAdded(FeedItem item) { if (item.Enclosure != null) { DatabaseTrackInfo track = new DatabaseTrackInfo(); track.ExternalId = item.DbId; track.PrimarySource = source; (track.ExternalObject as PodcastTrackInfo).SyncWithFeedItem(); track.Save(false); RefreshArtworkFor(item.Feed); } else { // We're only interested in items that have enclosures item.Delete(false); } }
public override void UpdateMetadata(DatabaseTrackInfo track) { SafeUri new_uri = new SafeUri(GetTrackPath(track, System.IO.Path.GetExtension(track.Uri))); if (new_uri.ToString() != track.Uri.ToString()) { Directory.Create(System.IO.Path.GetDirectoryName(new_uri.LocalPath)); Banshee.IO.File.Move(track.Uri, new_uri); //to remove the folder if it's not needed anymore: DeleteTrackFile(track); track.Uri = new_uri; track.Save(true, BansheeQuery.UriField); } base.UpdateMetadata(track); }
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); } } }
private void OnItemChanged(FeedItem item) { if (IgnoreItemChanges) { return; } DatabaseTrackInfo track = GetTrackByItemId(item.DbId); if (track != null) { PodcastTrackInfo pi = track.ExternalObject as PodcastTrackInfo; if (pi != null) { pi.SyncWithFeedItem(); track.Save(true); } } }
private void MigrateXspfTrack(Media.Playlists.Xspf.Playlist playlist, Track track) { if (track.LocationCount <= 0) { return; } DatabaseTrackInfo station = new DatabaseTrackInfo(); station.PrimarySource = source; station.IsLive = true; station.Uri = GetSafeUri(track.Locations[0]); if (!String.IsNullOrEmpty(track.Title)) { station.TrackTitle = track.Title; } if (!String.IsNullOrEmpty(track.Creator)) { station.ArtistName = track.Creator; } if (!String.IsNullOrEmpty(track.Annotation)) { station.Comment = track.Annotation; } if (!String.IsNullOrEmpty(playlist.Title)) { station.Genre = playlist.Title; } if (track.Info != null) { station.MoreInfoUri = GetSafeUri(track.Info); } station.Save(); }
private void ProcessSong(LibraryImportManager import_manager, XmlReader xml_reader) { data.total_processed++; var itunes_id = 0; var title = String.Empty; var title_sort = String.Empty; var genre = String.Empty; var artist = String.Empty; var artist_sort = String.Empty; var album_artist = String.Empty; var album_artist_sort = String.Empty; var composer = String.Empty; var album = String.Empty; var album_sort = String.Empty; var grouping = String.Empty; var year = 0; var rating = 0; var play_count = 0; var track_number = 0; var date_added = DateTime.Now; var last_played = DateTime.MinValue; SafeUri uri = null; using (xml_reader) { while (xml_reader.ReadToFollowing("key")) { xml_reader.Read(); string key = xml_reader.ReadContentAsString(); xml_reader.Read(); xml_reader.Read(); try { switch (key) { case "Track ID": itunes_id = Int32.Parse(xml_reader.ReadContentAsString()); break; case "Name": title = xml_reader.ReadContentAsString(); break; case "Sort Name": title_sort = xml_reader.ReadContentAsString(); break; case "Genre": genre = xml_reader.ReadContentAsString(); break; case "Artist": artist = xml_reader.ReadContentAsString(); break; case "Sort Artist": artist_sort = xml_reader.ReadContentAsString(); break; case "Album Artist": album_artist = xml_reader.ReadContentAsString(); break; case "Sort Album Artist": album_artist_sort = xml_reader.ReadContentAsString(); break; case "Composer": composer = xml_reader.ReadContentAsString(); break; case "Album": album = xml_reader.ReadContentAsString(); break; case "Sort Album": album_sort = xml_reader.ReadContentAsString(); break; case "Grouping": grouping = xml_reader.ReadContentAsString(); break; case "Year": year = Int32.Parse(xml_reader.ReadContentAsString()); break; case "Rating": rating = Int32.Parse(xml_reader.ReadContentAsString()) / 20; break; case "Play Count": play_count = Int32.Parse(xml_reader.ReadContentAsString()); break; case "Track Number": track_number = Int32.Parse(xml_reader.ReadContentAsString()); break; case "Date Added": date_added = DateTime.Parse(xml_reader.ReadContentAsString(), DateTimeFormatInfo.InvariantInfo, DateTimeStyles.AssumeUniversal); break; case "Play Date UTC": last_played = DateTime.Parse(xml_reader.ReadContentAsString(), DateTimeFormatInfo.InvariantInfo, DateTimeStyles.AssumeUniversal); break; case "Location": uri = ConvertToLocalUri(xml_reader.ReadContentAsString()); break; } } catch { } } } if (uri == null) { return; } UpdateUserJob(data.total_processed, data.total_songs, artist, title); try { DatabaseTrackInfo track = import_manager.ImportTrack(uri); if (track == null) { LogError(SafeUri.UriToFilename(uri), Catalog.GetString("Unable to import song.")); return; } if (!String.IsNullOrEmpty(title)) { track.TrackTitle = title; } if (!String.IsNullOrEmpty(title_sort)) { track.TrackTitleSort = title_sort; } if (!String.IsNullOrEmpty(artist)) { track.ArtistName = artist; } if (!String.IsNullOrEmpty(artist_sort)) { track.ArtistNameSort = artist_sort; } if (!String.IsNullOrEmpty(genre)) { track.Genre = genre; } if (!String.IsNullOrEmpty(album_artist)) { track.AlbumArtist = album_artist; } if (!String.IsNullOrEmpty(album_artist_sort)) { track.AlbumArtistSort = album_artist_sort; } if (!String.IsNullOrEmpty(composer)) { track.Composer = composer; } if (!String.IsNullOrEmpty(album)) { track.AlbumTitle = album; } if (!String.IsNullOrEmpty(album_sort)) { track.AlbumTitleSort = album_sort; } if (!String.IsNullOrEmpty(grouping)) { track.Grouping = grouping; } if (year > 0) { track.Year = year; } if (data.get_ratings && rating > 0 && rating <= 5) { track.Rating = rating; } if (data.get_stats && play_count > 0) { track.PlayCount = play_count; } if (track_number > 0) { track.TrackNumber = track_number; } if (data.get_stats) { track.DateAdded = date_added; } if (data.get_stats && last_played > DateTime.MinValue) { track.LastPlayed = last_played; } data.track_ids.Add(itunes_id, track.TrackId); track.Save(false); } catch (Exception e) { LogError(SafeUri.UriToFilename(uri), e); } }
protected override void AddTrackToDevice(DatabaseTrackInfo track, SafeUri fromUri) { if (track.PrimarySourceId == DbId) { return; } SafeUri new_uri = new SafeUri(GetTrackPath(track, System.IO.Path.GetExtension(fromUri))); // If it already is on the device but it's out of date, remove it //if (File.Exists(new_uri) && File.GetLastWriteTime(track.Uri.LocalPath) > File.GetLastWriteTime(new_uri)) //RemoveTrack(new MassStorageTrackInfo(new SafeUri(new_uri))); if (!File.Exists(new_uri)) { Directory.Create(System.IO.Path.GetDirectoryName(new_uri.LocalPath)); File.Copy(fromUri, new_uri, false); DatabaseTrackInfo copied_track = new DatabaseTrackInfo(track); copied_track.PrimarySource = this; copied_track.Uri = new_uri; // Write the metadata in db to the file on the DAP if it has changed since file was modified // to ensure that when we load it next time, it's data will match what's in the database // and the MetadataHash will actually match. We do this by comparing the time // stamps on files for last update of the db metadata vs the sync to file. // The equals on the inequality below is necessary for podcasts who often have a sync and // update time that are the same to the second, even though the album metadata has changed in the // DB to the feedname instead of what is in the file. It should be noted that writing the metadata // is a small fraction of the total copy time anyway. if (track.LastSyncedStamp >= Hyena.DateTimeUtil.ToDateTime(track.FileModifiedStamp)) { Log.DebugFormat("Copying Metadata to File Since Sync time >= Updated Time"); bool write_metadata = Metadata.SaveTrackMetadataService.WriteMetadataEnabled.Value; bool write_ratings_and_playcounts = Metadata.SaveTrackMetadataService.WriteRatingsAndPlayCountsEnabled.Value; Banshee.Streaming.StreamTagger.SaveToFile(copied_track, write_metadata, write_ratings_and_playcounts); } copied_track.Save(false); } if (CoverArtSize > -1 && !String.IsNullOrEmpty(CoverArtFileType) && !String.IsNullOrEmpty(CoverArtFileName) && (FolderDepth == -1 || FolderDepth > 0)) { SafeUri cover_uri = new SafeUri(System.IO.Path.Combine(System.IO.Path.GetDirectoryName(new_uri.LocalPath), CoverArtFileName)); string coverart_id = track.ArtworkId; if (!File.Exists(cover_uri) && CoverArtSpec.CoverExists(coverart_id)) { Gdk.Pixbuf pic = null; if (CoverArtSize == 0) { if (CoverArtFileType == "jpg" || CoverArtFileType == "jpeg") { SafeUri local_cover_uri = new SafeUri(Banshee.Base.CoverArtSpec.GetPath(coverart_id)); Banshee.IO.File.Copy(local_cover_uri, cover_uri, false); } else { pic = artwork_manager.LookupPixbuf(coverart_id); } } else { pic = artwork_manager.LookupScalePixbuf(coverart_id, CoverArtSize); } if (pic != null) { try { byte [] bytes = pic.SaveToBuffer(CoverArtFileType); System.IO.Stream cover_art_file = File.OpenWrite(cover_uri, true); cover_art_file.Write(bytes, 0, bytes.Length); cover_art_file.Close(); } catch (GLib.GException) { Log.DebugFormat("Could not convert cover art to {0}, unsupported filetype?", CoverArtFileType); } finally { Banshee.Collection.Gui.ArtworkManager.DisposePixbuf(pic); } } } } }
private void OnStationEditorResponse(object o, ResponseArgs args) { StationEditor editor = (StationEditor)o; bool destroy = true; try { if (args.ResponseId == ResponseType.Ok) { DatabaseTrackInfo track = editor.Track ?? new DatabaseTrackInfo(); track.PrimarySource = this; track.IsLive = true; try { track.Uri = new SafeUri(editor.StreamUri); } catch { destroy = false; editor.ErrorMessage = Catalog.GetString("Please provide a valid station URI"); } if (!String.IsNullOrEmpty(editor.StationCreator)) { track.ArtistName = editor.StationCreator; } track.Comment = editor.Description; if (!String.IsNullOrEmpty(editor.Genre)) { track.Genre = editor.Genre; } else { destroy = false; editor.ErrorMessage = Catalog.GetString("Please provide a station genre"); } if (!String.IsNullOrEmpty(editor.StationTitle)) { track.TrackTitle = editor.StationTitle; track.AlbumTitle = editor.StationTitle; } else { destroy = false; editor.ErrorMessage = Catalog.GetString("Please provide a station title"); } track.Rating = editor.Rating; if (destroy) { track.Save(); } } } finally { if (destroy) { editor.Response -= OnStationEditorResponse; editor.Destroy(); } } }
protected override void ImportCore() { LibraryImportManager import_manager = ServiceManager.Get <LibraryImportManager> (); HyenaSqliteConnection conn; try { conn = new HyenaSqliteConnection(amarok_db_path); } catch (Exception e) { LogError(amarok_db_path, String.Format( "Unable to open Amarok database: {0}", e.Message)); return; } int count = 0; try { count = conn.Query <int> ("SELECT COUNT(*) FROM tags"); } catch (Exception) {} try { HyenaSqliteCommand cmd = new HyenaSqliteCommand(@" SELECT DISTINCT NULL, tags.url, tags.title, artist.name, genre.name, album.name, year.name, tags.track, tags.length FROM tags, artist, album, genre, year WHERE tags.deviceid = -1 AND tags.artist = artist.id AND tags.album = album.id AND tags.genre = genre.id AND tags.year = year.id" ); HyenaSqliteCommand stats_cmd = new HyenaSqliteCommand(@" SELECT DISTINCT (rating+rating%2)/2, playcounter, createdate, accessdate FROM statistics WHERE url = ? AND deviceid = -1"); int processed = 0; IDataReader reader = conn.Query(cmd); while (reader.Read()) { if (CheckForCanceled()) { break; } processed++; try { string path = (string)reader[1]; SafeUri uri = null; if (path.StartsWith("./")) { uri = new SafeUri(path.Substring(1)); } else if (path.StartsWith("/")) { uri = new SafeUri(path); } else { continue; } string title = (string)reader[2]; string artist = (string)reader[3]; //Console.WriteLine ("Amarok import has {0}/{1} - {2}", artist, title, uri); // the following fields are not critical and can be skipped if something goes wrong int rating = 0, playcount = 0; long created = 0, accessed = 0; // Try to read stats try { IDataReader stats_reader = conn.Query(stats_cmd, path); while (stats_reader.Read()) { rating = Convert.ToInt32(stats_reader[0]); playcount = Convert.ToInt32(stats_reader[1]); created = Convert.ToInt64(stats_reader[2]); accessed = Convert.ToInt64(stats_reader[3]); } stats_reader.Dispose(); } catch (Exception) {} UpdateUserJob(processed, count, artist, title); try { DatabaseTrackInfo track = import_manager.ImportTrack(uri); if (track == null) { throw new Exception(String.Format(Catalog.GetString("Unable to import track: {0}"), uri.AbsoluteUri)); } if (rating > 0 || playcount > 0 || created > 0 || accessed > 0) { track.Rating = rating; track.PlayCount = playcount; if (created > 0) { track.DateAdded = Hyena.DateTimeUtil.FromTimeT(created); } if (accessed > 0) { track.LastPlayed = Hyena.DateTimeUtil.FromTimeT(accessed); } track.Save(false); } } catch (Exception e) { LogError(SafeUri.UriToFilename(uri), e); } } catch (Exception e) { Hyena.Log.Exception(e); // something went wrong, skip entry } } reader.Dispose(); import_manager.NotifyAllSources(); // TODO migrating more than the podcast subscriptions (eg whether to auto sync them etc) means 1) we need to have those features // and 2) we need to depend on Migo and/or the Podcast extension DBusCommandService cmd_service = ServiceManager.Get <DBusCommandService> (); if (cmd_service != null && ServiceManager.DbConnection.TableExists("PodcastSyndications")) { foreach (string podcast_url in conn.QueryEnumerable <string> ("SELECT url FROM podcastchannels")) { cmd_service.PushFile(podcast_url.Replace("http:", "feed:")); } } } catch (Exception e) { Hyena.Log.Exception(e); LogError(amarok_db_path, Catalog.GetString("Importing from Amarok failed")); } finally { conn.Dispose(); } }
private void TryToFixNonMp3Metadata() { if (already_fixed || mp3_imported_tracks.Count != mp3_count || non_mp3_queue.Count <= 0) { return; } already_fixed = true; // FIXME: this is all pretty lame. Amazon doesn't have any metadata on the PDF // files, which is a shame. So I attempt to figure out the best common metadata // from the already imported tracks in the album, and then forcefully persist // this in the database. When Taglib# supports reading/writing PDF, we can // persist this back the the PDF file, and support it for importing like normal. var artist_name = MostCommon <TrackInfo, string> (mp3_imported_tracks, track => track.AlbumArtist) ?? MostCommon <TrackInfo, string> (mp3_imported_tracks, track => track.ArtistName); var album_title = MostCommon <TrackInfo, string> (mp3_imported_tracks, track => track.AlbumTitle); var genre = MostCommon <TrackInfo, string> (mp3_imported_tracks, track => track.Genre); var copyright = MostCommon <TrackInfo, string> (mp3_imported_tracks, track => track.Copyright); var year = MostCommon <TrackInfo, int> (mp3_imported_tracks, track => track.Year); var track_count = MostCommon <TrackInfo, int> (mp3_imported_tracks, track => track.TrackCount); var disc_count = MostCommon <TrackInfo, int> (mp3_imported_tracks, track => track.DiscCount); while (non_mp3_queue.Count > 0) { var downloader = non_mp3_queue.Dequeue(); var track = new DatabaseTrackInfo() { AlbumArtist = artist_name, ArtistName = artist_name, AlbumTitle = album_title, TrackTitle = downloader.Track.Title, TrackCount = track_count, DiscCount = disc_count, Year = year, Genre = genre, Copyright = copyright, Uri = new SafeUri(downloader.LocalPath), MediaAttributes = TrackMediaAttributes.ExternalResource, PrimarySource = ServiceManager.SourceManager.MusicLibrary }; track.CopyToLibraryIfAppropriate(true); if (downloader.FileExtension == "pdf") { track.MimeType = "application/pdf"; Application.Invoke(delegate { ServiceManager.DbConnection.BeginTransaction(); try { track.Save(); ServiceManager.DbConnection.CommitTransaction(); } catch { ServiceManager.DbConnection.RollbackTransaction(); throw; } }); } } }
//private Stack<DatabaseTrackInfo> stk=new Stack<DatabaseTrackInfo>(); public void ImportSheet(CueSheet s) { if (import_manager == null) { try { import_manager = new LibraryImportManager(false); /*import_manager.ImportResult+=delegate(object sender,DatabaseImportResultArgs args) { * DatabaseTrackInfo trk=args.Track; * stk.Push (trk); * };*/ } catch (Exception ex) { Hyena.Log.Error(ex.ToString()); } } Hyena.Log.Debug("Importsheet: Starting transaction"); int i, N; for (i = 0, N = s.nEntries(); i < N; i++) { try { CueSheetEntry e = s.entry(i); string file = e.file(); string uuid = Regex.Replace(e.id(), "\\s", "_"); string ext = ".mp3"; string uid = Guid.NewGuid().ToString(); string u1 = uid.Substring(0, 1); string u2 = uid.Substring(0, 2); string dir = basedir + "/.banshee/" + u1; if (!Directory.Exists(dir)) { Directory.CreateDirectory(dir); } dir += "/" + u2; if (!Directory.Exists(dir)) { Directory.CreateDirectory(dir); } uuid = dir + "/" + uuid + ext; UnixFileInfo f = new UnixFileInfo(file); if (File.Exists(uuid)) { File.Delete(uuid); } //f.CreateLink (uuid); f.CreateSymbolicLink(uuid); DatabaseTrackInfo trk = import_manager.ImportTrack(uuid); //File.Delete (uuid); /*if (trk==null) { * Hyena.Log.Warning ("track = null (file="+e.file ()+")"); * if (stk.Count>0) { trk=stk.Pop (); } * }*/ if (trk == null) { Hyena.Log.Error("track = null (file=" + e.file() + ")"); } else { Hyena.Log.Information("track!=null (file=" + e.file() + ")"); //MySource.DbConnection.BeginTransaction(); trk.PartOfCue = 1; trk.CueAudioFile = e.file(); trk.AlbumTitle = s.title(); //trk.Album=s.title (); trk.AlbumArtist = s.performer(); trk.Composer = (e.Composer == "") ? s.composer() : e.Composer; //trk.ArtworkId=s.getArtId (); //trk.Artist= trk.ArtistName = (e.performer() == "") ? s.performer() : e.performer(); trk.TrackTitle = e.title(); trk.TrackNumber = i + 1; trk.Genre = s.genre(); trk.BeginOffset = e.BeginOffset; trk.EndOffset = e.EndOffset; //trk.Uri=trk.CueAudioUri; //trk.MediaAttributes = TrackMediaAttributes.ExternalResource; //trk.PrimarySource = ServiceManager.SourceManager.MusicLibrary; trk.Save(); //MySource.DbConnection.CommitTransaction(); } } catch (Exception ex) { Hyena.Log.Error(ex.ToString()); } } import_manager.NotifyAllSources(); }
/// <summary> /// Adds a track to is source. Does not actually set the tracks source. /// </summary> /// <param name="track"> /// A <see cref="DatabaseTrackInfo"/> -- the track to be added to its set source /// </param> public override void AddTrack(DatabaseTrackInfo track) { track.CanSaveToDatabase = false; track.PrimarySource = this; track.Save(); }
protected override string ProcessItem(string file_path) { if (!DatabaseImportManager.IsWhiteListedFile(file_path)) { return(null); } // Hack to ignore Podcast files if (file_path.Contains("Podcasts")) { return(null); } //Hyena.Log.DebugFormat ("Rescanning item {0}", file_path); try { SafeUri uri = new SafeUri(file_path); using (var reader = ServiceManager.DbConnection.Query(fetch_command, psource.DbId, uri.AbsoluteUri)) { if (reader.Read()) { //Hyena.Log.DebugFormat ("Found it in the db!"); DatabaseTrackInfo track = DatabaseTrackInfo.Provider.Load(reader); MergeIfModified(track); // Either way, update the LastSyncStamp track.LastSyncedStamp = DateTime.Now; track.Save(false); status = String.Format("{0} - {1}", track.DisplayArtistName, track.DisplayTrackTitle); } else { // This URI is not in the database - try to find it based on MetadataHash in case it was simply moved DatabaseTrackInfo track = new DatabaseTrackInfo(); Banshee.Streaming.StreamTagger.TrackInfoMerge(track, uri); using (var similar_reader = ServiceManager.DbConnection.Query( fetch_similar_command, psource.DbId, scan_started, track.MetadataHash)) { DatabaseTrackInfo similar_track = null; while (similar_reader.Read()) { similar_track = DatabaseTrackInfo.Provider.Load(similar_reader); if (!Banshee.IO.File.Exists(similar_track.Uri)) { //Hyena.Log.DebugFormat ("Apparently {0} was moved to {1}", similar_track.Uri, file_path); similar_track.Uri = uri; MergeIfModified(similar_track); similar_track.LastSyncedStamp = DateTime.Now; similar_track.Save(false); status = String.Format("{0} - {1}", similar_track.DisplayArtistName, similar_track.DisplayTrackTitle); break; } similar_track = null; } // If we still couldn't find it, try to import it if (similar_track == null) { //Hyena.Log.DebugFormat ("Couldn't find it, so queueing to import it"); status = System.IO.Path.GetFileNameWithoutExtension(file_path); ServiceManager.Get <Banshee.Library.LibraryImportManager> ().ImportTrack(uri); } } } } } catch (Exception e) { Hyena.Log.Exception(e); } return(null); }
private void ImportSongs(LibraryImportManager manager, XmlNodeList songs) { foreach (XmlElement song in songs) { if (CheckForCanceled()) { break; } processed++; string title = String.Empty, genre = String.Empty, artist = String.Empty, album = String.Empty; int year = 0, rating = 0, play_count = 0, track_number = 0; DateTime date_added = DateTime.Now, last_played = DateTime.MinValue; SafeUri uri = null; foreach (XmlElement child in song.ChildNodes) { if (child == null || child.InnerText == null || child.InnerText == String.Empty) { continue; } try { switch (child.Name) { case "title": title = child.InnerText; break; case "genre": genre = child.InnerText; break; case "artist": artist = child.InnerText; break; case "album": album = child.InnerText; break; case "track-number": track_number = Int32.Parse(child.InnerText); break; case "location": uri = new SafeUri(child.InnerText); break; case "date": if (child.InnerText != "0") { year = (new DateTime(1, 1, 1).AddDays(Double.Parse(child.InnerText))).Year; } break; case "rating": rating = Int32.Parse(child.InnerText); break; case "play-count": play_count = Int32.Parse(child.InnerText); break; case "last-played": last_played = Hyena.DateTimeUtil.ToDateTime(Int64.Parse(child.InnerText)); break; case "first-seen": date_added = Hyena.DateTimeUtil.ToDateTime(Int64.Parse(child.InnerText));; break; } } catch (Exception) { // parsing InnerText failed } } if (uri == null) { continue; } UpdateUserJob(processed, count, artist, title); try { DatabaseTrackInfo track = manager.ImportTrack(uri); if (track == null) { LogError(SafeUri.UriToFilename(uri), Catalog.GetString("Unable to import song.")); continue; } track.TrackTitle = title; track.ArtistName = artist; track.Genre = genre; track.AlbumTitle = album; track.TrackNumber = track_number; track.Year = year; track.DateAdded = date_added; track.Rating = (rating >= 0 && rating <= 5) ? rating : 0; track.PlayCount = (play_count >= 0) ? play_count : 0; track.LastPlayed = last_played; track.Save(false); } catch (Exception e) { LogError(SafeUri.UriToFilename(uri), e); } } }
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(); }