Пример #1
0
func playlist(w http.ResponseWriter, r *http.Request) {
	mpdClient, err := mpd.Dial("tcp", MPDSERVER)
	if err != nil {
		fmt.Printf("Error dialing")
	}
	songs, err := mpdClient.PlaylistInfo(-1, -1)
	if err != nil {
		fmt.Fprintf(w, "Error")
		return
	}
	output := []Song{}
	for _, song := range songs {
		output = append(output, Song{song["Id"], song["Artist"], song["Title"]})
		/*
		   for key, value := range song {
		       fmt.Fprintf(w, "%s: %s\n", key, value)
		   }
		   fmt.Fprintf(w, "-----\n")
		*/
	}
	js, err := json.Marshal(output)
	if err != nil {
		http.Error(w, err.Error(), http.StatusInternalServerError)
	}
	w.Header().Set("Content-Type", "application/json")
	w.Write(js)
	defer mpdClient.Close()
}
Пример #2
0
//Updates the library
func (l *library) update() error {
	var conn *mpd.Client

	fmt.Println("Connecting to MPD")
	conn, err := mpd.Dial("tcp", "127.0.0.1:6600")
	if err != nil {
		fmt.Println("Error: could not connect to MPD for lib update")
		return errors.New("Could not connect to MPD!")
	}
	defer conn.Close()

	_, err = conn.Update("")
	if err != nil {
		fmt.Println("Error: could not update library!")
		return err
	}

	//Let the update happen
	time.Sleep(2 * time.Second)
	songs, err := conn.ListAllInfo("/")
	if err != nil {
		fmt.Println("Error: could not retrieve new library!")
		return err
	}

	l.library = songs
	return nil
}
Пример #3
0
func mpdConnect() *mpd.Client {
	con, err := mpd.Dial("tcp", configuration.MPDConf.Host)
	if err != nil {
		glog.Error("mpdConnect error: ", err.Error())
	}
	return con
}
Пример #4
0
func (mpd *mpdClientComponent) connect() error {
	var err error
	mpd.client, err = gompd.Dial("tcp", mpd.url)
	if err != nil {
		mpd.connected = false
		return err
	}
	mpd.connected = true
	return nil
}
Пример #5
0
func (m MPDInstance) Render() (item modules.Item) {
	mpdItem := MPDItem{Name: m.name, Markup: "pango"}
	mpdFormatData := MPDFormatData{}
	var client *go_mpd.Client

	if c, err := go_mpd.Dial("tcp", m.host_name+":"+strconv.Itoa(m.port)); err != nil {
		log.Error(err.Error())
		return nil
	} else {
		client = c
	}

	defer func(client *go_mpd.Client) {
		if err := client.Close(); err != nil {
			log.Error("Failed to disconnect: " + err.Error())
		}
	}(client)

	if attrs, err := client.Status(); err == nil {
		if state, ok := attrs["state"]; ok {
			mpdFormatData.State = state
		} else {
			log.Error("Failed to read state.")
			return nil
		}
	} else {
		log.Error("Failed to obtain status: " + err.Error())
		return nil
	}

	if attrs, err := client.CurrentSong(); err != nil {
		log.Error("Failed to obtain current song: " + err.Error())
		return nil
	} else {
		obj := reflect.ValueOf(&mpdFormatData).Elem()
		for key, val := range attrs {
			if f := obj.FieldByName(key); f.IsValid() {
				val = strings.TrimSpace(val)
				f.Set(reflect.ValueOf(val))
			}
		}
	}

	buffer := bytes.Buffer{}

	if err := m.template.Execute(&buffer, mpdFormatData); err != nil {
		log.Error("Failed to render mpd template: " + err.Error())
		return nil
	} else {
		mpdItem.Text = buffer.String()
	}

	item = mpdItem
	return
}
Пример #6
0
func (s *Service) Enable() (err error) {
	s.Mpd, err = mpd.Dial("tcp", "localhost:6600")
	if err != nil {
		return err
	}

	s.Subscribe("mpd/play", "", s.handleSimple(s.play))
	s.Subscribe("mpd/pause", "", s.handleSimple(s.pause))
	s.Subscribe("mpd/next", "", s.handleSimple(s.Mpd.Next))
	s.Subscribe("mpd/prev", "", s.handleSimple(s.Mpd.Previous))

	return nil
}
Пример #7
0
func play(w http.ResponseWriter, r *http.Request) {
	mpdClient, err := mpd.Dial("tcp", MPDSERVER)
	if err != nil {
		fmt.Printf("Error dialing")
	}

	err = mpdClient.Play(-1)

	if err != nil {
		fmt.Fprintf(w, "Error play")
		return
	}
	defer mpdClient.Close()
}
Пример #8
0
func Run(server string) int {
	conn, err := mpd.Dial("tcp", server)
	if err != nil {
		log.Fatal(err)
		return 1
	}
	defer conn.Close()

	u := &ui.Ui{Title: "nmpas"}
	c := &Client{Conn: conn, Ui: u}
	go c.Run()
	u.Run()

	return 0
}
Пример #9
0
func add(w http.ResponseWriter, r *http.Request) {
	url := r.FormValue("url")
	mpdClient, err := mpd.Dial("tcp", MPDSERVER)
	if err != nil {
		fmt.Printf("Error dialing")
		return
	}

	if url != "" {
		err = mpdClient.Add(url)
		if err != nil {
			fmt.Fprintf(w, "Error adding %s", url)
			return
		}
		fmt.Fprintf(w, "ok")
	}

	defer mpdClient.Close()

}
Пример #10
0
func main() {
	cfg := MustParseCommandline()

	client, err := mpd.Dial("tcp", fmt.Sprintf("%s:%d", cfg.Host, cfg.Port))
	if err != nil {
		log.Fatalf("Failed to connect to mpd: %v", err)
		return
	}

	keepAlivePinger := make(chan bool)

	// Make sure the mpd connection survives long timeouts:
	go func() {
		for range keepAlivePinger {
			client.Ping()
			time.Sleep(1 * time.Minute)
		}
	}()

	// Close pinger and client on exit:
	defer func() {
		close(keepAlivePinger)
		client.Close()
	}()

	if cfg.UpdateMoodDatabase {
		if err := updateMoodDatabase(client, cfg); err != nil {
			log.Fatalf("Failed to update the mood db: %v", err)
		}

		return
	}

	if err := CleanupCatlightLock(); err != nil {
		log.Fatalf("Failed to clean up previous lock: %v", err)
		return
	}

	// Monitor MPD events and sync moodbar appropiately.
	Watcher(client, cfg)
}
Пример #11
0
//Create a new queue
func newLibrary() *library {
	var conn *mpd.Client

	fmt.Println("Connecting to MPD")
	conn, err := mpd.Dial("tcp", "127.0.0.1:6600")
	if err != nil {
		fmt.Println("Error: could not connect to MPD, exiting")
		os.Exit(1)
	}
	defer conn.Close()

	songs, err := conn.ListAllInfo("/")
	if err != nil {
		fmt.Println("Error: could not connect to MPD, exiting")
		os.Exit(1)
	}
	shuffle(songs)

	return &library{
		library: songs,
	}
}
Пример #12
0
func main() {
	conn, err := mpd.Dial("tcp", "127.0.0.1:6600")

	if err != nil {
		fmt.Println("Error: could not connect to MPD, exiting")
		os.Exit(1)
	}
	defer conn.Close()

	w, err := mpd.NewWatcher("tcp", "127.0.0.1:6600", "", "player")
	if err != nil {
		fmt.Println("Error: could not connect to MPD, exiting")
		os.Exit(1)
	}
	defer w.Close()

	h := newHub()
	go h.run()

	// Log errors.
	go func() {
		for err := range w.Error {
			log.Println("Error:", err)
		}
	}()

	//Control song transitions -- During this time, update the websockets
	go func() {
		var status mpd.Attrs
		for _ = range w.Event {
			status, err = conn.Status()
			if err != nil {
				//Connections seem to drop often, so reconnect when this happens
				fmt.Println("Couldn't get current status! Error: " + err.Error())
				conn.Close()

				fmt.Println("Reconnecting...")
				conn, err = mpd.Dial("tcp", "127.0.0.1:6600")

				if err != nil {
					fmt.Println("Error: could not connect to MPD, exiting")
					os.Exit(1)
				}
				defer conn.Close()

				status, err = conn.Status()
			}
			pos, _ := strconv.ParseFloat(status["elapsed"], 64)
			fmt.Println(pos)
			if pos == 0.000 {
				//Stop us from getting into an infinite loop by waiting 25 ms
				time.Sleep(25 * time.Millisecond)
				//updateQueue <- &updateQueueMsg{Song: song["Title"], Artist: song["Artist"]}
				conn.Pause(true)
				//Wait 3 seconds then resume next song
				time.Sleep(3000 * time.Millisecond)
				conn.Pause(false)
				song, err := conn.CurrentSong()
				if err != nil {
					fmt.Println("Couldn't get current song! Error: " + err.Error())
				} else {
					//Serialize and send info
					msg := map[string]string{"cmd": "NP", "Title": song["Title"], "Artist": song["Artist"], "Album": song["Album"], "Cover": "/art/" + GetAlbumDir(song["file"])}
					jsonMsg, _ := json.Marshal(msg)
					h.broadcast <- []byte(jsonMsg)
				}
			}
		}
	}()

	song, err := conn.CurrentSong()
	if err != nil {
		fmt.Println("No Song!")
	} else {
		fmt.Println(song["Title"])
	}
	songs, err := conn.ListAllInfo("/")
	shuffle(songs)
	subset := songs[:20]

	//Searches for cover image
	web.Get("/art/(.+)", getCover)

	//Returns main page with custom selection of songs
	web.Get("/", func(ctx *web.Context) string {
		return getIndex(ctx, subset)
	})

	//Returns a raw song
	web.Get("/song/(.+)", getSong)

	//Returns the JSON info for the currently playing song
	web.Get("/np", func(ctx *web.Context) string {
		song, _ := conn.CurrentSong()
		jsonMsg, _ := json.Marshal(song)
		return string(jsonMsg)
	})

	//Handle the websocket
	web.Websocket("/ws", websocket.Handler(func(ws *websocket.Conn) {
		handleSocket(ws, h)
	}))
	web.Get("/library", func(ctx *web.Context) string {
		jsonMsg, _ := json.Marshal(subset)
		return string(jsonMsg)
	})
	web.Run("0.0.0.0:8080")
}