From 16e849eb657a847b899eaed6ac391508be805aaf Mon Sep 17 00:00:00 2001 From: "Alexander \"Arav\" Andreev" Date: Mon, 29 Aug 2022 12:47:06 +0400 Subject: [PATCH] Rewritten lastPlayedSong() in a sane way. Hope it will work. --- internal/radio/icecast.go | 21 ++++++++------------- 1 file changed, 8 insertions(+), 13 deletions(-) diff --git a/internal/radio/icecast.go b/internal/radio/icecast.go index 65c2aaa..e0120f3 100644 --- a/internal/radio/icecast.go +++ b/internal/radio/icecast.go @@ -7,7 +7,6 @@ import ( "io" "net/http" "os" - "strings" "sync" "syscall" "time" @@ -115,12 +114,12 @@ func IcecastLastSong(playlistPath string) (Song, error) { func lastPlayedSong(playlistPath string) (*Song, error) { buf := make([]byte, bufferSize) - var last_song_line string playlist, err := os.Open(playlistPath) if err != nil { return nil, err } + defer playlist.Close() playlist_stat, _ := playlist.Stat() @@ -135,24 +134,20 @@ func lastPlayedSong(playlistPath string) (*Song, error) { return nil, err } - newline_end_pos := bytes.LastIndexByte(buf, '\n') + lines := bytes.Split(buf, []byte("\n")) - if newline_end_pos == -1 { - newline_end_pos = len(buf) + if len(lines) < 2 { + return nil, nil } - newline_start_pos := bytes.LastIndexByte(buf[:newline_end_pos-1], '\n') + fields := bytes.Split(lines[len(lines)-2], []byte("|")) - last_song_line = string(buf[newline_start_pos+1 : newline_end_pos-1]) - - fields := strings.Split(last_song_line, "|") - - tim, _ := time.Parse(IcecastPlaylistDateFormat, fields[0]) + tim, _ := time.Parse(IcecastPlaylistDateFormat, string(fields[0])) return &Song{ Time: tim.Format(SongTimeFormat), - Listeners: fields[2], - Song: fields[3]}, nil + Listeners: string(fields[2]), + Song: string(fields[3])}, nil } var playlistWatcher watcher.InotifyWatcher