Moving utils.go to utils package

This commit is contained in:
aditya-K2 2021-12-13 01:35:40 +05:30
parent bc3e5b6741
commit 9b60cbc98e
9 changed files with 79 additions and 69 deletions

4
cache/cache.go vendored
View File

@ -6,7 +6,7 @@ import (
"os" "os"
"strings" "strings"
"github.com/aditya-K2/goMP/config" "github.com/aditya-K2/goMP/utils"
) )
var ( var (
@ -15,7 +15,7 @@ var (
) )
func SetCacheDir(path string) { func SetCacheDir(path string) {
CACHE_DIR = config.CheckDirectoryFmt(path) CACHE_DIR = utils.CheckDirectoryFmt(path)
} }
func Exists(artist, album string) bool { func Exists(artist, album string) bool {

View File

@ -5,6 +5,7 @@ import (
"fmt" "fmt"
"strings" "strings"
"github.com/aditya-K2/goMP/utils"
"github.com/aditya-K2/tview" "github.com/aditya-K2/tview"
) )
@ -12,16 +13,6 @@ var (
WHITE_AND_BOLD string = "[#ffffff::b]" WHITE_AND_BOLD string = "[#ffffff::b]"
) )
func getFormattedString(s string, width int) string {
if len(s) < width {
s += strings.Repeat(" ", (width - len(s)))
} else {
s = s[:(width - 2)]
s += " "
}
return s
}
func togglePlayBack() error { func togglePlayBack() error {
status, err := CONN.Status() status, err := CONN.Status()
if status["state"] == "play" && err == nil { if status["state"] == "play" && err == nil {
@ -39,10 +30,10 @@ func UpdatePlaylist(inputTable *tview.Table) {
for i, j := range _playlistAttr { for i, j := range _playlistAttr {
_, _, w, _ := inputTable.GetInnerRect() _, _, w, _ := inputTable.GetInnerRect()
if j["Title"] == "" || j["Artist"] == "" || j["Album"] == "" { if j["Title"] == "" || j["Artist"] == "" || j["Album"] == "" {
inputTable.SetCell(i, 0, tview.NewTableCell(getFormattedString(j["file"], w/3))) inputTable.SetCell(i, 0, tview.NewTableCell(utils.GetFormattedString(j["file"], w/3)))
} else { } else {
inputTable.SetCell(i, 0, tview.NewTableCell(getFormattedString("[green]"+j["Title"], w/3))) inputTable.SetCell(i, 0, tview.NewTableCell(utils.GetFormattedString("[green]"+j["Title"], w/3)))
inputTable.SetCell(i, 1, tview.NewTableCell(getFormattedString("[magenta]"+j["Artist"], w/3))) inputTable.SetCell(i, 1, tview.NewTableCell(utils.GetFormattedString("[magenta]"+j["Artist"], w/3)))
inputTable.SetCell(i, 2, tview.NewTableCell("[yellow]"+j["Album"])) inputTable.SetCell(i, 2, tview.NewTableCell("[yellow]"+j["Album"]))
} }
} }
@ -106,14 +97,14 @@ func UpdateSearchView(inputTable *tview.Table, c []interface{}) {
switch content.(type) { switch content.(type) {
case [3]string: case [3]string:
{ {
inputTable.SetCell(i, 0, tview.NewTableCell(getFormattedString("[green]"+content.([3]string)[0], width/3))) inputTable.SetCell(i, 0, tview.NewTableCell(utils.GetFormattedString("[green]"+content.([3]string)[0], width/3)))
inputTable.SetCell(i, 1, tview.NewTableCell(getFormattedString("[magenta]"+content.([3]string)[1], width/3))) inputTable.SetCell(i, 1, tview.NewTableCell(utils.GetFormattedString("[magenta]"+content.([3]string)[1], width/3)))
inputTable.SetCell(i, 2, tview.NewTableCell(getFormattedString("[yellow]"+content.([3]string)[2], width/3))) inputTable.SetCell(i, 2, tview.NewTableCell(utils.GetFormattedString("[yellow]"+content.([3]string)[2], width/3)))
} }
case [2]string: case [2]string:
{ {
inputTable.SetCell(i, 0, tview.NewTableCell(getFormattedString("[green]"+content.([2]string)[0], width/3))) inputTable.SetCell(i, 0, tview.NewTableCell(utils.GetFormattedString("[green]"+content.([2]string)[0], width/3)))
inputTable.SetCell(i, 1, tview.NewTableCell(getFormattedString("[magenta]"+content.([2]string)[1], width/3))) inputTable.SetCell(i, 1, tview.NewTableCell(utils.GetFormattedString("[magenta]"+content.([2]string)[1], width/3)))
} }
case string: case string:
{ {
@ -128,16 +119,6 @@ func UpdateSearchView(inputTable *tview.Table, c []interface{}) {
} }
} }
func join(stringSlice []string) string {
var _s string = stringSlice[0]
for i := 1; i < len(stringSlice); i++ {
if _s != "" {
_s += ("/" + stringSlice[i])
}
}
return _s
}
func Update(f []FileNode, inputTable *tview.Table) { func Update(f []FileNode, inputTable *tview.Table) {
inputTable.Clear() inputTable.Clear()
for i, j := range f { for i, j := range f {
@ -146,11 +127,11 @@ func Update(f []FileNode, inputTable *tview.Table) {
if err == nil && _songAttributes[0]["Title"] != "" { if err == nil && _songAttributes[0]["Title"] != "" {
_, _, w, _ := inputTable.GetInnerRect() _, _, w, _ := inputTable.GetInnerRect()
inputTable.SetCell(i, 0, inputTable.SetCell(i, 0,
tview.NewTableCell("[green]"+getFormattedString(_songAttributes[0]["Title"], w/3)). tview.NewTableCell("[green]"+utils.GetFormattedString(_songAttributes[0]["Title"], w/3)).
SetAlign(tview.AlignLeft)) SetAlign(tview.AlignLeft))
inputTable.SetCell(i, 1, inputTable.SetCell(i, 1,
tview.NewTableCell("[magenta]"+getFormattedString(_songAttributes[0]["Artist"], w/3)). tview.NewTableCell("[magenta]"+utils.GetFormattedString(_songAttributes[0]["Artist"], w/3)).
SetAlign(tview.AlignLeft)) SetAlign(tview.AlignLeft))
inputTable.SetCell(i, 2, inputTable.SetCell(i, 2,

View File

@ -6,6 +6,7 @@ import (
"os" "os"
"strings" "strings"
"github.com/aditya-K2/goMP/utils"
"github.com/spf13/viper" "github.com/spf13/viper"
) )
@ -17,10 +18,10 @@ var (
"ADDITIONAL_PADDING_Y": 16, "ADDITIONAL_PADDING_Y": 16,
"IMAGE_WIDTH_EXTRA_X": -1.5, "IMAGE_WIDTH_EXTRA_X": -1.5,
"IMAGE_WIDTH_EXTRA_Y": -3.75, "IMAGE_WIDTH_EXTRA_Y": -3.75,
"MUSIC_DIRECTORY": CheckDirectoryFmt(getMusicDirectory()), "MUSIC_DIRECTORY": utils.CheckDirectoryFmt(getMusicDirectory()),
"PORT": "6600", "PORT": "6600",
"DEFAULT_IMAGE_PATH": "default.jpg", "DEFAULT_IMAGE_PATH": "default.jpg",
"CACHE_DIR": CheckDirectoryFmt(USER_CACHE_DIR), "CACHE_DIR": utils.CheckDirectoryFmt(USER_CACHE_DIR),
} }
) )
@ -73,11 +74,3 @@ func getMusicDirectory() string {
} }
return "" return ""
} }
func CheckDirectoryFmt(path string) string {
if strings.HasSuffix(path, "/") {
return path
} else {
return path + "/"
}
}

View File

@ -5,6 +5,8 @@ import (
"os" "os"
"strings" "strings"
"github.com/aditya-K2/goMP/utils"
"github.com/bogem/id3v2" "github.com/bogem/id3v2"
"github.com/mewkiz/flac" "github.com/mewkiz/flac"
"github.com/mewkiz/flac/meta" "github.com/mewkiz/flac/meta"
@ -69,17 +71,17 @@ func extractImageFromFile(uri string, imagePath string) string {
if strings.HasSuffix(uri, ".mp3") { if strings.HasSuffix(uri, ".mp3") {
imagePath := GetMp3Image(uri, imagePath) imagePath := GetMp3Image(uri, imagePath)
if imagePath == "" { if imagePath == "" {
Copy(viper.GetString("DEFAULT_IMAGE_PATH"), _i) utils.Copy(viper.GetString("DEFAULT_IMAGE_PATH"), _i)
return viper.GetString("DEFAULT_IMAGE_PATH") return viper.GetString("DEFAULT_IMAGE_PATH")
} }
} else if strings.HasSuffix(uri, ".flac") { } else if strings.HasSuffix(uri, ".flac") {
imagePath := GetFlacImage(uri, imagePath) imagePath := GetFlacImage(uri, imagePath)
if imagePath == "" { if imagePath == "" {
Copy(viper.GetString("DEFAULT_IMAGE_PATH"), _i) utils.Copy(viper.GetString("DEFAULT_IMAGE_PATH"), _i)
return viper.GetString("DEFAULT_IMAGE_PATH") return viper.GetString("DEFAULT_IMAGE_PATH")
} }
} else { } else {
Copy(viper.GetString("DEFAULT_IMAGE_PATH"), _i) utils.Copy(viper.GetString("DEFAULT_IMAGE_PATH"), _i)
return viper.GetString("DEFAULT_IMAGE_PATH") return viper.GetString("DEFAULT_IMAGE_PATH")
} }
return imagePath return imagePath
@ -95,7 +97,7 @@ func getImg(uri string) (image.Image, error) {
if err != nil { if err != nil {
return nil, err return nil, err
} }
fw, fh := getFontWidth() fw, fh := utils.GetFontWidth()
img = resize.Resize( img = resize.Resize(
uint(float32(IMG_W)*(fw+float32(viper.GetFloat64("IMAGE_WIDTH_EXTRA_X")))), uint(float32(IMG_H)*(fh+float32(viper.GetFloat64("IMAGE_WIDTH_EXTRA_Y")))), uint(float32(IMG_W)*(fw+float32(viper.GetFloat64("IMAGE_WIDTH_EXTRA_X")))), uint(float32(IMG_H)*(fh+float32(viper.GetFloat64("IMAGE_WIDTH_EXTRA_Y")))),
img, img,

View File

@ -4,6 +4,8 @@ import (
"strconv" "strconv"
"time" "time"
"github.com/aditya-K2/goMP/utils"
"github.com/aditya-K2/fuzzy" "github.com/aditya-K2/fuzzy"
"github.com/aditya-K2/goMP/cache" "github.com/aditya-K2/goMP/cache"
"github.com/aditya-K2/goMP/config" "github.com/aditya-K2/goMP/config"
@ -55,7 +57,7 @@ func main() {
Repeat, _ = strconv.ParseBool(_v["repeat"]) Repeat, _ = strconv.ParseBool(_v["repeat"])
ARTIST_TREE, err = GenerateArtistTree() ARTIST_TREE, err = GenerateArtistTree()
ARTIST_TREE_CONTENT := ConvertToArray() ARTIST_TREE_CONTENT := utils.ConvertToArray(ARTIST_TREE)
NOTIFICATION_SERVER = NewNotificationServer() NOTIFICATION_SERVER = NewNotificationServer()
NOTIFICATION_SERVER.Start() NOTIFICATION_SERVER.Start()
@ -206,7 +208,7 @@ func main() {
if i == 10 { if i == 10 {
break break
} }
suggestions = append(suggestions, getFormattedString(match.Str, w-2)) suggestions = append(suggestions, utils.GetFormattedString(match.Str, w-2))
} }
return suggestions return suggestions
} else { } else {

View File

@ -3,6 +3,8 @@ package main
import ( import (
"time" "time"
"github.com/aditya-K2/goMP/utils"
"github.com/aditya-K2/tview" "github.com/aditya-K2/tview"
"github.com/gdamore/tcell/v2" "github.com/gdamore/tcell/v2"
) )
@ -23,7 +25,7 @@ func NewNotification(s string) *Notification {
/* Draw Function for the Notification Primitive */ /* Draw Function for the Notification Primitive */
func (self *Notification) Draw(screen tcell.Screen) { func (self *Notification) Draw(screen tcell.Screen) {
termDetails := getWidth() termDetails := utils.GetWidth()
var ( var (
COL int = int(termDetails.Col) COL int = int(termDetails.Col)

View File

@ -4,6 +4,8 @@ import (
"fmt" "fmt"
"strconv" "strconv"
"github.com/aditya-K2/goMP/utils"
"github.com/aditya-K2/tview" "github.com/aditya-K2/tview"
"github.com/gdamore/tcell/v2" "github.com/gdamore/tcell/v2"
) )
@ -69,14 +71,14 @@ func (s *progressBar) updateProgress() {
if du != 0 { if du != 0 {
percentage := el / du * 100 percentage := el / du * 100
if err == nil && err1 == nil { if err == nil && err1 == nil {
s.t.SetTitle(fmt.Sprintf("[[::i] %s [-:-:-]Shuffle: %s Repeat: %s Volume: %s ]", formatString(_status["state"]), formatString(_status["random"]), formatString(_status["repeat"]), _status["volume"])).SetTitleAlign(tview.AlignRight) s.t.SetTitle(fmt.Sprintf("[[::i] %s [-:-:-]Shuffle: %s Repeat: %s Volume: %s ]", utils.FormatString(_status["state"]), utils.FormatString(_status["random"]), utils.FormatString(_status["repeat"]), _status["volume"])).SetTitleAlign(tview.AlignRight)
s.t.GetCell(2, 0).Text = getText(float64(_width), percentage, strTime(el)+"/"+strTime(du)+"("+strconv.FormatFloat(percentage, 'f', 2, 32)+"%"+")") s.t.GetCell(2, 0).Text = utils.GetText(float64(_width), percentage, utils.StrTime(el)+"/"+utils.StrTime(du)+"("+strconv.FormatFloat(percentage, 'f', 2, 32)+"%"+")")
} else { } else {
s.t.SetTitle(fmt.Sprintf("[[::i] %s [-:-:-]Shuffle: %s Repeat: %s]", formatString(_status["state"]), formatString(_status["random"]), formatString(_status["repeat"]))).SetTitleAlign(tview.AlignRight) s.t.SetTitle(fmt.Sprintf("[[::i] %s [-:-:-]Shuffle: %s Repeat: %s]", utils.FormatString(_status["state"]), utils.FormatString(_status["random"]), utils.FormatString(_status["repeat"]))).SetTitleAlign(tview.AlignRight)
s.t.GetCell(2, 0).Text = "" s.t.GetCell(2, 0).Text = ""
} }
} else { } else {
s.t.SetTitle(fmt.Sprintf("[[::i] %s [-:-:-]Shuffle: %s Repeat: %s Volume: %s ]", formatString(_status["state"]), formatString(_status["random"]), formatString(_status["repeat"]), _status["volume"])).SetTitleAlign(tview.AlignRight) s.t.SetTitle(fmt.Sprintf("[[::i] %s [-:-:-]Shuffle: %s Repeat: %s Volume: %s ]", utils.FormatString(_status["state"]), utils.FormatString(_status["random"]), utils.FormatString(_status["repeat"]), _status["volume"])).SetTitleAlign(tview.AlignRight)
s.t.GetCell(2, 0).Text = getText(float64(_width), 0, " ---:---") s.t.GetCell(2, 0).Text = utils.GetText(float64(_width), 0, " ---:---")
} }
} }

View File

@ -2,7 +2,7 @@ package main
import ( import (
"github.com/aditya-K2/goMP/cache" "github.com/aditya-K2/goMP/cache"
"github.com/aditya-K2/goMP/config" "github.com/aditya-K2/goMP/utils"
"github.com/spf13/viper" "github.com/spf13/viper"
"gitlab.com/diamondburned/ueberzug-go" "gitlab.com/diamondburned/ueberzug-go"
) )
@ -42,7 +42,7 @@ func (self *Renderer) Send(path string) {
*/ */
func openImage(path string, c chan string) { func openImage(path string, c chan string) {
fw, fh := getFontWidth() fw, fh := utils.GetFontWidth()
var im *ueberzug.Image var im *ueberzug.Image
if path != "stop" { if path != "stop" {
extractedImage := getImagePath(path) extractedImage := getImagePath(path)
@ -80,7 +80,7 @@ func getImagePath(path string) string {
extractedImage = cache.GenerateName(a[0]["artist"], a[0]["album"]) extractedImage = cache.GenerateName(a[0]["artist"], a[0]["album"])
} else { } else {
imagePath := cache.GenerateName(a[0]["artist"], a[0]["album"]) imagePath := cache.GenerateName(a[0]["artist"], a[0]["album"])
absPath := config.CheckDirectoryFmt(viper.GetString("MUSIC_DIRECTORY")) + path absPath := utils.CheckDirectoryFmt(viper.GetString("MUSIC_DIRECTORY")) + path
extractedImage = extractImageFromFile(absPath, imagePath) extractedImage = extractImageFromFile(absPath, imagePath)
if extractedImage == viper.GetString("DEFAULT_IMAGE_PATH") && viper.GetString("GET_COVER_ART_FROM_LAST_FM") == "TRUE" { if extractedImage == viper.GetString("DEFAULT_IMAGE_PATH") && viper.GetString("GET_COVER_ART_FROM_LAST_FM") == "TRUE" {
downloadedImage, err := getImageFromLastFM(a[0]["artist"], a[0]["album"], imagePath) downloadedImage, err := getImageFromLastFM(a[0]["artist"], a[0]["album"], imagePath)

View File

@ -1,4 +1,4 @@
package main package utils
import ( import (
"io/ioutil" "io/ioutil"
@ -15,7 +15,7 @@ type winsize struct {
Ypixel uint16 Ypixel uint16
} }
func getWidth() *winsize { func GetWidth() *winsize {
ws := &winsize{} ws := &winsize{}
retCode, _, errno := syscall.Syscall(syscall.SYS_IOCTL, retCode, _, errno := syscall.Syscall(syscall.SYS_IOCTL,
uintptr(syscall.Stdin), uintptr(syscall.Stdin),
@ -28,14 +28,14 @@ func getWidth() *winsize {
return ws return ws
} }
func getFontWidth() (float32, float32) { func GetFontWidth() (float32, float32) {
g := getWidth() g := GetWidth()
fw := (float32(g.Xpixel) / float32(g.Col)) fw := (float32(g.Xpixel) / float32(g.Col))
fh := (float32(g.Ypixel) / float32(g.Row)) fh := (float32(g.Ypixel) / float32(g.Row))
return fw, fh return fw, fh
} }
func strTime(e float64) string { func StrTime(e float64) string {
a := int(e) a := int(e)
var min, seconds string var min, seconds string
if a/60 < 10 { if a/60 < 10 {
@ -53,24 +53,24 @@ func strTime(e float64) string {
return min + ":" + seconds return min + ":" + seconds
} }
func insertAt(inputString, stringTobeInserted string, index int) string { func InsertAt(inputString, stringTobeInserted string, index int) string {
s := inputString[:index] + stringTobeInserted + inputString[index:] s := inputString[:index] + stringTobeInserted + inputString[index:]
return s return s
} }
func getText(width, percentage float64, eta string) string { func GetText(width, percentage float64, eta string) string {
q := "[#000000:#ffffff:b]" q := "[#000000:#ffffff:b]"
var a string var a string
a += strings.Repeat(" ", int(width)-len(eta)) a += strings.Repeat(" ", int(width)-len(eta))
a = insertAt(a, eta, int(width/2)-10) a = InsertAt(a, eta, int(width/2)-10)
a = insertAt(a, "[-:-:-]", int(width*percentage/100)) a = InsertAt(a, "[-:-:-]", int(width*percentage/100))
q += a q += a
return q return q
} }
func ConvertToArray() []string { func ConvertToArray(ArtistTree map[string]map[string]map[string]string) []string {
var p []string var p []string
for k2, v := range ARTIST_TREE { for k2, v := range ArtistTree {
p = append(p, k2) p = append(p, k2)
for k1, v1 := range v { for k1, v1 := range v {
p = append(p, k1) p = append(p, k1)
@ -82,7 +82,7 @@ func ConvertToArray() []string {
return p return p
} }
func formatString(a interface{}) string { func FormatString(a interface{}) string {
if a == "play" { if a == "play" {
return "Playing" return "Playing"
} else if a == "1" { } else if a == "1" {
@ -108,3 +108,31 @@ func Copy(sourceImage, destinationImage string) error {
return nil return nil
} }
} }
func Join(stringSlice []string) string {
var _s string = stringSlice[0]
for i := 1; i < len(stringSlice); i++ {
if _s != "" {
_s += ("/" + stringSlice[i])
}
}
return _s
}
func GetFormattedString(s string, width int) string {
if len(s) < width {
s += strings.Repeat(" ", (width - len(s)))
} else {
s = s[:(width - 2)]
s += " "
}
return s
}
func CheckDirectoryFmt(path string) string {
if strings.HasSuffix(path, "/") {
return path
} else {
return path + "/"
}
}