示例#1
0
func (ms MusicServer) create(port string, indexFolder, musicFolder, addressMask, webfolder string) {
	ms.folder = indexFolder
	ms.textIndexer = music.LoadTextIndexer(ms.folder)
	ms.albumManager = music.NewAlbumManager(ms.folder)
	ms.webfolder = "resources/"
	if musicFolder != "" {
		ms.musicFolder = musicFolder
		if addressMask != "" {
			for i, val := range strings.Split(addressMask, ".") {
				if intVal, e := strconv.ParseInt(val, 10, 32); e == nil {
					ms.addressMask[i] = int(intVal)
				}
			}
		}
	}
	if webfolder != "" {
		ms.webfolder = webfolder
	}
	ms.dico = music.LoadDictionnary(ms.folder)
	if port == "" {
		logger.GetLogger().Fatal("Impossible to run node, port is not defined")
	}
	localIP := ms.findExposedURL()

	mux := ms.createRoutes()
	logger.GetLogger().Info("Runner ok on :", localIP, port)
	http.ListenAndServe(":"+port, mux)

	logger.GetLogger().Error("Runner ko")
}
示例#2
0
func IndexArtists(folder string) TextIndexer {
	// Recreate albums index at each time (very quick)
	artists := LoadArtists(folder)
	logger.GetLogger().Info("Launch index with", len(artists), "artists")
	dico := LoadDictionnary(folder)
	musicsByArtist := LoadArtistMusicIndex(folder)

	am := NewAlbumManager(folder)

	// Index album by genre (consider only one genre by album)

	for n, artistId := range artists {
		musicsIds := musicsByArtist.Get(artistId)
		// Load all tracks and group by album
		albums := make(map[string][]int)
		logger.GetLogger().Info("=>", n, artistId, dico.GetMusicsFromIds(musicsIds))
		for i, music := range dico.GetMusicsFromIds(musicsIds) {
			musicId := musicsIds[i]
			if ids, ok := albums[music["album"]]; ok {
				albums[music["album"]] = append(ids, musicId)
			} else {
				albums[music["album"]] = []int{musicId}
			}
			am.AddMusic(music["album"], musicId)
			am.IndexText(musicId, music["title"], music["artist"])
		}
		am.AddAlbumsByArtist(artistId, albums)
	}
	am.textIndexer.Build()
	am.Save()
	logger.GetLogger().Info("End index")
	return am.textIndexer
}
示例#3
0
func createServer(port string) {
	if port == "" {
		logger.GetLogger().Fatal("Port is not defined")
	}
	localIP := findExposedURL()
	gameManager = longhorn.NewGameManager()
	mux := createRoutes()
	logger.GetLogger().Info("Runner ok on :", localIP, port)
	http.ListenAndServe(":"+port, mux)

	logger.GetLogger().Error("Runner ko")
}
示例#4
0
// Return music content
func (ms MusicServer) readmusic(response http.ResponseWriter, request *http.Request) {
	id, _ := strconv.ParseInt(request.FormValue("id"), 10, 32)
	logger.GetLogger().Info("Get music id", id)
	musicInfo := ms.dico.GetMusicFromId(int(id))

	m, _ := os.Open(musicInfo["path"])
	info, _ := m.Stat()
	logger.GetLogger().Info("load", musicInfo["path"])
	response.Header().Set("Content-type", "audio/mpeg")
	response.Header().Set("Content-Length", fmt.Sprintf("%d", info.Size()))
	io.Copy(response, m)
}
示例#5
0
// Return info about many musics
func (ms MusicServer) musicsInfo(response http.ResponseWriter, request *http.Request) {
	var ids []int
	json.Unmarshal([]byte(request.FormValue("ids")), &ids)
	logger.GetLogger().Info("Load musics", len(ids))

	ms.musicsResponse(ids, response)
}
示例#6
0
// LoadArtistIndex Get artist index to search...
func LoadArtistIndex(folder string) ArtistIndex {
	ai := ArtistIndex{artists: make(map[string]int), artistsToSave: make([]string, 0)}
	ai.artists = LoadArtists(folder)
	ai.currentId = len(ai.artists) + 1
	logger.GetLogger().Info("Current artist id", ai.currentId)
	return ai
}
示例#7
0
func (ms MusicServer) checkRequester(request *http.Request) bool {
	addr := request.RemoteAddr[:strings.LastIndex(request.RemoteAddr, ":")]
	if "[::1]" != addr {
		// [::1] means localhost. Otherwise, compare to mask
		for i, val := range strings.Split(addr, ".") {
			if intval, e := strconv.ParseInt(val, 10, 32); e != nil {
				logger.GetLogger().Error("User attempt to update data from outside", request.Host, request.RemoteAddr)
				return false
			} else {
				if int(intval)&ms.addressMask[i] != int(intval) {
					logger.GetLogger().Error("User attempt to update data from outside", request.Host, request.RemoteAddr)
					return false
				}
			}
		}
	}
	return true
}
示例#8
0
func (ms MusicServer) listByArtist(response http.ResponseWriter, request *http.Request) {
	if id := request.FormValue("id"); id == "" {
		ms.getAllArtists(response)
	} else {
		logger.GetLogger().Info("Load music of artist", id)
		artistId, _ := strconv.ParseInt(id, 10, 32)
		musicsIds := music.LoadArtistMusicIndex(ms.folder).MusicsByArtist[int(artistId)]
		ms.getMusics(response, musicsIds, false)
	}
}
示例#9
0
func CreateShareConnection(response http.ResponseWriter, deviceName, sessionId string) {
	createSSEHeader(response)
	// Generate unique code to receive order
	device := &Device{name: deviceName, response: response, sessionId: sessionId, connected: true}
	ss := &SharedSession{id: generateShareCode(), connected: true, original: device}
	sharedSessions[ss.id] = ss
	ss.original.send("id", fmt.Sprintf("%d", ss.id))
	logger.GetLogger().Info("Create share", ss.id)
	checkConnection(device)
	removeSharedSession(ss.id)
}
示例#10
0
// Return info about music
func (ms MusicServer) musicInfo(response http.ResponseWriter, request *http.Request) {
	id, _ := strconv.ParseInt(request.FormValue("id"), 10, 32)
	logger.GetLogger().Info("Load music info with id", id)
	musicInfo := ms.dico.GetMusicFromId(int(id))
	delete(musicInfo, "path")
	musicInfo["id"] = fmt.Sprintf("%d", id)
	musicInfo["src"] = fmt.Sprintf("music?id=%d", id)
	bdata, _ := json.Marshal(musicInfo)
	writeCrossAccessHeader(response)
	response.Write(bdata)
}
示例#11
0
// Add the artist in index. Return id
func (ai *ArtistIndex) Add(artist string) int {
	// Check if exist
	if id, exist := ai.artists[artist]; exist {
		return id
	}
	id := ai.currentId
	ai.artists[artist] = id
	ai.artistsToSave = append(ai.artistsToSave, artist)
	logger.GetLogger().Info("Add artist", artist, " :", ai.currentId)
	ai.currentId++
	return id
}
示例#12
0
// boardCows contains nb of cows on board by color
func (p Player) CountPoint(boardCows []int) int {
	// Point if 100 for each color staying on board
	total := 0
	for i, nb := range p.Cows {
		total += boardCows[i] * 100 * int(nb)
	}
	for _, money := range p.Moneys {
		total += money
	}
	logger.GetLogger().Info("POINT", p.Id, p.Cows, boardCows, p.Moneys)
	return total
}
示例#13
0
func (ms MusicServer) getAllArtists(response http.ResponseWriter) {
	logger.GetLogger().Info("Get all artists")
	// Response with nampe and url
	artists := music.LoadArtistIndex(ms.folder).FindAll()
	artistsData := make([]map[string]string, 0, len(artists))
	for artist, id := range artists {
		artistsData = append(artistsData, map[string]string{"name": artist, "url": fmt.Sprintf("id=%d", id)})
	}
	sort.Sort(sortByArtist(artistsData))
	bdata, _ := json.Marshal(artistsData)
	response.Write(bdata)
}
示例#14
0
//search musics by free text
func (ms *MusicServer) search(response http.ResponseWriter, request *http.Request) {
	text := request.FormValue("term")
	size := float64(10)
	if s := request.FormValue("size"); s != "" {
		if intSize, e := strconv.ParseInt(s, 10, 32); e == nil {
			size = float64(intSize)
		}
	}
	musics := ms.textIndexer.Search(text)
	logger.GetLogger().Info("Search", text, len(musics))
	ms.musicsResponse(musics[:int(math.Min(size, float64(len(musics))))], response)
}
示例#15
0
func sessionID(response http.ResponseWriter, request *http.Request) string {
	if id := getSessionID(request); id != "" {
		return id
	}
	h := md5.New()
	h.Write([]byte(fmt.Sprintf("%d-%d", time.Now().Nanosecond(), rand.Int())))
	hash := h.Sum(nil)
	hexValue := hex.EncodeToString(hash)
	logger.GetLogger().Info("Set cookie session", hexValue)
	http.SetCookie(response, &http.Cookie{Name: "jsessionid", Value: hexValue})
	return hexValue
}
示例#16
0
func (d Device) send(event string, data string) (success bool) {
	defer func() {
		if e := recover(); e != nil {
			success = false
		}
	}()
	logger.GetLogger().Info("SEND", event, data, d.sessionId)
	if event != "" {
		d.response.Write([]byte(fmt.Sprintf("event: %s\n", event)))
	}
	d.response.Write([]byte("data: " + data + "\n\n"))
	d.response.(http.Flusher).Flush()
	success = true
	return
}
示例#17
0
func (ss *SharedSession) ConnectToShare(response http.ResponseWriter, deviceName, sessionId string) {
	var device *Device
	logger.GetLogger().Info("Connect clone", ss.id)
	// Check if sessionId exist
	createSSEHeader(response)
	if v, dev := ss.isClone(sessionId); !v {
		//check device exist
		device = &Device{name: deviceName, sessionId: sessionId, response: response, connected: true}
		ss.clones = append(ss.clones, device)
	} else {
		dev.response = response
		device = dev
	}
	device.send("id", fmt.Sprintf("%d", ss.id))
	ss.original.send("askPlaylist", "")
	checkConnection(device)
	// remove clone
	ss.removeClone(sessionId)
}
示例#18
0
func checkConnection(d *Device) {
	disconnect := false
	go func() {
		defer func() {
			if err := recover(); err != nil {
				disconnect = true
			}
		}()
		<-d.response.(http.CloseNotifier).CloseNotify()
		disconnect = true
	}()
	for {
		if !d.connected || disconnect {
			break
		}
		time.Sleep(5 * time.Second)
	}
	logger.GetLogger().Info("End device", d.sessionId)
}
示例#19
0
func (ms MusicServer) listByOnlyAlbums(response http.ResponseWriter, request *http.Request) {
	switch {
	// return albums of artist
	case request.FormValue("id") != "":
		logger.GetLogger().Info("Get musics of album")
		idAlbum, _ := strconv.ParseInt(request.FormValue("id"), 10, 32)
		musics := ms.albumManager.GetMusicsAll(int(idAlbum))
		ms.getMusics(response, musics, true)
	default:
		albums := ms.albumManager.LoadAllAlbums()
		albumsData := make([]map[string]string, 0, len(albums))
		for album, id := range albums {
			albumsData = append(albumsData, map[string]string{"name": album, "url": fmt.Sprintf("id=%d", id)})
		}
		sort.Sort(sortByArtist(albumsData))
		data, _ := json.Marshal(albumsData)
		response.Write(data)
	}

}
示例#20
0
func main() {
	var (
		err       error
		cmdConfig *config.CommandLineConfiguration
		cfg       *config.Config
		m         *martini.ClassicMartini
		log       *logging.Logger
	)
	cmdConfig, err = config.GetCommandLineConfiguration()
	if err != nil {
		panic(err)
	}
	cfg, err = config.GetConfig(cmdConfig.ConfigFilePath)
	if err != nil {
		panic(err)
	}
	defer cfg.Logger.LogFile.Close()
	log, err = logger.GetLogger(&cfg.Logger)
	if err != nil {
		panic(err)
	}
	session, err := db.GetSession(&cfg.DatabaseConnectOpts)
	if err != nil {
		panic(err)
	}
	m = martini.Classic()
	m.Map(log)
	m.Map(&cfg.WebSocketConfig)
	m.Map(&cfg.HttpServer)
	m.Map(&cfg)
	m.Map(session)
	m.Use(render.Renderer(render.Options{
		Layout: "base",
	}))
	routing.Configure(m)
	log.Info("Listening")
	m.RunOnAddr(cfg.ListenHost + ":" + cfg.ListenPort)
	log.Info("Listening")
}
示例#21
0
func doSearch(params string, threashold int) string {
	fParams := url.Values{"query": []string{params}}.Encode()
	checkLastGet()
	totalMBRequest++
	//logger.GetLogger().Info("req",params,totalMBRequest,retryMBRequest)
	if resp, e := http.Get(musicBrainzUrl + fParams); e == nil {
		defer resp.Body.Close()
		// Quota exceed, relaunch after time
		if resp.StatusCode == 503 {
			retryMBRequest++
			logger.GetLogger().Error("Limit exceed, retry", totalMBRequest, retryMBRequest, params)
			time.Sleep(time.Duration(waitMBTime) * time.Millisecond)
			return doSearch(params, threashold)
		}
		// Check if release field are present, if not, limit
		d, _ := ioutil.ReadAll(resp.Body)
		if cover, err := extractInfo(d, threashold); err == nil {
			return cover
		}
	}
	return ""
}
示例#22
0
// Join or create a game
func join(response http.ResponseWriter, r *http.Request) {
	var g *longhorn.Game
	sessionId := setSessionID(response, *r)
	name := r.FormValue("name")
	if idGame := r.FormValue("idGame"); idGame != "" {
		if id, err := strconv.ParseInt(idGame, 10, 32); err == nil {
			g, _ = gameManager.GetGame(int(id), sessionId, name)
			if g == nil {
				// Create a game with the specific id
				g = gameManager.CreateGameFromId(sessionId, name, int(id))
			}
		}
	}
	if g == nil {
		logger.GetLogger().Info("create game")
		g = gameManager.CreateGame(sessionId, name)
	}
	http.SetCookie(response, &http.Cookie{Name: "gameid", Value: fmt.Sprintf("%d", g.Board.GetId())})
	m := longhorn.NewServerMessage(g.Board)

	response.Header().Set("Content-type", "application/json")
	response.Write(m.ToJSON())
}
示例#23
0
func (ms MusicServer) listByAlbum(response http.ResponseWriter, request *http.Request) {
	switch {
	// return albums of artist
	case request.FormValue("id") != "":
		logger.GetLogger().Info("Get all albums")
		idArtist, _ := strconv.ParseInt(request.FormValue("id"), 10, 32)
		albums := music.NewAlbumByArtist().GetAlbums(ms.folder, int(idArtist))
		albumsData := make([]map[string]string, 0, len(albums))
		for _, album := range albums {
			albumsData = append(albumsData, map[string]string{"name": album.Name, "url": fmt.Sprintf("idAlbum=%d", album.Id)})
		}
		sort.Sort(sortByArtist(albumsData))
		bdata, _ := json.Marshal(albumsData)
		response.Write(bdata)
	case request.FormValue("idAlbum") != "":
		idAlbum, _ := strconv.ParseInt(request.FormValue("idAlbum"), 10, 32)
		musics := ms.albumManager.GetMusics(int(idAlbum))
		ms.getMusics(response, musics, true)

	default:
		ms.getAllArtists(response)
	}

}
示例#24
0
文件: game.go 项目: jotitan/longhorn
func (g Game) SendToAll(event string, data []byte) error {
	logger.GetLogger().Info("TOALL", string(data))
	g.pd1.sendMessage(event, data)
	g.pd2.sendMessage(event, data)
	return nil
}
示例#25
0
文件: game.go 项目: jotitan/longhorn
func (g *Game) Workflow(e Event) error {
	logger.GetLogger().Info("Receive event", e)
	if e.GameId == 0 && g.Board.currentCase == nil {
		return g.begin()
	}

	// execute standard action. Not executed when begin case
	nbCow := int8(0)
	if e.Color != -1 {
		if err := checkEvent(g.Board, e); err != nil {
			logger.GetLogger().Error(err)
			return err
		}
		nbCow = g.Board.currentCase.TakeColor(e.Color)
		g.Board.currentPlayer.GetCows(map[int]int8{e.Color: nbCow})
		g.Board.previousCowNumber = int(nbCow)
	}

	// execute specific action if necessary
	switchPlayer := true
	moveCase := true
	if e.Info != nil {
		switchPlayer, moveCase = g.Board.currentCase.ExecuteSpecificAction(g.Board, *e.Info)
	}
	var m []byte
	// check win : no move available, 9 of one color, sheriff
	if hasWinner, winner := g.HasWinner(); hasWinner {
		return g.SendWinner(winner, "get 9 of one color")
	} else {
		// Some action avoid moving case cause board is changing (swallow, snake, killcolor)
		// Move next player

		// If no move available, win. Warning when move case (when nbCow = 0)
		if g.Board.currentCase != nil && nbCow > 0 {
			if moves := g.Board.FindPlayableCases(int(g.Board.currentCase.position), int(nbCow)); len(moves) == 0 {
				winner, score1, score2 := g.Board.FindWinner()
				return g.SendWinner(winner, fmt.Sprintf("No move, win by score : %d / %d", score1, score2))
			}
		}
		if moveCase {
			// If no move, end, compute results
			g.Board.MoveCase(e.NextCasePos)
			// Switch player or not
			if switchPlayer {
				g.Board.SwitchPlayer()
			}
			// Test sheriff case
			if g.Board.currentCase.action != nil && g.Board.currentCase.action.IsSheriff() && g.Board.currentCase.PlayAction() {
				// Player current lose
				return g.SendWinner(g.Board.otherPlayer, "looser got a sheriff")
			}
			m = NewServerMessage(g.Board).ToJSON()
		} else {
			m = NewMoveServerMessage(g.Board, g.Board.FindPlayableCases(int(g.Board.currentCase.position), int(nbCow))).ToJSON()
		}

	}
	// Send data to user (player info and board data)

	g.SendToAll("", m)
	return nil
}
示例#26
0
func main() {

	return

	fmt.Println(music.Intersect([]int{1, 3, 5, 6}, []int{2, 3, 4, 5, 6, 7}))
	fmt.Println(music.Intersect([]int{1, 3, 5, 6}, []int{2, 4, 7, 9}))
	fmt.Println(music.Intersect([]int{1, 2, 3, 5, 6, 7}, []int{4, 7, 9}))
	fmt.Println(music.Intersect([]int{4, 7, 9}, []int{1, 2, 3, 5, 6, 7}))

	ti := music.NewTextIndexer()
	ti.Add("aaa", 1)
	ti.Add("aaa", 22)
	ti.Add("aaa", 222)
	ti.Add("cc", 45)
	ti.Add("ccc", 3)
	ti.Add("ccc", 33)
	ti.Add("ccc", 333)
	ti.Add("bbb", 2)
	ti.Add("bbb", 22)
	ti.Add("bbb", 222)
	ti.Add("ddd", 4)
	ti.Add("ggg", 7)
	ti.Add("fff", 6)
	ti.Add("lll", 12)

	ti.Build()

	fmt.Println(ti.Search("bbb"))
	fmt.Println(ti.Search("d"))
	fmt.Println(ti.Search("g"))
	fmt.Println(ti.Search("t"))
	fmt.Println(ti.Search("l"))
	fmt.Println(ti.Search("a"))
	fmt.Println(ti.Search("c"))
	fmt.Println(ti.Search("de"))
	fmt.Println(ti.Search("aab"))
	fmt.Println(ti.Search("bbb a"))

	return

	pathMu := "D:\\test\\audio\\02-II. Dies Irae - Dies Irae.mp3"
	//pathMu := "D:\\test\\audio\\01-I. Requiem.mp3"
	ff, _ := os.Open(pathMu)
	defer ff.Close()
	info := id3.Read(ff)
	logger.GetLogger().Info(info)
	return

	album := "totoand vvc cd 1"
	if p := strings.Index(album, "cd"); p != -1 {
		logger.GetLogger().Info(album[:p] + "d")
	}
	return

	uuu := "http://musicbrainz.org/ws/2/release/?query=artist%3A%22John+Barry%22+AND+release%3A%22you%20only%20live%20twice%22"
	if resp, e := http.Get(uuu); e == nil {
		// Check if release field are present, if not, limit
		d, _ := ioutil.ReadAll(resp.Body)
		var m music.RootResponse
		e := xml.Unmarshal(d, &m)

		logger.GetLogger().Info(e, m)
	}

	return

	searchStr := "Thomas Newman and helmut P.  (ok bob)"
	rrr, _ := regexp.Compile("[a-zA-Z0-9\\.]+")
	logger.GetLogger().Info(len(rrr.FindAllString(searchStr, -1)))
	return

	//artist := "Queen"
	artist := "Alicia%20Keys"
	album = "Unplugged"
	params := "artist:\"" + artist + "\""
	if album != "" {
		params += " AND release:\"" + album + "\""
	}

	u := url.Values{"query": []string{params}}

	params = u.Encode()

	url := "http://musicbrainz.org/ws/2/release/?" + params
	if resp, e := http.Get(url); e == nil {
		// Quota exceed, relaunch after 1000ms
		if resp.StatusCode == 503 {
			time.Sleep(time.Second)
		}
		// Check if release field are present, if not, limit
		d, _ := ioutil.ReadAll(resp.Body)
		var m map[string]string
		e := xml.Unmarshal(d, &m)

		logger.GetLogger().Info(e, m)
	}

	return
	//run()

	//args := arguments.ParseArgs()
	//dico := music.LoadDictionnary(args["workingFolder"])
	//music.IndexArtists(args["workingFolder"])
	//dico.Browse(args["browse"])

	//aa := music.LoadAllAlbums(args["workingFolder"])
	//logger.GetLogger().Info(aa)

	t := []int{2, 4, 6, 8, 10}

	pos := 4
	logger.GetLogger().Info(append(t[:pos], t[pos+1:]...))
	return

	path := "C:\\DataBE\\Bernardo1"

	data, _ := exec.Command("ls", path, "-i1").Output()

	r := bufio.NewReader(bytes.NewBuffer(data))
	for {
		if line, _, error := r.ReadLine(); error == nil {
			info := strings.Split(string(line), " ")
			logger.GetLogger().Info(info[1], "=>", info[0])
		} else {
			break
		}

	}
}
示例#27
0
// Save only new artists
func (ai *ArtistIndex) Save(folder string) {
	is := IndexSaver{ai.artistsToSave, 0}
	logger.GetLogger().Info("Save artists", len(ai.artistsToSave))
	is.Save(filepath.Join(folder, "artist.dico"), false)
}
示例#28
0
func removeSharedSession(id int) {
	logger.GetLogger().Info("Remove share", id)
	delete(sharedSessions, id)
}