Do not alter Song struct listeners with its methods, use a ListenerCounter to populate Listeners and MaxListeners. Eliminates the need for a mutex and SetFrom(), UpdateMaxListeners() and IncListeners() methods.
This commit is contained in:
parent
3b22643733
commit
1682362779
@ -2,50 +2,20 @@ package radio
|
|||||||
|
|
||||||
import (
|
import (
|
||||||
"encoding/json"
|
"encoding/json"
|
||||||
"sync"
|
|
||||||
"time"
|
"time"
|
||||||
)
|
)
|
||||||
|
|
||||||
type Song struct {
|
type Song struct {
|
||||||
mutex sync.Mutex
|
|
||||||
Artist string
|
Artist string
|
||||||
Title string
|
Title string
|
||||||
|
StartAt time.Time
|
||||||
Duration time.Duration
|
Duration time.Duration
|
||||||
Listeners int64
|
Listeners int64
|
||||||
MaxListeners int64
|
MaxListeners int64
|
||||||
StartAt time.Time
|
|
||||||
}
|
|
||||||
|
|
||||||
func (s *Song) SetFrom(os *Song) {
|
|
||||||
s.mutex.Lock()
|
|
||||||
s.Artist = os.Artist
|
|
||||||
s.Title = os.Title
|
|
||||||
s.Duration = os.Duration
|
|
||||||
s.Listeners = os.Listeners
|
|
||||||
s.MaxListeners = os.MaxListeners
|
|
||||||
s.StartAt = os.StartAt
|
|
||||||
s.mutex.Unlock()
|
|
||||||
}
|
|
||||||
|
|
||||||
func (s *Song) UpdateMaxListeners(listeners int64) {
|
|
||||||
s.mutex.Lock()
|
|
||||||
if listeners > s.MaxListeners {
|
|
||||||
s.MaxListeners = listeners
|
|
||||||
}
|
|
||||||
s.mutex.Unlock()
|
|
||||||
}
|
|
||||||
|
|
||||||
// IncListeners increments by one an overall amount of listeners of this song.
|
|
||||||
func (s *Song) IncListeners() {
|
|
||||||
s.mutex.Lock()
|
|
||||||
s.Listeners++
|
|
||||||
s.mutex.Unlock()
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// DurationString returns song's duration as a string formatted as [H:]M:SS.
|
// DurationString returns song's duration as a string formatted as [H:]M:SS.
|
||||||
func (s *Song) DurationString() string {
|
func (s *Song) DurationString() string {
|
||||||
s.mutex.Lock()
|
|
||||||
defer s.mutex.Unlock()
|
|
||||||
if s.Duration.Hours() >= 1 {
|
if s.Duration.Hours() >= 1 {
|
||||||
return time.UnixMilli(s.Duration.Milliseconds()).Format("3:4:05")
|
return time.UnixMilli(s.Duration.Milliseconds()).Format("3:4:05")
|
||||||
}
|
}
|
||||||
@ -53,8 +23,6 @@ func (s *Song) DurationString() string {
|
|||||||
}
|
}
|
||||||
|
|
||||||
func (s *Song) MarshalJSON() ([]byte, error) {
|
func (s *Song) MarshalJSON() ([]byte, error) {
|
||||||
s.mutex.Lock()
|
|
||||||
defer s.mutex.Unlock()
|
|
||||||
return json.Marshal(&struct {
|
return json.Marshal(&struct {
|
||||||
Artist string `json:"artist"`
|
Artist string `json:"artist"`
|
||||||
Title string `json:"title"`
|
Title string `json:"title"`
|
||||||
|
Loading…
Reference in New Issue
Block a user