-
Notifications
You must be signed in to change notification settings - Fork 32
Expand file tree
/
Copy pathsong.go
More file actions
86 lines (75 loc) · 2.11 KB
/
Copy pathsong.go
File metadata and controls
86 lines (75 loc) · 2.11 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
package main
import (
"encoding/json"
"fmt"
"strings"
)
type Song struct {
Filename string `json:"filename"`
Path string `json:"path"`
Extension string `json:"extension"`
Title string `json:"title"`
Artist string `json:"artist"`
Album string `json:"album"`
DiscNum *int `json:"disc_num"`
TrackNum *int `json:"track_num"` // we use pointer for string, so we can set it to "nil" if there is no track number
Length int `json:"length"`
}
// For sorting songs in a natural way (artist, album, format, track number)
func (song *Song) ToNaturalSortString() string {
sortables := []string{}
if song.Artist != "" {
sortables = append(sortables, song.Artist)
}
if song.Album != "" {
sortables = append(sortables, song.Album)
}
if song.Extension != "" {
sortables = append(sortables, song.Extension)
}
if song.DiscNum != nil {
sortables = append(sortables, fmt.Sprintf("%03d", *song.DiscNum))
}
if song.TrackNum == nil {
sortables = append(sortables, song.Title)
} else {
sortables = append(sortables, fmt.Sprintf("%03d", *song.TrackNum))
}
if len(sortables) > 0 {
return strings.Join(sortables, " ")
}
return song.Filename
}
// Return a nice title for the song, like "Artist - Title". Fallback to the filename
func (s *Song) NiceTitle() string {
if s.Title != "" && s.Artist != "" {
return fmt.Sprintf("%s - %s", s.Artist, s.Title)
}
return s.Filename
}
// Convert the raw seconds length to a human-readable string like "04:52" or "01:23:45"
func (s Song) NiceLength() string {
seconds := s.Length
minutes := seconds / 60
hours := minutes / 60
seconds %= 60
minutes %= 60
if hours > 0 {
return fmt.Sprintf("%d:%02d:%02d", hours, minutes, seconds)
} else {
return fmt.Sprintf("%d:%02d", minutes, seconds)
}
}
// Custom marshaling for adding "nice_title" and "nice_length" to the JSON output
func (s *Song) MarshalJSON() ([]byte, error) {
type Alias Song
return json.Marshal(&struct {
*Alias
NiceTitle string `json:"nice_title"`
NiceLength string `json:"nice_length"`
}{
Alias: (*Alias)(s),
NiceTitle: s.NiceTitle(),
NiceLength: s.NiceLength(),
})
}