From 9856f52070ec8a837f20016690ade738f34c88ce Mon Sep 17 00:00:00 2001 From: Unlock Music Dev Date: Mon, 28 Nov 2022 18:52:19 +0800 Subject: [PATCH] feat: add meta parser from filename --- algo/common/meta.go | 50 ++++++++++++++++++++++++++++++++++++++++ algo/common/meta_test.go | 38 ++++++++++++++++++++++++++++++ 2 files changed, 88 insertions(+) create mode 100644 algo/common/meta.go create mode 100644 algo/common/meta_test.go diff --git a/algo/common/meta.go b/algo/common/meta.go new file mode 100644 index 0000000..8c174dc --- /dev/null +++ b/algo/common/meta.go @@ -0,0 +1,50 @@ +package common + +import ( + "path" + "strings" +) + +type filenameMeta struct { + artists []string + title string + album string +} + +func (f *filenameMeta) GetArtists() []string { + return f.artists +} + +func (f *filenameMeta) GetTitle() string { + return f.title +} + +func (f *filenameMeta) GetAlbum() string { + return f.album +} + +func ParseFilenameMeta(filename string) (meta AudioMeta) { + partName := strings.TrimSuffix(filename, path.Ext(filename)) + items := strings.Split(partName, "-") + ret := &filenameMeta{} + + switch len(items) { + case 0: + // no-op + case 1: + ret.title = strings.TrimSpace(items[0]) + default: + ret.title = strings.TrimSpace(items[len(items)-1]) + + for _, v := range items[:len(items)-1] { + artists := strings.FieldsFunc(v, func(r rune) bool { + return r == ',' || r == '_' + }) + for _, artist := range artists { + ret.artists = append(ret.artists, strings.TrimSpace(artist)) + } + } + } + + return ret +} diff --git a/algo/common/meta_test.go b/algo/common/meta_test.go new file mode 100644 index 0000000..f91a27f --- /dev/null +++ b/algo/common/meta_test.go @@ -0,0 +1,38 @@ +package common + +import ( + "reflect" + "testing" +) + +func TestParseFilenameMeta(t *testing.T) { + + tests := []struct { + name string + wantMeta AudioMeta + }{ + { + name: "test1", + wantMeta: &filenameMeta{title: "test1"}, + }, + { + name: "周杰伦 - 晴天.flac", + wantMeta: &filenameMeta{artists: []string{"周杰伦"}, title: "晴天"}, + }, + { + name: "Alan Walker _ Iselin Solheim - Sing Me to Sleep.flac", + wantMeta: &filenameMeta{artists: []string{"Alan Walker", "Iselin Solheim"}, title: "Sing Me to Sleep"}, + }, + { + name: "Christopher,Madcon - Limousine.flac", + wantMeta: &filenameMeta{artists: []string{"Christopher", "Madcon"}, title: "Limousine"}, + }, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + if gotMeta := ParseFilenameMeta(tt.name); !reflect.DeepEqual(gotMeta, tt.wantMeta) { + t.Errorf("ParseFilenameMeta() = %v, want %v", gotMeta, tt.wantMeta) + } + }) + } +}