public void TestTrack()
        {
            var tag = new TagLib.Id3v1.Tag();

            Assert.IsTrue(tag.IsEmpty, "Initially empty");
            Assert.AreEqual(0, tag.Track, "Initially zero");

            var rendered = tag.Render();

            tag = new TagLib.Id3v1.Tag(rendered);
            Assert.IsTrue(tag.IsEmpty, "Still empty");
            Assert.AreEqual(0, tag.Track, "Still zero");

            tag.Track = 123;
            Assert.IsFalse(tag.IsEmpty, "Not empty");
            Assert.AreEqual(123, tag.Track);

            rendered = tag.Render();
            tag      = new TagLib.Id3v1.Tag(rendered);
            Assert.IsFalse(tag.IsEmpty, "Still not empty");
            Assert.AreEqual(123, tag.Track);

            tag.Track = 0;
            Assert.IsTrue(tag.IsEmpty, "Again empty");
            Assert.AreEqual(0, tag.Track, "Again zero");

            rendered = tag.Render();
            tag      = new TagLib.Id3v1.Tag(rendered);
            Assert.IsTrue(tag.IsEmpty, "Still empty");
            Assert.AreEqual(0, tag.Track, "Still zero");
        }
Esempio n. 2
0
 public TagLib.Tag AddTag(TagTypes type, TagLib.Tag copy)
 {
     TagLib.Tag tag = null;
     if (type == TagTypes.Id3v1)
     {
         tag = new TagLib.Id3v1.Tag();
     }
     else if (type == TagTypes.Id3v2)
     {
         Id3v2.Tag tag32 = new Id3v2.Tag();
         tag32.Version = 4;
         tag32.Flags  |= Id3v2.HeaderFlags.FooterPresent;
         tag           = tag32;
     }
     else if (type == TagTypes.Ape)
     {
         tag = new TagLib.Ape.Tag();
     }
     if (tag != null)
     {
         if (copy != null)
         {
             copy.CopyTo(tag, true);
         }
         if (type == TagTypes.Id3v1)
         {
             AddTag(tag);
         }
         else
         {
             InsertTag(0, tag);
         }
     }
     return(tag);
 }
        public void TestYear()
        {
            var tag = new TagLib.Id3v1.Tag();

            Assert.IsTrue(tag.IsEmpty, "Initially empty");
            Assert.AreEqual(0, tag.Year, "Initially zero");

            var rendered = tag.Render();

            tag = new TagLib.Id3v1.Tag(rendered);
            Assert.IsTrue(tag.IsEmpty, "Still empty");
            Assert.AreEqual(0, tag.Year, "Still zero");

            tag.Year = 1999;
            Assert.IsFalse(tag.IsEmpty, "Not empty");
            Assert.AreEqual(1999, tag.Year);

            rendered = tag.Render();
            tag      = new TagLib.Id3v1.Tag(rendered);
            Assert.IsFalse(tag.IsEmpty, "Still not empty");
            Assert.AreEqual(1999, tag.Year);

            tag.Year = 20000;
            Assert.IsTrue(tag.IsEmpty, "Again empty");
            Assert.AreEqual(0, tag.Year, "Again zero");

            rendered = tag.Render();
            tag      = new TagLib.Id3v1.Tag(rendered);
            Assert.IsTrue(tag.IsEmpty, "Still empty");
            Assert.AreEqual(0, tag.Year, "Still zero");
        }
        public void TestTitle()
        {
            var tag = new TagLib.Id3v1.Tag();

            Assert.IsTrue(tag.IsEmpty, "Initially empty");
            Assert.IsNull(tag.Title, "Initially null");

            var rendered = tag.Render();

            tag = new TagLib.Id3v1.Tag(rendered);
            Assert.IsTrue(tag.IsEmpty, "Still empty");
            Assert.IsNull(tag.Title, "Still null");

            tag.Title = "01234567890123456789012345678901234567890123456789";
            Assert.IsFalse(tag.IsEmpty, "Not empty");
            Assert.AreEqual("01234567890123456789012345678901234567890123456789", tag.Title);

            rendered = tag.Render();
            tag      = new TagLib.Id3v1.Tag(rendered);
            Assert.IsFalse(tag.IsEmpty, "Still not empty");
            Assert.AreEqual("012345678901234567890123456789", tag.Title);

            tag.Title = string.Empty;
            Assert.IsTrue(tag.IsEmpty, "Again empty");
            Assert.IsNull(tag.Title, "Again null");

            rendered = tag.Render();
            tag      = new TagLib.Id3v1.Tag(rendered);
            Assert.IsTrue(tag.IsEmpty, "Still empty");
            Assert.IsNull(tag.Title, "Still null");
        }
        public void TestPerformers()
        {
            var tag = new TagLib.Id3v1.Tag();

            Assert.IsTrue(tag.IsEmpty, "Initially empty");
            Assert.AreEqual(0, tag.Performers.Length, "Initially empty");

            var rendered = tag.Render();

            tag = new TagLib.Id3v1.Tag(rendered);
            Assert.IsTrue(tag.IsEmpty, "Still empty");
            Assert.AreEqual(0, tag.Performers.Length, "Still empty");

            tag.Performers = new[] { "A123456789", "B123456789", "C123456789", "D123456789", "E123456789" };
            Assert.IsFalse(tag.IsEmpty, "Not empty");
            Assert.AreEqual("A123456789; B123456789; C123456789; D123456789; E123456789", tag.JoinedPerformers);

            rendered = tag.Render();
            tag      = new TagLib.Id3v1.Tag(rendered);
            Assert.IsFalse(tag.IsEmpty, "Still not empty");
            Assert.AreEqual("A123456789; B123456789; C1234567", tag.JoinedPerformers);

            tag.Performers = new string[0];
            Assert.IsTrue(tag.IsEmpty, "Again empty");
            Assert.AreEqual(0, tag.Performers.Length, "Again empty");

            rendered = tag.Render();
            tag      = new TagLib.Id3v1.Tag(rendered);
            Assert.IsTrue(tag.IsEmpty, "Still empty");
            Assert.AreEqual(0, tag.Performers.Length, "Still empty");
        }
Esempio n. 6
0
 public TagError(string path, string details, TagLib.Id3v2.Tag id3V2Tag, TagLib.Id3v1.Tag id3V1Tag)
 {
     FilePath = path;
     Details  = details;
     ID3V2Tag = new Data.TagData();
     ID3V2Tag.LoadTagData(id3V2Tag, id3V1Tag);
 }
Esempio n. 7
0
        /// <summary>
        ///    Reads a tag ending at a specified position and moves the
        ///    cursor to its start position.
        /// </summary>
        /// <param name="end">
        ///    A <see cref="long" /> value reference specifying at what
        ///    position the potential tag ends at. If a tag is found,
        ///    this value will be updated to the position at which the
        ///    found tag starts.
        /// </param>
        /// <returns>
        ///    A <see cref="TagLib.Tag" /> object representing the tag
        ///    found at the specified position, or <see langword="null"
        ///    /> if no tag was found.
        /// </returns>
        private TagLib.Tag ReadTag(ref long end)
        {
            long     start = end;
            TagTypes type  = ReadTagInfo(ref start);

            TagLib.Tag tag = null;

            try {
                switch (type)
                {
                case TagTypes.Ape:
                    tag = new TagLib.Ape.Tag(file, end - TagLib.Ape.Footer.Size);
                    break;

                case TagTypes.Id3v2:
                    tag = new TagLib.Id3v2.Tag(file, start);
                    break;

                case TagTypes.Id3v1:
                    tag = new TagLib.Id3v1.Tag(file, start);
                    break;
                }

                end = start;
            } catch (CorruptFileException) {
            }

            return(tag);
        }
        public void TestRender()
        {
            var rendered = new TagLib.Id3v1.Tag().Render();

            Assert.AreEqual(128, rendered.Count);
            Assert.IsTrue(rendered.StartsWith(TagLib.Id3v1.Tag.FileIdentifier));
        }
Esempio n. 9
0
        private void Preview(string path)
        {
            if (!File.Exists(path))
            {
                return;
            }
            try
            {
                var tfile           = TagLib.File.Create(path, TagLib.ReadStyle.None);
                TagLib.Id3v1.Tag t  = (TagLib.Id3v1.Tag)tfile.GetTag(TagLib.TagTypes.Id3v1);
                TagLib.Id3v2.Tag t2 = (TagLib.Id3v2.Tag)tfile.GetTag(TagLib.TagTypes.Id3v2);

                ID3v1_TagList.Clear();
                ID3v2_TagList.Clear();
                GetAllStringProperties(t).ForEach(x =>
                {
                    x.Value         = encoding[1].GetString(Encoding.GetEncoding("ISO-8859-1").GetBytes(x.Value));
                    x.Value_Preview = ConvertHelper.Convert(x.Value, encoding, ToChinese1);
                    ID3v1_TagList.Add(x);
                });

                GetAllStringProperties(t2).ForEach(x =>
                {
                    x.Value_Preview = ConvertHelper.Convert(x.Value, ToChinese2);
                    ID3v2_TagList.Add(x);
                });
            }
            catch (TagLib.UnsupportedFormatException)
            {
                ID3v1_TagList.Clear();
                ID3v2_TagList.Clear();
                ID3v1_TagList.Add(new TagList_Line()
                {
                    TagName = "Error", Value = "非音訊檔"
                });
                ID3v2_TagList.Add(new TagList_Line()
                {
                    TagName = "Error", Value = "非音訊檔"
                });
            }
            catch (System.Exception)
            {
                ID3v1_TagList.Clear();
                ID3v2_TagList.Clear();
                ID3v1_TagList.Add(new TagList_Line()
                {
                    TagName = "Error", Value = "未知"
                });
                ID3v2_TagList.Add(new TagList_Line()
                {
                    TagName = "Error", Value = "未知"
                });
            }
        }
Esempio n. 10
0
 /// <summary>Function to read the various tags from file, if available
 /// These will be checked in various get functions
 /// </summary>
 private void ReadTags()
 {
     //currentFile = TagLib.File.Create(FileInfoView.FocusedItem.SubItems[4].Text);
     id3v1 = currentFile.GetTag(TagLib.TagTypes.Id3v1) as TagLib.Id3v1.Tag;
     id3v2 = currentFile.GetTag(TagLib.TagTypes.Id3v2) as TagLib.Id3v2.Tag;
     apple = currentFile.GetTag(TagLib.TagTypes.Apple) as TagLib.Mpeg4.AppleTag;
     ape   = currentFile.GetTag(TagLib.TagTypes.Ape) as TagLib.Ape.Tag;
     //            asf = currentFile.GetTag(TagLib.TagTypes.Asf) as TagLib.Asf.Tag;
     ogg  = currentFile.GetTag(TagLib.TagTypes.Xiph) as TagLib.Ogg.XiphComment;
     flac = currentFile.GetTag(TagLib.TagTypes.FlacMetadata) as TagLib.Flac.Metadata;
 }
Esempio n. 11
0
 /// <summary>
 /// move to previous tag & retreat index
 /// </summary>
 public void Previous()
 {
     if (lv.SelectedItems.Count > Index && Index > 0)
     {
         FileInfo fi = (FileInfo)lv.SelectedItems[--idx].Tag;
         //  lblFile.Text = fi.FullName;
         tag_file = TagLib.File.Create(fi.FullName);
         v2       = (TagLib.Id3v2.Tag)tag_file.GetTag(TagLib.TagTypes.Id3v2);
         v1       = (TagLib.Id3v1.Tag)tag_file.GetTag(TagLib.TagTypes.Id3v1);
         Fill();
     }
 }
Esempio n. 12
0
 private void LoadV1Tag(TagLib.Id3v1.Tag id3Tag)
 {
     Album              = id3Tag.Album;
     Artist             = id3Tag.JoinedPerformers;
     AlbumArtist        = id3Tag.JoinedAlbumArtists;
     DiscNumber         = id3Tag.Disc != 0 ? id3Tag.Disc.ToString() : "";
     DiscCount          = id3Tag.DiscCount != 0 ? id3Tag.DiscCount.ToString() : "";
     DiscNumberAndCount = "";
     TrackNumber        = id3Tag.Track.ToString();
     Year              = id3Tag.Year == 0 ? "0000" : id3Tag.Year.ToString();
     Genre             = id3Tag.JoinedGenres;
     Title             = id3Tag.Title;
     ContainsOtherTags = !string.IsNullOrEmpty(id3Tag.Comment);
     OtherTags         = ContainsOtherTags ? string.Join(",", Data.ID3V2Definitions.FrameDefintions["COMM"]) : "";
 }
Esempio n. 13
0
        /// <summary>
        /// merge like values, hide unlike values
        /// </summary>
        public override void Coalesce()
        {
            FileInfo fi = (FileInfo)lv.SelectedItems[0].Tag;

            TagLib.File      tag_file  = TagLib.File.Create(fi.FullName);
            TagLib.Id3v1.Tag first_tag = tag_file.GetTag(TagLib.TagTypes.Id3v1) as TagLib.Id3v1.Tag;

            foreach (ListViewItem item in lv.SelectedItems)
            {
                fi       = (FileInfo)item.Tag;
                tag_file = TagLib.File.Create(fi.FullName);
                TagLib.Tag tag = tag_file.GetTag(TagLib.TagTypes.Id3v1);

                if (tag != null)
                {
                    if (first_tag.Album != tag.Album)
                    {
                        first_tag.Album = string.Empty;
                    }
                    if (first_tag.JoinedPerformers != tag.JoinedPerformers)
                    {
                        first_tag.Performers = new string[0];
                    }
                    if (first_tag.Title != tag.Title)
                    {
                        first_tag.Title = string.Empty;
                    }
                    if (first_tag.Track != tag.Track)
                    {
                        first_tag.Track = 0;
                    }
                    if (first_tag.Year != tag.Year)
                    {
                        first_tag.Year = 0;
                    }
                    if (first_tag.JoinedGenres != tag.JoinedGenres)
                    {
                        first_tag.Genres = new string[0];
                    }
                    if (first_tag.Comment != tag.Comment)
                    {
                        first_tag.Comment = string.Empty;
                    }
                }
            }
            v1 = first_tag;
        }
        public static MusicFileTag AddFile(string path)
        {
            if (System.IO.File.Exists(path))
            {
                var tagInfo = File.Create(path);

                TagLib.Id3v1.Tag id3v1Tag = tagInfo.GetTag(TagTypes.Id3v1) as TagLib.Id3v1.Tag;
                TagLib.Id3v2.Tag id3v2Tag = tagInfo.GetTag(TagTypes.Id3v2) as TagLib.Id3v2.Tag;

                return(MusicFileTag.ConvertTagToMusicFileTag(id3v1Tag, id3v2Tag, path));
            }
            else
            {
                MessageBox.Show("Couldn't find:\n" + path);
                return(null);
            }
        }
Esempio n. 15
0
        private void GetTags()
        {
            using (TagLib.File file = TagLib.File.Create(MediaFile.FullName))
            {
                DateTime id3v1Start = DateTime.Now;

                try
                {
                    TagLib.Id3v1.Tag v1Tag = (TagLib.Id3v1.Tag)file.GetTag(TagLib.TagTypes.Id3v1);
                    ID3V1Tag = new TagLib.Id3v1.Tag();
                    v1Tag.CopyTo(ID3V1Tag, true);
                }
                catch
                {
                    ID3V1Tag = null;
                }

                DateTime id3v1End = DateTime.Now;

                if (Globals.VerboseLogging)
                {
                    Logger.Info($"'{MediaFile.FullName}' ID3V1 tag loaded in {(id3v1End - id3v1Start).TotalMilliseconds} milliseconds.");
                }

                DateTime id3v2Start = DateTime.Now;

                TagLib.Id3v2.Tag v2Tag = (TagLib.Id3v2.Tag)file.GetTag(TagLib.TagTypes.Id3v2);
                ID3V2Tag = new TagLib.Id3v2.Tag();
                v2Tag.CopyTo(ID3V2Tag, true);

                DateTime id3v2End = DateTime.Now;

                if (Globals.VerboseLogging)
                {
                    Logger.Info($"'{MediaFile.FullName}' ID3V2 tag loaded in {(id3v2End - id3v2Start).TotalMilliseconds} milliseconds.");
                }
            }

            ExecuteTagEdits();
        }
        public void TestGenres()
        {
            var tag = new TagLib.Id3v1.Tag();

            Assert.IsTrue(tag.IsEmpty, "Initially empty");
            Assert.AreEqual(0, tag.Genres.Length, "Initially empty");

            var rendered = tag.Render();

            tag = new TagLib.Id3v1.Tag(rendered);
            Assert.IsTrue(tag.IsEmpty, "Still empty");
            Assert.AreEqual(0, tag.Genres.Length, "Still empty");

            tag.Genres = new[] { "Rap", "Jazz", "Non-Genre", "Blues" };
            Assert.IsFalse(tag.IsEmpty, "Not empty");
            Assert.AreEqual("Rap", tag.JoinedGenres);

            rendered = tag.Render();
            tag      = new TagLib.Id3v1.Tag(rendered);
            Assert.IsFalse(tag.IsEmpty, "Still not empty");
            Assert.AreEqual("Rap", tag.JoinedGenres);

            tag.Genres = new[] { "Non-Genre" };
            Assert.IsTrue(tag.IsEmpty, "Surprisingly empty");
            Assert.AreEqual(0, tag.Genres.Length, "Surprisingly empty");

            rendered = tag.Render();
            tag      = new TagLib.Id3v1.Tag(rendered);
            Assert.IsTrue(tag.IsEmpty, "Still empty");
            Assert.AreEqual(0, tag.Genres.Length, "Still empty");

            tag.Genres = new string[0];
            Assert.IsTrue(tag.IsEmpty, "Again empty");
            Assert.AreEqual(0, tag.Genres.Length, "Again empty");

            rendered = tag.Render();
            tag      = new TagLib.Id3v1.Tag(rendered);
            Assert.IsTrue(tag.IsEmpty, "Still empty");
            Assert.AreEqual(0, tag.Genres.Length, "Still empty");
        }
Esempio n. 17
0
        public void LoadTagData(TagLib.Id3v2.Tag id3V2Tag, TagLib.Id3v1.Tag id3V1Tag, bool forceIDV2Tag = false)
        {
            ValidV1Tag = id3V1Tag != null;
            ValidV2Tag = id3V2Tag != null;

            if ((forceIDV2Tag && id3V2Tag == null) ||
                (id3V1Tag == null && id3V2Tag == null))
            {
                TagDataLoaded = false;
                return;
            }

            if (id3V2Tag != null)
            {
                LoadV2Tag(id3V2Tag);
            }
            else if (id3V1Tag != null)
            {
                LoadV1Tag(id3V1Tag);
            }

            TagDataLoaded = true;
        }
        public void TestClear()
        {
            var tag = new TagLib.Id3v1.Tag {
                Title      = "A",
                Performers = new[] { "B" },
                Album      = "C",
                Year       = 123,
                Comment    = "D",
                Track      = 234,
                Genres     = new[] { "Blues" }
            };

            Assert.IsFalse(tag.IsEmpty, "Should be full.");
            tag.Clear();
            Assert.IsNull(tag.Title, "Title");
            Assert.AreEqual(0, tag.Performers.Length, "Performers");
            Assert.IsNull(tag.Album, "Album");
            Assert.AreEqual(0, tag.Year, "Year");
            Assert.IsNull(tag.Comment, "Comment");
            Assert.AreEqual(0, tag.Track, "Track");
            Assert.AreEqual(0, tag.Genres.Length, "Genres");
            Assert.IsTrue(tag.IsEmpty, "Should be empty.");
        }
Esempio n. 19
0
        private async void Button_Convert_Click(object sender, RoutedEventArgs e)
        {
            ((Button)e.Source).IsEnabled = false;
            Stopwatch stopwatch = new Stopwatch();

            stopwatch.Start();

            var    temp         = FileList.Where(x => x.IsChecked).ToList();
            string ErrorMessage = null;

            foreach (var _temp in temp)
            {
                Mouse.OverrideCursor = Cursors.Wait;
                stopwatch.Start();
                try
                {
                    var tfile = TagLib.File.Create(Path.Combine(_temp.Path, _temp.Name));
                    tfile.RemoveTags((Enable_ID3v1 ? TagLib.TagTypes.None : TagLib.TagTypes.Id3v1) | (Enable_ID3v2 ? TagLib.TagTypes.None : TagLib.TagTypes.Id3v2));
                    TagLib.Id3v1.Tag t  = (TagLib.Id3v1.Tag)tfile.GetTag(TagLib.TagTypes.Id3v1, Enable_ID3v1 ? true : false);
                    TagLib.Id3v2.Tag t2 = (TagLib.Id3v2.Tag)tfile.GetTag(TagLib.TagTypes.Id3v2, Enable_ID3v2 ? true : false);
                    SetID3v2Encoding(Encoding_Output_ID3v2);
                    if (t != null)
                    {
                        var TagList = GetAllStringProperties(t);
                        var Dic     = TagList.ToDictionary(x => x.TagName, x => StringToUnicode.TryToConvertLatin1ToUnicode(x.Value, encoding[0]));
                        var resoult = ConvertEncoding ? await ConvertHelper.ConvertDictionary(Dic, encoding, ToChinese1) : await ConvertHelper.ConvertDictionary(Dic, ToChinese1);

                        resoult.ToList().ForEach(x => t.SetPropertiesValue(x.Key, Encoding.GetEncoding("ISO-8859-1").GetString(encoding[1].GetBytes(x.Value))));
                    }
                    if (t2 != null)
                    {
                        var TagList = GetAllStringProperties(t2);
                        var Dic     = TagList.ToDictionary(x => x.TagName, x =>
                        {
                            if (tfile.TagTypesOnDisk.HasFlag(TagLib.TagTypes.Id3v2))
                            {
                                return(StringToUnicode.TryToConvertLatin1ToUnicode(x.Value, encoding2[0]));
                            }
                            else
                            {
                                var _ = ID3v1_TagList.Where(y => y.TagName == x.TagName).FirstOrDefault();
                                return(_ != null ? _.Value_Preview : "");
                            }
                        });
                        var resoult = await ConvertHelper.ConvertDictionary(Dic, ToChinese2);

                        resoult.ToList().ForEach(x => t.SetPropertiesValue(x.Key, x.Value));
                        t2.Version = (Combobox_ID3v2_Version.Text == "2.3") ? (byte)3 : (byte)4;
                    }
                    tfile.Save();
                }
                catch (TagLib.UnsupportedFormatException) { ErrorMessage = string.Format("轉換{0}時出現錯誤,該檔案並非音訊檔", _temp.Name); }
                catch (FanhuajiException val)
                {
                    ErrorMessage = ((Exception)val).Message;
                    break;
                }
                catch { ErrorMessage = string.Format("轉換{0}時出現未知錯誤", _temp.Name); }
            }
            Mouse.OverrideCursor = null;
            stopwatch.Stop();
            if (!string.IsNullOrEmpty(ErrorMessage))
            {
                Window_MessageBoxEx.ShowDialog(ErrorMessage, "轉換過程中出現錯誤", "我知道了");
            }
            else if (App.Settings.Prompt)
            {
                new Toast(string.Format("轉換完成\r\n耗時:{0} ms", stopwatch.ElapsedMilliseconds)).Show();
            }
            ((Button)e.Source).IsEnabled = true;
            Listview_SelectionChanged(null, null);
        }
Esempio n. 20
0
        /// <summary>
        /// Save the Modified file
        /// </summary>
        /// <param name="track"></param>
        /// <param name="errorMessage"></param>
        /// <returns></returns>
        public static bool SaveFile(TrackData track, ref string errorMessage)
        {
            errorMessage = "";
            if (!track.Changed)
            {
                return(true);
            }

            if (track.Readonly && !Options.MainSettings.ChangeReadOnlyAttributte &&
                (Options.ReadOnlyFileHandling == 0 || Options.ReadOnlyFileHandling == 2))
            {
                Form         dlg       = new ReadOnlyDialog(track.FullFileName);
                DialogResult dlgResult = dlg.ShowDialog();

                switch (dlgResult)
                {
                case DialogResult.Yes:
                    Options.ReadOnlyFileHandling = 0; // Yes
                    break;

                case DialogResult.OK:
                    Options.ReadOnlyFileHandling = 1; // Yes to All
                    break;

                case DialogResult.No:
                    Options.ReadOnlyFileHandling = 2; // No
                    break;

                case DialogResult.Cancel:
                    Options.ReadOnlyFileHandling = 3; // No to All
                    break;
                }
            }

            if (track.Readonly)
            {
                if (!Options.MainSettings.ChangeReadOnlyAttributte && Options.ReadOnlyFileHandling > 1)
                {
                    errorMessage = "File is readonly";
                    return(false);
                }

                try
                {
                    System.IO.File.SetAttributes(track.FullFileName,
                                                 System.IO.File.GetAttributes(track.FullFileName) & ~FileAttributes.ReadOnly);

                    track.Readonly = false;
                }
                catch (Exception ex)
                {
                    log.Error("File Save: Can't reset Readonly attribute: {0} {1}", track.FullFileName, ex.Message);
                    errorMessage = ServiceScope.Get <ILocalisation>().ToString("message", "ErrorResetAttr");
                    return(false);
                }
            }

            TagLib.File file  = null;
            bool        error = false;

            try
            {
                TagLib.ByteVector.UseBrokenLatin1Behavior = true;
                file = TagLib.File.Create(track.FullFileName);
            }
            catch (CorruptFileException)
            {
                log.Warn("File Read: Ignoring track {0} - Corrupt File!", track.FullFileName);
                errorMessage = ServiceScope.Get <ILocalisation>().ToString("message", "CorruptFile");
                error        = true;
            }
            catch (UnsupportedFormatException)
            {
                log.Warn("File Read: Ignoring track {0} - Unsupported format!", track.FullFileName);
                errorMessage = ServiceScope.Get <ILocalisation>().ToString("message", "UnsupportedFormat");
                error        = true;
            }
            catch (FileNotFoundException)
            {
                log.Warn("File Read: Ignoring track {0} - Physical file no longer existing!", track.FullFileName);
                errorMessage = ServiceScope.Get <ILocalisation>().ToString("message", "NonExistingFile");
                error        = true;
            }
            catch (Exception ex)
            {
                log.Error("File Read: Error processing file: {0} {1}", track.FullFileName, ex.Message);
                errorMessage = string.Format(ServiceScope.Get <ILocalisation>().ToString("message", "ErrorReadingFile"), ex.Message);
                error        = true;
            }

            if (file == null || error)
            {
                log.Error("File Read: Error processing file.: {0}", track.FullFileName);
                return(false);
            }

            try
            {
                // Get the ID3 Frame for ID3 specifc frame handling
                TagLib.Id3v1.Tag id3v1tag = null;
                TagLib.Id3v2.Tag id3v2tag = null;
                if (track.IsMp3)
                {
                    id3v1tag = file.GetTag(TagTypes.Id3v1, true) as TagLib.Id3v1.Tag;
                    id3v2tag = file.GetTag(TagTypes.Id3v2, true) as TagLib.Id3v2.Tag;
                }

                // Remove Tags, if they have been removed in TagEdit Panel
                foreach (TagLib.TagTypes tagType in track.TagsRemoved)
                {
                    file.RemoveTags(tagType);
                }

                #region Main Tags
                string[] splitValues = track.Artist.Split(new[] { ';', '|' });
                file.Tag.Performers = splitValues;

                splitValues           = track.AlbumArtist.Split(new[] { ';', '|' });
                file.Tag.AlbumArtists = splitValues;

                file.Tag.Album          = track.Album.Trim();
                file.Tag.BeatsPerMinute = (uint)track.BPM;


                if (track.Comment != "")
                {
                    file.Tag.Comment = "";
                    if (track.IsMp3)
                    {
                        id3v1tag.Comment = track.Comment;
                        foreach (Comment comment in track.ID3Comments)
                        {
                            CommentsFrame commentsframe = CommentsFrame.Get(id3v2tag, comment.Description, comment.Language, true);
                            commentsframe.Text        = comment.Text;
                            commentsframe.Description = comment.Description;
                            commentsframe.Language    = comment.Language;
                        }
                    }
                    else
                    {
                        file.Tag.Comment = track.Comment;
                    }
                }
                else
                {
                    file.Tag.Comment = "";
                }

                if (track.IsMp3)
                {
                    id3v2tag.IsCompilation = track.Compilation;
                }

                file.Tag.Disc      = track.DiscNumber;
                file.Tag.DiscCount = track.DiscCount;

                splitValues     = track.Genre.Split(new[] { ';', '|' });
                file.Tag.Genres = splitValues;

                file.Tag.Title = track.Title;

                file.Tag.Track      = track.TrackNumber;
                file.Tag.TrackCount = track.TrackCount;

                file.Tag.Year = (uint)track.Year;

                file.Tag.ReplayGainTrack     = track.ReplayGainTrack;
                file.Tag.ReplayGainTrackPeak = track.ReplayGainTrackPeak;
                file.Tag.ReplayGainAlbum     = track.ReplayGainAlbum;
                file.Tag.ReplayGainAlbumPeak = track.ReplayGainAlbumPeak;

                #endregion

                #region Detailed Information

                splitValues        = track.Composer.Split(new[] { ';', '|' });
                file.Tag.Composers = splitValues;
                file.Tag.Conductor = track.Conductor;
                file.Tag.Copyright = track.Copyright;
                file.Tag.Grouping  = track.Grouping;

                splitValues               = track.ArtistSortName.Split(new[] { ';', '|' });
                file.Tag.PerformersSort   = splitValues;
                splitValues               = track.AlbumArtistSortName.Split(new[] { ';', '|' });
                file.Tag.AlbumArtistsSort = splitValues;
                file.Tag.AlbumSort        = track.AlbumSortName;
                file.Tag.TitleSort        = track.TitleSortName;

                #endregion

                #region Picture

                List <TagLib.Picture> pics = new List <TagLib.Picture>();
                foreach (Picture pic in track.Pictures)
                {
                    TagLib.Picture tagPic = new TagLib.Picture();

                    try
                    {
                        byte[]     byteArray = pic.Data;
                        ByteVector data      = new ByteVector(byteArray);
                        tagPic.Data        = data;
                        tagPic.Description = pic.Description;
                        tagPic.MimeType    = "image/jpg";
                        tagPic.Type        = pic.Type;
                        pics.Add(tagPic);
                    }
                    catch (Exception ex)
                    {
                        log.Error("Error saving Picture: {0}", ex.Message);
                    }

                    file.Tag.Pictures = pics.ToArray();
                }

                // Clear the picture
                if (track.Pictures.Count == 0)
                {
                    file.Tag.Pictures = pics.ToArray();
                }

                #endregion

                #region Lyrics

                if (track.Lyrics != null && track.Lyrics != "")
                {
                    file.Tag.Lyrics = track.Lyrics;
                    if (track.IsMp3)
                    {
                        foreach (Lyric lyric in track.LyricsFrames)
                        {
                            UnsynchronisedLyricsFrame lyricframe = UnsynchronisedLyricsFrame.Get(id3v2tag, lyric.Description, lyric.Language, true);
                            lyricframe.Text        = lyric.Text;
                            lyricframe.Description = lyric.Description;
                            lyricframe.Language    = lyric.Language;
                        }
                    }
                    else
                    {
                        file.Tag.Lyrics = track.Lyrics;
                    }
                }
                else
                {
                    file.Tag.Lyrics = "";
                }
                #endregion

                #region Ratings

                if (track.IsMp3)
                {
                    if (track.Ratings.Count > 0)
                    {
                        foreach (PopmFrame rating in track.Ratings)
                        {
                            PopularimeterFrame popmFrame = PopularimeterFrame.Get(id3v2tag, rating.User, true);
                            popmFrame.Rating    = Convert.ToByte(rating.Rating);
                            popmFrame.PlayCount = Convert.ToUInt32(rating.PlayCount);
                        }
                    }
                    else
                    {
                        id3v2tag.RemoveFrames("POPM");
                    }
                }
                else if (track.TagType == "ogg" || track.TagType == "flac")
                {
                    if (track.Ratings.Count > 0)
                    {
                        XiphComment xiph = file.GetTag(TagLib.TagTypes.Xiph, true) as XiphComment;
                        xiph.SetField("RATING", track.Rating.ToString());
                    }
                }

                #endregion

                #region Non- Standard Taglib and User Defined Frames

                if (Options.MainSettings.ClearUserFrames)
                {
                    foreach (Frame frame in track.UserFrames)
                    {
                        ByteVector frameId = new ByteVector(frame.Id);

                        if (frame.Id == "TXXX")
                        {
                            id3v2tag.SetUserTextAsString(frame.Description, "");
                        }
                        else
                        {
                            id3v2tag.SetTextFrame(frameId, "");
                        }
                    }
                }

                List <Frame> allFrames = new List <Frame>();
                allFrames.AddRange(track.Frames);

                // The only way to avoid duplicates of User Frames is to delete them by assigning blank values to them
                if (track.SavedUserFrames != null && !Options.MainSettings.ClearUserFrames)
                {
                    // Clean the previously saved Userframes, to avoid duplicates
                    foreach (Frame frame in track.SavedUserFrames)
                    {
                        ByteVector frameId = new ByteVector(frame.Id);

                        if (frame.Id == "TXXX")
                        {
                            id3v2tag.SetUserTextAsString(frame.Description, "");
                        }
                        else
                        {
                            id3v2tag.SetTextFrame(frameId, "");
                        }
                    }

                    allFrames.AddRange(track.UserFrames);
                }

                foreach (Frame frame in allFrames)
                {
                    ByteVector frameId = new ByteVector(frame.Id);

                    // The only way to avoid duplicates of User Frames is to delete them by assigning blank values to them
                    if (frame.Id == "TXXX")
                    {
                        if (frame.Description != "")
                        {
                            id3v2tag.SetUserTextAsString(frame.Description, "");
                            id3v2tag.SetUserTextAsString(frame.Description, frame.Value);
                        }
                    }
                    else
                    {
                        id3v2tag.SetTextFrame(frameId, "");
                        id3v2tag.SetTextFrame(frameId, frame.Value);
                    }
                }

                #endregion


                // Now, depending on which frames the user wants to save, we will remove the other Frames
                file = Util.FormatID3Tag(file);

                // Set the encoding for ID3 Tags
                if (track.IsMp3)
                {
                    TagLib.Id3v2.Tag.ForceDefaultEncoding = true;
                    switch (Options.MainSettings.CharacterEncoding)
                    {
                    case 0:
                        TagLib.Id3v2.Tag.DefaultEncoding = StringType.Latin1;
                        break;

                    case 1:
                        TagLib.Id3v2.Tag.DefaultEncoding = StringType.UTF16;
                        break;

                    case 2:
                        TagLib.Id3v2.Tag.DefaultEncoding = StringType.UTF16BE;
                        break;

                    case 3:
                        TagLib.Id3v2.Tag.DefaultEncoding = StringType.UTF8;
                        break;

                    case 4:
                        TagLib.Id3v2.Tag.DefaultEncoding = StringType.UTF16LE;
                        break;
                    }
                }

                // Save the file
                file.Save();
            }
            catch (Exception ex)
            {
                log.Error("File Save: Error processing file: {0} {1}", track.FullFileName, ex.Message);
                errorMessage = ServiceScope.Get <ILocalisation>().ToString("message", "ErrorSave");
                error        = true;
            }

            if (error)
            {
                return(false);
            }

            return(true);
        }
        /// <summary>
        ///    Reads a tag ending at a specified position and moves the
        ///    cursor to its start position.
        /// </summary>
        /// <param name="end">
        ///    A <see cref="long" /> value reference specifying at what
        ///    position the potential tag ends at. If a tag is found,
        ///    this value will be updated to the position at which the
        ///    found tag starts.
        /// </param>
        /// <returns>
        ///    A <see cref="TagLib.Tag" /> object representing the tag
        ///    found at the specified position, or <see langword="null"
        ///    /> if no tag was found.
        /// </returns>
        private TagLib.Tag ReadTag(ref long end)
        {
            long start = end;
            TagTypes type = ReadTagInfo (ref start);
            TagLib.Tag tag = null;

            try {
                switch (type)
                {
                case TagTypes.Ape:
                    tag = new TagLib.Ape.Tag (file, end - TagLib.Ape.Footer.Size);
                    break;
                case TagTypes.Id3v2:
                    tag = new TagLib.Id3v2.Tag (file, start);
                    break;
                case TagTypes.Id3v1:
                    tag = new TagLib.Id3v1.Tag (file, start);
                    break;
                }

                end = start;
            } catch (CorruptFileException) {
            }

            return tag;
        }
        /// <summary>
        ///    Adds a tag of a specified type to the current instance,
        ///    optionally copying values from an existing type.
        /// </summary>
        /// <param name="type">
        ///    A <see cref="TagTypes" /> value specifying the type of
        ///    tag to add to the current instance. At the time of this
        ///    writing, this is limited to <see cref="TagTypes.Ape" />,
        ///    <see cref="TagTypes.Id3v1" />, and <see
        ///    cref="TagTypes.Id3v2" />.
        /// </param>
        /// <param name="copy">
        ///    A <see cref="TagLib.Tag" /> to copy values from using
        ///    <see cref="TagLib.Tag.CopyTo" />, or <see
        ///    langword="null" /> if no tag is to be copied.
        /// </param>
        /// <returns>
        ///    The <see cref="TagLib.Tag" /> object added to the current
        ///    instance, or <see langword="null" /> if it couldn't be
        ///    created.
        /// </returns>
        /// <remarks>
        ///    ID3v2 tags are added at the end of the current instance,
        ///    while other tags are added to the beginning.
        /// </remarks>
        public TagLib.Tag AddTag(TagTypes type, TagLib.Tag copy)
        {
            TagLib.Tag tag = null;

            if (type == TagTypes.Id3v1) {
                tag = new TagLib.Id3v1.Tag ();
            } else if (type == TagTypes.Id3v2) {
                Id3v2.Tag tag32 = new Id3v2.Tag ();
                tag32.Version = 4;
                tag32.Flags |= Id3v2.HeaderFlags.FooterPresent;
                tag = tag32;
            } else if (type == TagTypes.Ape) {
                tag = new TagLib.Ape.Tag ();
            }

            if (tag != null) {
                if (copy != null)
                    copy.CopyTo (tag, true);

                if (type == TagTypes.Id3v1)
                    AddTag (tag);
                else
                    InsertTag (0, tag);
            }

            return tag;
        }
Esempio n. 23
0
        /// <summary>
        /// Save the Modified file
        /// </summary>
        /// <param name="song"></param>
        /// <param name="errorMessage"></param>
        /// <returns></returns>
        public static bool SaveFile(SongData song, ref string errorMessage)
        {
            errorMessage = "";
            if (!song.Changed)
            {
                return(true);
            }

            var options = (ServiceLocator.Current.GetInstance(typeof(ISettingsManager)) as ISettingsManager)?.GetOptions;

            /*
             * if (song.Readonly && !options.MainSettings.ChangeReadOnlyAttributte &&
             *    (options.ReadOnlyFileHandling == 0 || options.ReadOnlyFileHandling == 2))
             * {
             * Form dlg = new ReadOnlyDialog(song.FullFileName);
             * DialogResult dlgResult = dlg.ShowDialog();
             *
             * switch (dlgResult)
             * {
             *  case DialogResult.Yes:
             *    options.ReadOnlyFileHandling = 0; // Yes
             *    break;
             *
             *  case DialogResult.OK:
             *    options.ReadOnlyFileHandling = 1; // Yes to All
             *    break;
             *
             *  case DialogResult.No:
             *    options.ReadOnlyFileHandling = 2; // No
             *    break;
             *
             *  case DialogResult.Cancel:
             *    options.ReadOnlyFileHandling = 3; // No to All
             *    break;
             * }
             * }
             */

            if (song.Readonly)
            {
                if (!options.MainSettings.ChangeReadOnlyAttribute && options.ReadOnlyFileHandling > 1)
                {
                    errorMessage = "File is readonly";
                    return(false);
                }

                try
                {
                    System.IO.File.SetAttributes(song.FullFileName,
                                                 System.IO.File.GetAttributes(song.FullFileName) & ~FileAttributes.ReadOnly);

                    song.Readonly = false;
                }
                catch (Exception ex)
                {
                    log.Error($"File Save: Can't reset Readonly attribute: {song.FullFileName} {ex.Message}");
                    errorMessage = LocalizeDictionary.Instance.GetLocalizedObject("MPTagThat", "Strings", "message_ErrorResetAttr",
                                                                                  LocalizeDictionary.Instance.Culture).ToString();
                    return(false);
                }
            }

            TagLib.File file  = null;
            bool        error = false;

            try
            {
                TagLib.ByteVector.UseBrokenLatin1Behavior = true;
                file = TagLib.File.Create(song.FullFileName);
            }
            catch (CorruptFileException)
            {
                log.Warn($"File Read: Ignoring song {song.FullFileName} - Corrupt File!");
                errorMessage = LocalizeDictionary.Instance.GetLocalizedObject("MPTagThat", "Strings", "message_CorruptFile",
                                                                              LocalizeDictionary.Instance.Culture).ToString();
                error = true;
            }
            catch (UnsupportedFormatException)
            {
                log.Warn($"File Read: Ignoring song {song.FullFileName} - Unsupported format!");
                errorMessage = LocalizeDictionary.Instance.GetLocalizedObject("MPTagThat", "Strings", "message_UnsupportedFormat",
                                                                              LocalizeDictionary.Instance.Culture).ToString();
                error = true;
            }
            catch (FileNotFoundException)
            {
                log.Warn($"File Read: Ignoring song {song.FullFileName} - Physical file no longer existing!");
                errorMessage = LocalizeDictionary.Instance.GetLocalizedObject("MPTagThat", "Strings", "message_NonExistingFile",
                                                                              LocalizeDictionary.Instance.Culture).ToString();
                error = true;
            }
            catch (Exception ex)
            {
                log.Error($"File Read: Error processing file: {song.FullFileName} {ex.Message}");
                errorMessage = string.Format(LocalizeDictionary.Instance.GetLocalizedObject("MPTagThat", "Strings", "message_ErrorReadingFile",
                                                                                            LocalizeDictionary.Instance.Culture).ToString(), song.FullFileName);
                error = true;
            }

            if (file == null || error)
            {
                log.Error("File Read: Error processing file.: {0}", song.FullFileName);
                return(false);
            }

            try
            {
                // Get the ID3 Frame for ID3 specifc frame handling
                TagLib.Id3v1.Tag id3v1tag = null;
                TagLib.Id3v2.Tag id3v2tag = null;
                if (song.IsMp3)
                {
                    id3v1tag = file.GetTag(TagTypes.Id3v1, true) as TagLib.Id3v1.Tag;
                    id3v2tag = file.GetTag(TagTypes.Id3v2, true) as TagLib.Id3v2.Tag;
                }

                // Remove Tags, if they have been removed in TagEdit Panel
                foreach (TagLib.TagTypes tagType in song.TagsRemoved)
                {
                    file.RemoveTags(tagType);
                }


                if (file.Tag != null)
                {
                    #region Main Tags

                    string[] splitValues = song.Artist.Split(new[] { ';', '|' });
                    file.Tag.Performers = splitValues;

                    splitValues           = song.AlbumArtist.Split(new[] { ';', '|' });
                    file.Tag.AlbumArtists = splitValues;

                    file.Tag.Album          = song.Album.Trim();
                    file.Tag.BeatsPerMinute = (uint)song.BPM;


                    if (song.Comment != "")
                    {
                        file.Tag.Comment = "";
                        if (song.IsMp3)
                        {
                            id3v1tag.Comment = song.Comment;
                            foreach (Comment comment in song.ID3Comments)
                            {
                                CommentsFrame commentsframe = CommentsFrame.Get(id3v2tag, comment.Description, comment.Language, true);
                                commentsframe.Text        = comment.Text;
                                commentsframe.Description = comment.Description;
                                commentsframe.Language    = comment.Language;
                            }
                        }
                        else
                        {
                            file.Tag.Comment = song.Comment;
                        }
                    }
                    else
                    {
                        if (song.IsMp3 && id3v2tag != null)
                        {
                            id3v2tag.RemoveFrames("COMM");
                        }
                        else
                        {
                            file.Tag.Comment = "";
                        }
                    }

                    if (song.IsMp3)
                    {
                        id3v2tag.IsCompilation = song.Compilation;
                    }

                    file.Tag.Disc      = song.DiscNumber;
                    file.Tag.DiscCount = song.DiscCount;

                    splitValues     = song.Genre.Split(new[] { ';', '|' });
                    file.Tag.Genres = splitValues;

                    file.Tag.Title = song.Title;

                    file.Tag.Track      = song.TrackNumber;
                    file.Tag.TrackCount = song.TrackCount;

                    file.Tag.Year = (uint)song.Year;

                    double gain;
                    var    replayGainTrack = string.IsNullOrEmpty(song.ReplayGainTrack) ? "" : song.ReplayGainTrack.Substring(0, song.ReplayGainTrack.IndexOf(" ", StringComparison.Ordinal));
                    if (double.TryParse(replayGainTrack, NumberStyles.Any, CultureInfo.InvariantCulture, out gain))
                    {
                        file.Tag.ReplayGainTrackGain = gain;
                    }
                    if (Double.TryParse(song.ReplayGainTrackPeak, NumberStyles.Any, CultureInfo.InvariantCulture, out gain))
                    {
                        file.Tag.ReplayGainTrackPeak = gain;
                    }
                    var replayGainAlbum = string.IsNullOrEmpty(song.ReplayGainAlbum) ? "" : song.ReplayGainAlbum.Substring(0, song.ReplayGainAlbum.IndexOf(" ", StringComparison.Ordinal));
                    if (Double.TryParse(replayGainAlbum, NumberStyles.Any, CultureInfo.InvariantCulture, out gain))
                    {
                        file.Tag.ReplayGainAlbumGain = gain;
                    }
                    if (Double.TryParse(song.ReplayGainAlbumPeak, NumberStyles.Any, CultureInfo.InvariantCulture, out gain))
                    {
                        file.Tag.ReplayGainAlbumPeak = gain;
                    }

                    #endregion

                    #region MusicBrainz

                    file.Tag.MusicBrainzArtistId        = song.MusicBrainzArtistId;
                    file.Tag.MusicBrainzDiscId          = song.MusicBrainzDiscId;
                    file.Tag.MusicBrainzReleaseArtistId = song.MusicBrainzReleaseArtistId;
                    file.Tag.MusicBrainzReleaseCountry  = song.MusicBrainzReleaseCountry;
                    file.Tag.MusicBrainzReleaseGroupId  = song.MusicBrainzReleaseGroupId;
                    file.Tag.MusicBrainzReleaseId       = song.MusicBrainzReleaseId;
                    file.Tag.MusicBrainzReleaseStatus   = song.MusicBrainzReleaseStatus;
                    file.Tag.MusicBrainzTrackId         = song.MusicBrainzTrackId;
                    file.Tag.MusicBrainzReleaseType     = song.MusicBrainzReleaseType;

                    #endregion

                    #region Detailed Information

                    splitValues        = song.Composer.Split(new[] { ';', '|' });
                    file.Tag.Composers = splitValues;
                    file.Tag.Conductor = song.Conductor;
                    file.Tag.Copyright = song.Copyright;
                    file.Tag.Grouping  = song.Grouping;

                    splitValues               = song.ArtistSortName.Split(new[] { ';', '|' });
                    file.Tag.PerformersSort   = splitValues;
                    splitValues               = song.AlbumArtistSortName.Split(new[] { ';', '|' });
                    file.Tag.AlbumArtistsSort = splitValues;
                    file.Tag.AlbumSort        = song.AlbumSortName;
                    file.Tag.TitleSort        = song.TitleSortName;

                    #endregion

                    #region Picture

                    List <TagLib.Picture> pics = new List <TagLib.Picture>();
                    foreach (Picture pic in song.Pictures)
                    {
                        TagLib.Picture tagPic = new TagLib.Picture();

                        try
                        {
                            byte[]     byteArray = pic.Data;
                            ByteVector data      = new ByteVector(byteArray);
                            tagPic.Data        = data;
                            tagPic.Description = pic.Description;
                            tagPic.MimeType    = "image/jpg";
                            tagPic.Type        = pic.Type;
                            pics.Add(tagPic);
                        }
                        catch (Exception ex)
                        {
                            log.Error("Error saving Picture: {0}", ex.Message);
                        }

                        file.Tag.Pictures = pics.ToArray();
                    }

                    // Clear the picture
                    if (song.Pictures.Count == 0)
                    {
                        file.Tag.Pictures = pics.ToArray();
                    }

                    #endregion

                    #region Lyrics

                    if (song.Lyrics != null && song.Lyrics != "")
                    {
                        file.Tag.Lyrics = song.Lyrics;
                        if (song.IsMp3)
                        {
                            id3v2tag.RemoveFrames("USLT");
                            foreach (Lyric lyric in song.LyricsFrames)
                            {
                                UnsynchronisedLyricsFrame lyricframe = UnsynchronisedLyricsFrame.Get(id3v2tag, lyric.Description,
                                                                                                     lyric.Language, true);
                                lyricframe.Text        = lyric.Text;
                                lyricframe.Description = lyric.Description;
                                lyricframe.Language    = lyric.Language;
                            }
                        }
                        else
                        {
                            file.Tag.Lyrics = song.Lyrics;
                        }
                    }
                    else
                    {
                        file.Tag.Lyrics = "";
                    }

                    #endregion

                    #region Ratings

                    if (song.IsMp3)
                    {
                        id3v2tag.RemoveFrames("POPM");
                        if (song.Ratings.Count > 0)
                        {
                            foreach (PopmFrame rating in song.Ratings)
                            {
                                PopularimeterFrame popmFrame = PopularimeterFrame.Get(id3v2tag, rating.User, true);
                                popmFrame.Rating    = Convert.ToByte(rating.Rating);
                                popmFrame.PlayCount = Convert.ToUInt32(rating.PlayCount);
                            }
                        }
                    }
                    else if (song.TagType == "ogg" || song.TagType == "flac")
                    {
                        if (song.Ratings.Count > 0)
                        {
                            XiphComment xiph = file.GetTag(TagLib.TagTypes.Xiph, true) as XiphComment;
                            xiph.SetField("RATING", song.Rating.ToString());
                        }
                    }

                    #endregion

                    #region Non- Standard Taglib and User Defined Frames

                    if (options.MainSettings.ClearUserFrames)
                    {
                        foreach (Frame frame in song.UserFrames)
                        {
                            ByteVector frameId = new ByteVector(frame.Id);

                            if (frame.Id == "TXXX")
                            {
                                id3v2tag.SetUserTextAsString(frame.Description, "", true);
                            }
                            else
                            {
                                id3v2tag.SetTextFrame(frameId, "");
                            }
                        }
                    }

                    List <Frame> allFrames = new List <Frame>();
                    allFrames.AddRange(song.Frames);

                    // The only way to avoid duplicates of User Frames is to delete them by assigning blank values to them
                    if (song.SavedUserFrames != null && !options.MainSettings.ClearUserFrames)
                    {
                        // Clean the previously saved Userframes, to avoid duplicates
                        foreach (Frame frame in song.SavedUserFrames)
                        {
                            ByteVector frameId = new ByteVector(frame.Id);

                            if (frame.Id == "TXXX")
                            {
                                id3v2tag.SetUserTextAsString(frame.Description, "", true);
                            }
                            else
                            {
                                id3v2tag.SetTextFrame(frameId, "");
                            }
                        }

                        allFrames.AddRange(song.UserFrames);
                    }

                    foreach (Frame frame in allFrames)
                    {
                        ByteVector frameId = new ByteVector(frame.Id);

                        // The only way to avoid duplicates of User Frames is to delete them by assigning blank values to them
                        if (frame.Id == "TXXX")
                        {
                            if (frame.Description != "")
                            {
                                id3v2tag.SetUserTextAsString(frame.Description, "", true);
                                id3v2tag.SetUserTextAsString(frame.Description, frame.Value, true);
                            }
                        }
                        else
                        {
                            id3v2tag.SetTextFrame(frameId, "");
                            id3v2tag.SetTextFrame(frameId, frame.Value);
                        }
                    }

                    #endregion


                    // Now, depending on which frames the user wants to save, we will remove the other Frames
                    file = Util.FormatID3Tag(file);

                    // Set the encoding for ID3 Tags
                    if (song.IsMp3)
                    {
                        TagLib.Id3v2.Tag.ForceDefaultEncoding = true;
                        switch (options.MainSettings.CharacterEncoding)
                        {
                        case "Latin1":
                            TagLib.Id3v2.Tag.DefaultEncoding = StringType.Latin1;
                            break;

                        case "UTF16":
                            TagLib.Id3v2.Tag.DefaultEncoding = StringType.UTF16;
                            break;

                        case "UTF16-BE":
                            TagLib.Id3v2.Tag.DefaultEncoding = StringType.UTF16BE;
                            break;

                        case "UTF8":
                            TagLib.Id3v2.Tag.DefaultEncoding = StringType.UTF8;
                            break;

                        case "UTF16-LE":
                            TagLib.Id3v2.Tag.DefaultEncoding = StringType.UTF16LE;
                            break;
                        }
                    }
                }
                // Save the file
                file.Save();
            }
            catch (Exception ex)
            {
                log.Error("File Save: Error processing file: {0} {1}", song.FullFileName, ex.Message);
                errorMessage = string.Format(LocalizeDictionary.Instance.GetLocalizedObject("MPTagThat", "Strings", "message_ErrorSave",
                                                                                            LocalizeDictionary.Instance.Culture).ToString(), song.FullFileName);
                error = true;
            }

            if (error)
            {
                return(false);
            }

            return(true);
        }
Esempio n. 24
0
        /// <summary>
        /// init item
        /// </summary>
        public bool IntializeItem()
        {
            try
            {
                tag_file = TagLib.File.Create(fi.FullName);
                v1       = tag_file.GetTag(TagLib.TagTypes.Id3v1) as TagLib.Id3v1.Tag;
                v2       = tag_file.GetTag(TagLib.TagTypes.Id3v2) as TagLib.Id3v2.Tag;
            }
            catch (TagLib.CorruptFileException e)
            {
                // BKP todo
                // humm, what shall we do? log?
                System.Diagnostics.Trace.WriteLine(e.Message);
                return(false);
            }

            Win32.SHFILEINFO sInfo = new OS.Win32.Win32.SHFILEINFO();
            // Use this to get the small Icon
            IntPtr handle = Win32.SHGetFileInfo(fi.FullName, 0, ref sInfo, (uint)Marshal.SizeOf(sInfo),
                                                Win32.SHGFI_ICON | Win32.SHGFI_SMALLICON);

            if (lv.SmallImageList.Images.ContainsKey(sInfo.dwAttributes.ToString()) != true)
            {
                // The icon is returned in the hIcon member of the shinfo struct
                System.Drawing.Icon icon = System.Drawing.Icon.FromHandle(sInfo.hIcon);
                lv.SmallImageList.Images.Add(sInfo.dwAttributes.ToString(), icon);
            }
            this.ImageIndex = lv.SmallImageList.Images.IndexOfKey(sInfo.dwAttributes.ToString());

            Dictionary <Column, Column> tmp_items = new Dictionary <Column, Column>();

            // fill dictionary with all values
            foreach (Column c in Enum.GetValues(typeof(Column)))
            {
                tmp_items.Add(c, c);
            }
            // add configured, then remove
            foreach (ColumnHeader header in lv.Columns)
            {
                if (header.Text == "File")
                {
                    continue;
                }
                Column key = (Column)Enum.Parse(typeof(Column), header.Text);
                string val = GetString(key);
                ListViewItem.ListViewSubItem sub_item = new ListViewItem.ListViewSubItem(this, val);
                sub_item.Name = key.ToString();
                this.SubItems.Add(sub_item);
                tmp_items.Remove(key);
            }
            // add the leftovers
            foreach (Column key in tmp_items.Keys)
            {
                if (key == Column.File)
                {
                    continue;
                }
                string val = GetString(key);
                ListViewItem.ListViewSubItem sub_item = new ListViewItem.ListViewSubItem(this, val);
                sub_item.Name = key.ToString();
                this.SubItems.Add(sub_item);
            }

            return(true);
        }
Esempio n. 25
0
        private void Button_Convert_Click(object sender, RoutedEventArgs e)
        {
            ((Button)e.Source).IsEnabled = false;
            Stopwatch stopwatch = new Stopwatch();

            stopwatch.Start();

            var temp = FileList.Where(x => x.IsChecked).ToList();

            foreach (var _temp in temp)
            {
                Mouse.OverrideCursor = Cursors.Wait;
                stopwatch.Start();
                switch (Encoding_Output_ID3v2)
                {
                case "UTF-8":
                    TagLib.Id3v2.Tag.DefaultEncoding = TagLib.StringType.UTF8;
                    break;

                case "UTF-16":
                    TagLib.Id3v2.Tag.DefaultEncoding = TagLib.StringType.UTF16;
                    break;

                case "UTF-16BE":
                    TagLib.Id3v2.Tag.DefaultEncoding = TagLib.StringType.UTF16BE;
                    break;

                case "UTF-16LE":
                    TagLib.Id3v2.Tag.DefaultEncoding = TagLib.StringType.UTF16LE;
                    break;
                }
                try
                {
                    var tfile = TagLib.File.Create(Path.Combine(_temp.Path, _temp.Name));
                    tfile.RemoveTags((Enable_ID3v1 ? TagLib.TagTypes.None : TagLib.TagTypes.Id3v1) | (Enable_ID3v2 ? TagLib.TagTypes.None : TagLib.TagTypes.Id3v2));
                    TagLib.Id3v1.Tag t  = (TagLib.Id3v1.Tag)tfile.GetTag(TagLib.TagTypes.Id3v1);
                    TagLib.Id3v2.Tag t2 = (TagLib.Id3v2.Tag)tfile.GetTag(TagLib.TagTypes.Id3v2, Enable_ID3v1 ? true : false);

                    GetAllStringProperties(t).ForEach(x =>
                    {
                        x.Value         = encoding[1].GetString(Encoding.GetEncoding("ISO-8859-1").GetBytes(x.Value));
                        x.Value_Preview = ConvertHelper.Convert(x.Value, encoding, ToChinese1);
                        SetPropertiesValue(t, x.TagName, Encoding.GetEncoding("ISO-8859-1").GetString(encoding[1].GetBytes(x.Value_Preview)));
                    });

                    GetAllStringProperties(t2).ForEach(x =>
                    {
                        x.Value_Preview = ConvertHelper.Convert(x.Value, ToChinese2);
                        SetPropertiesValue(t2, x.TagName, x.Value_Preview);
                    });
                    t2.Version = (Combobox_ID3v2_Version.Text == "2.3") ? (byte)3 : (byte)4;
                    tfile.Save();
                }
                catch (TagLib.UnsupportedFormatException) { MessageBox.Show(string.Format("轉換{0}時出現錯誤,該檔案並非音訊檔", _temp.Name)); }
                catch { MessageBox.Show(string.Format("轉換{0}時出現未知錯誤", _temp.Name)); }
                Mouse.OverrideCursor = null;
            }

            stopwatch.Stop();
            if (App.Settings.Prompt)
            {
                MessageBox.Show(string.Format("轉換完成\r\n耗時:{0} ms", stopwatch.ElapsedMilliseconds));
            }
            ((Button)e.Source).IsEnabled = true;
            Listview_SelectionChanged(null, null);
        }
Esempio n. 26
0
        public static MusicFileTag ConvertTagToMusicFileTag(TagLib.Id3v1.Tag tagV1, TagLib.Id3v2.Tag tagV2, string filePath)
        {
            var tmp = new MusicFileTag
            {
                // File Details
                FilePath = filePath,
                FileName = Path.GetFileName(filePath),
                FileSize = Logic.BasicFunctions.FormatFileSize(new FileInfo(filePath).Length),
            };

            // TagTypes
            TagTypes myTagTypes = TagLib.File.Create(filePath).TagTypesOnDisk;

            tmp.EnabledV1 = myTagTypes.ToString().ToLower().Contains("id3v1") ? true : false;
            tmp.EnabledV2 = myTagTypes.ToString().ToLower().Contains("id3v2") ? true : false;

            // V1
            if (tmp.EnabledV1)
            {
                tmp.ArtistV1  = tagV1.FirstPerformer == null ? "" : tagV1.FirstPerformer.Replace("�", string.Empty);
                tmp.AlbumV1   = tagV1.Album == null ? "" : tagV1.Album.Replace("�", string.Empty);
                tmp.GenreV1   = tagV1.FirstGenre == null ? "" : tagV1.FirstGenre.Replace("�", string.Empty);
                tmp.YearV1    = tagV1.Year.ToString() == null ? "" : tagV1.Year.ToString().Replace("�", string.Empty);
                tmp.TitleV1   = tagV1.Title == null ? "" : tagV1.Title.Replace("�", string.Empty);
                tmp.CommentV1 = tagV1.Comment == null ? "" : tagV1.Comment.Replace("�", string.Empty);
                tmp.TrackV1   = tagV1.Track.ToString() == null ? "" : tagV1.Track.ToString().Replace("�", string.Empty);
            }

            // V2
            if (tmp.EnabledV2)
            {
                tmp.VersionV2 = tagV2.Version.ToString();

                // Version 3
                tmp.PlayListDelayV2      = Logic.TaggingLogic.GetTagContent(tagV2, "TDLY").Replace("�", string.Empty);
                tmp.TrackNumberV2        = Logic.TaggingLogic.GetTagContent(tagV2, "TRCK").Replace("�", string.Empty);
                tmp.PartOfSetV2          = Logic.TaggingLogic.GetTagContent(tagV2, "TPOS").Replace("�", string.Empty);
                tmp.BPMV2                = Logic.TaggingLogic.GetTagContent(tagV2, "TBPM").Replace("�", string.Empty);
                tmp.ArtistV2             = Logic.TaggingLogic.GetTagContent(tagV2, "TPE1").Replace("�", string.Empty);
                tmp.GenreV2              = Logic.TaggingLogic.GetTagContent(tagV2, "TCON").Replace("�", string.Empty);
                tmp.LanguageV2           = Logic.TaggingLogic.GetTagContent(tagV2, "TLAN").Replace("�", string.Empty);
                tmp.KeyV2                = Logic.TaggingLogic.GetTagContent(tagV2, "TKEY").Replace("�", string.Empty);
                tmp.SetSubtitleV2        = Logic.TaggingLogic.GetTagContent(tagV2, "TSST").Replace("�", string.Empty);
                tmp.ContentDescriptionV2 = Logic.TaggingLogic.GetTagContent(tagV2, "TIT1").Replace("�", string.Empty);
                tmp.InterpretedV2        = Logic.TaggingLogic.GetTagContent(tagV2, "TPE4").Replace("�", string.Empty);
                tmp.AlbumV2              = Logic.TaggingLogic.GetTagContent(tagV2, "TALB").Replace("�", string.Empty);
                tmp.TitleV2              = Logic.TaggingLogic.GetTagContent(tagV2, "TIT2").Replace("�", string.Empty);

                /// Frames from
                /// http://id3.org/id3v2.3.0#Declared_ID3v2_frames

                // + Version 4
                if (tagV2.Version == 4)
                {
                    tmp.TitleSortV2 = Logic.TaggingLogic.GetTagContent(tagV2, "TSOT").Replace("�", string.Empty);
                    tmp.AlbumSortV2 = Logic.TaggingLogic.GetTagContent(tagV2, "TSOA").Replace("�", string.Empty);
                    tmp.MoodV2      = Logic.TaggingLogic.GetTagContent(tagV2, "TMOO").Replace("�", string.Empty);
                    tmp.SubtitleV2  = Logic.TaggingLogic.GetTagContent(tagV2, "TIT3").Replace("�", string.Empty);
                }
            }
            else
            {
                tmp.VersionV2 = "4";
            }

            return(tmp);
        }
Esempio n. 27
0
        private void Preview(string path)
        {
            if (!File.Exists(path))
            {
                return;
            }
            try
            {
                var tfile           = TagLib.File.Create(path, TagLib.ReadStyle.None);
                TagLib.Id3v1.Tag t  = (TagLib.Id3v1.Tag)tfile.GetTag(TagLib.TagTypes.Id3v1);
                TagLib.Id3v2.Tag t2 = (TagLib.Id3v2.Tag)tfile.GetTag(TagLib.TagTypes.Id3v2);

                ID3v1_TagList.Clear();
                ID3v2_TagList.Clear();

                GetAllStringProperties(t).ForEach(x =>
                {
                    x.Value         = StringToUnicode.TryToConvertLatin1ToUnicode(x.Value, encoding[0]);
                    x.Value_Preview = ConvertEncoding ? ConvertHelper.Convert(x.Value, encoding, ToChinese1) : ConvertHelper.Convert(x.Value, ToChinese1);
                    ID3v1_TagList.Add(x);
                });

                GetAllStringProperties(t2).ForEach(x =>
                {
                    if (tfile.TagTypesOnDisk.HasFlag(TagLib.TagTypes.Id3v2))
                    {
                        x.Value = StringToUnicode.TryToConvertLatin1ToUnicode(x.Value, encoding2[0]);
                    }
                    else
                    {
                        var _   = ID3v1_TagList.Where(y => y.TagName == x.TagName).FirstOrDefault();
                        x.Value = _ != null ? _.Value_Preview : "";
                    }
                    x.Value_Preview = ConvertHelper.Convert(x.Value, ToChinese2);
                    ID3v2_TagList.Add(x);
                });
            }
            catch (TagLib.UnsupportedFormatException)
            {
                ID3v1_TagList.Clear();
                ID3v2_TagList.Clear();
                ID3v1_TagList.Add(new TagList_Line()
                {
                    TagName = "Error", Value = "非音訊檔"
                });
                ID3v2_TagList.Add(new TagList_Line()
                {
                    TagName = "Error", Value = "非音訊檔"
                });
            }
            catch (System.Exception)
            {
                ID3v1_TagList.Clear();
                ID3v2_TagList.Clear();
                ID3v1_TagList.Add(new TagList_Line()
                {
                    TagName = "Error", Value = "未知"
                });
                ID3v2_TagList.Add(new TagList_Line()
                {
                    TagName = "Error", Value = "未知"
                });
            }
        }
Esempio n. 28
0
        private void Button_Convert_Click(object sender, RoutedEventArgs e)
        {
            ((Button)e.Source).IsEnabled = false;
            Stopwatch stopwatch = new Stopwatch();

            stopwatch.Start();

            var temp = FileList.Where(x => x.IsChecked).ToList();

            foreach (var _temp in temp)
            {
                Mouse.OverrideCursor = Cursors.Wait;
                stopwatch.Start();
                try
                {
                    var tfile = TagLib.File.Create(Path.Combine(_temp.Path, _temp.Name));
                    tfile.RemoveTags((Enable_ID3v1 ? TagLib.TagTypes.None : TagLib.TagTypes.Id3v1) | (Enable_ID3v2 ? TagLib.TagTypes.None : TagLib.TagTypes.Id3v2));
                    TagLib.Id3v1.Tag t  = (TagLib.Id3v1.Tag)tfile.GetTag(TagLib.TagTypes.Id3v1, Enable_ID3v1 ? true : false);
                    TagLib.Id3v2.Tag t2 = (TagLib.Id3v2.Tag)tfile.GetTag(TagLib.TagTypes.Id3v2, Enable_ID3v2 ? true : false);
                    SetID3v2Encoding(Encoding_Output_ID3v2);
                    if (t != null)
                    {
                        GetAllStringProperties(t).ForEach(x =>
                        {
                            x.Value         = StringToUnicode.TryToConvertLatin1ToUnicode(x.Value, encoding[0]);
                            x.Value_Preview = ConvertEncoding ? ConvertHelper.Convert(x.Value, encoding, ToChinese1) : ConvertHelper.Convert(x.Value, ToChinese1);
                            t.SetPropertiesValue(x.TagName, Encoding.GetEncoding("ISO-8859-1").GetString(encoding[1].GetBytes(x.Value_Preview)));
                        });
                    }
                    if (t2 != null)
                    {
                        GetAllStringProperties(t2).ForEach(x =>
                        {
                            if (tfile.TagTypesOnDisk.HasFlag(TagLib.TagTypes.Id3v2))
                            {
                                x.Value = StringToUnicode.TryToConvertLatin1ToUnicode(x.Value, encoding2[0]);
                            }
                            else
                            {
                                var _   = ID3v1_TagList.Where(y => y.TagName == x.TagName).FirstOrDefault();
                                x.Value = _ != null ? _.Value_Preview : "";
                            }
                            x.Value_Preview = ConvertHelper.Convert(x.Value, ToChinese2);
                            t2.SetPropertiesValue(x.TagName, x.Value_Preview);
                        });
                        t2.Version = (Combobox_ID3v2_Version.Text == "2.3") ? (byte)3 : (byte)4;
                    }
                    tfile.Save();
                }
                catch (TagLib.UnsupportedFormatException) { MessageBox.Show(string.Format("轉換{0}時出現錯誤,該檔案並非音訊檔", _temp.Name)); }
                catch { MessageBox.Show(string.Format("轉換{0}時出現未知錯誤", _temp.Name)); }
            }
            Mouse.OverrideCursor = null;
            stopwatch.Stop();
            if (App.Settings.Prompt)
            {
                new Toast(string.Format("轉換完成\r\n耗時:{0} ms", stopwatch.ElapsedMilliseconds)).Show();
            }
            ((Button)e.Source).IsEnabled = true;
            Listview_SelectionChanged(null, null);
        }
Esempio n. 29
0
        private async void Preview(string path)
        {
            if (!File.Exists(path))
            {
                return;
            }
            try
            {
                var tfile           = TagLib.File.Create(path, TagLib.ReadStyle.None);
                TagLib.Id3v1.Tag t  = (TagLib.Id3v1.Tag)tfile.GetTag(TagLib.TagTypes.Id3v1);
                TagLib.Id3v2.Tag t2 = (TagLib.Id3v2.Tag)tfile.GetTag(TagLib.TagTypes.Id3v2);

                ID3v1_TagList.Clear();
                ID3v2_TagList.Clear();

                var TagList = GetAllStringProperties(t);
                TagList.ForEach(x => x.Value = StringToUnicode.TryToConvertLatin1ToUnicode(x.Value, encoding[0]));
                var Dic     = TagList.ToDictionary(x => x.TagName, x => x.Value);
                var resoult = ConvertEncoding ? await ConvertHelper.ConvertDictionary(Dic, encoding, ToChinese1) : await ConvertHelper.ConvertDictionary(Dic, ToChinese1);

                TagList.ForEach(x =>
                {
                    x.Value_Preview = resoult[x.TagName];
                    ID3v1_TagList.Add(x);
                });


                TagList = GetAllStringProperties(t2);
                Dic     = TagList.ToDictionary(x => x.TagName, x =>
                {
                    if (tfile.TagTypesOnDisk.HasFlag(TagLib.TagTypes.Id3v2))
                    {
                        return(StringToUnicode.TryToConvertLatin1ToUnicode(x.Value, encoding2[0]));
                    }
                    else
                    {
                        var _ = ID3v1_TagList.Where(y => y.TagName == x.TagName).FirstOrDefault();
                        return(_ != null ? _.Value_Preview : "");
                    }
                });
                resoult = await ConvertHelper.ConvertDictionary(Dic, ToChinese2);

                TagList.ForEach(x =>
                {
                    x.Value_Preview = resoult[x.TagName];
                    ID3v2_TagList.Add(x);
                });
            }
            catch (TagLib.UnsupportedFormatException)
            {
                ID3v1_TagList.Clear();
                ID3v2_TagList.Clear();
                ID3v1_TagList.Add(new TagList_Line()
                {
                    TagName = "Error", Value = "非音訊檔"
                });
                ID3v2_TagList.Add(new TagList_Line()
                {
                    TagName = "Error", Value = "非音訊檔"
                });
            }
            catch (FanhuajiException val)
            {
                ID3v1_TagList.Clear();
                ID3v2_TagList.Clear();
                ID3v1_TagList.Add(new TagList_Line
                {
                    TagName = "Error",
                    Value   = val.Message
                });
                ID3v2_TagList.Add(new TagList_Line
                {
                    TagName = "Error",
                    Value   = val.Message
                });
            }
            catch (System.Exception)
            {
                ID3v1_TagList.Clear();
                ID3v2_TagList.Clear();
                ID3v1_TagList.Add(new TagList_Line()
                {
                    TagName = "Error", Value = "未知"
                });
                ID3v2_TagList.Add(new TagList_Line()
                {
                    TagName = "Error", Value = "未知"
                });
            }
        }