Пример #1
0
func ListenAndServer(host string, ns *notification.Sender) {
	notificationSender = ns
	l, err := net.Listen("tcp", host)
	if err != nil {
		log.Println("TcpSocket Error listening:", err.Error())
		os.Exit(1)
	}

	println("Starting tcp server...")

	defer l.Close()

	defer close(*events.GetNewVoteChan())
	defer close(*events.GetVoteUpdateChan())
	defer close(*events.GetNewSocketsChan())
	defer close(*events.GetClosedSocketsChan())

	go ListenToEvents()

	for {
		conn, err := l.Accept()
		if err != nil {
			log.Println("TcpSocket Error accepting: ", err.Error())
			os.Exit(1)
		}

		go HandleNewConnection(conn)
	}
}
Пример #2
0
func ListenToEvents() {
	clients := make([]*events.SomeSocket, 0, 1024)
	clientsCounter := 0
	for {
		select {
		case newVoteEvent := <-*events.GetNewVoteChan():
			for _, client := range clients {
				client.NewVoteEvent <- &newVoteEvent
			}
		case voteUpdateEvent := <-*events.GetVoteUpdateChan():
			for _, client := range clients {
				client.VoteUpdEvent <- &voteUpdateEvent
			}
		case newSocketEvent := <-*events.GetNewSocketsChan():
			clientsCounter++
			newSocketEvent.Socket.Id = strconv.Itoa(clientsCounter)
			clients = append(clients, newSocketEvent.Socket)
		case socketClosedEvent := <-*events.GetClosedSocketsChan():
			id := socketClosedEvent.Socket.Id
			index := 0
			for i, socket := range clients {
				if socket.Id == id {
					index = i
				}
			}

			clients = append(clients[:index], clients[index+1:]...)
		}
	}
}
Пример #3
0
func ListenAndServer(host string, ns *notification.Sender, dbconn string) {
	notificationSender = ns
	dbConnectionAddress = dbconn

	l, err := net.Listen("tcp", host)
	if err != nil {
		log.Error.Printf("TcpSocket Error listening: %s\n", err.Error())
		os.Exit(1)
	}

	defer l.Close()

	defer close(*events.GetNewVoteChan())
	defer close(*events.GetVoteUpdateChan())
	defer close(*events.GetNewSocketsChan())
	defer close(*events.GetClosedSocketsChan())

	go ListenToEvents()

	for {
		conn, err := l.Accept()
		if err != nil {
			log.Error.Printf("TcpSocket Error accepting: %s\n", err.Error())
			os.Exit(1)
		}

		go handleNewConnection(conn)
	}
}
Пример #4
0
func createVote(w http.ResponseWriter, r *http.Request, _ httprouter.Params) {
	funcPrefix := "New vote creation"
	log.Debug.Printf("%s: start\n", funcPrefix)
	defer log.Debug.Printf("%s: end\n", funcPrefix)
	log.Debug.Printf("%s: authenticating user...\n", funcPrefix)
	user, error := authenticate(r.Header.Get("auth_token"))
	if error != nil {
		log.Error.Printf("%s: user authentication failed\n", funcPrefix)
		w.WriteHeader(400)
		return
	}

	var params ParamSt
	log.Debug.Printf("%s: decoding params...\n", funcPrefix)
	err := json.NewDecoder(r.Body).Decode(&params)
	if err != nil {
		log.Error.Printf("%s: decoding params failed: %s\n", funcPrefix, err.Error())
		w.WriteHeader(400)
		return
	}

	log.Debug.Printf("%s: adding new vote to storage...\n", funcPrefix)
	vote := storage.NewVote(params.Name, user.Id)

	// i think better use new goroutine
	go func() {
		log.Debug.Printf("%s: getting users from storage...\n", funcPrefix)
		users, _ := storage.GetUsers()
		log.Debug.Printf("%s: sending notifications to users...\n", funcPrefix)
		notificationSender.Send(users, *vote)
	}()

	log.Debug.Printf("%s: getting vote result status...\n", funcPrefix)
	res := storage.GetVoteResultStatus(*vote, *user)

	log.Debug.Printf("%s: sending new vote event...\n", funcPrefix)
	*events.GetNewVoteChan() <- events.NewVoteEvent{res}

	log.Info.Printf("%s: new vote '%s' has been succesfully created!\n", funcPrefix, params.Name)

	w.Header().Set("Content-Type", "application/json; charset=utf-8")
	w.Header().Set("Access-Control-Allow-Origin", "*")
	w.Header().Set("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, OPTIONS")
	w.Header().Set("Access-Control-Allow-Headers", "*")
	if json.NewEncoder(w).Encode(res) != nil {
		log.Error.Printf("%s: encoding response failed\n", funcPrefix)
		w.WriteHeader(500)
	}
}
func (s *TcpSocket) handleNewVote(packet *PulsePacket) {
	funcPrefix := "New vote creation"
	log.Debug.Printf("%s: start\n", funcPrefix)
	defer log.Debug.Printf("%s: end\n", funcPrefix)

	storageConnection := storage.NewStorageConnection(dbConnectionAddress)
	defer storageConnection.CloseStorageConnection()

	var params CSCreateVoteRequest
	log.Debug.Printf("%s: unmarshaling params...\n", funcPrefix)
	err := json.Unmarshal(packet.content, &params)
	if err != nil {
		log.Error.Printf("%s: unmarshaling params failed: %s\n", funcPrefix, err.Error())
		return
	}

	log.Debug.Printf("%s: adding new vote to storage...\n", funcPrefix)
	vote, err1 := storageConnection.NewVote(params.Name, s.user.Id)
	if err1 != nil {
		log.Error.Printf("%s: adding vote '%s' to storage failed: %s\n", funcPrefix, params.Name, err.Error())
		return
	}

	log.Debug.Printf("%s: getting vote result status...\n", funcPrefix)
	res, err2 := storageConnection.GetVoteResultStatus(*vote, s.user, storageConnection.UsersCount())
	if err2 != nil {
		log.Error.Printf("%s: getting vote result status failed: %s\n", funcPrefix, err.Error())
		return
	}

	log.Debug.Printf("%s: getting users from storage...\n", funcPrefix)
	users, _ := storageConnection.GetUsers()
	log.Debug.Printf("%s: removing vote creator from notification list...\n", funcPrefix)
	for p, v := range users {
		if s.user.Id == v.Id {
			users = append(users[:p], users[p+1:]...)
			log.Debug.Printf("%s: vote creator has been found and succesfully removed from the list\n", funcPrefix)
			break
		}
	}
	log.Debug.Printf("%s: sending notifications to users...\n", funcPrefix)
	notificationSender.Send(users, res, dbConnectionAddress)

	log.Debug.Printf("%s: sending new vote event...\n", funcPrefix)
	*events.GetNewVoteChan() <- events.NewVoteEvent{res}

	log.Info.Printf("%s: new vote '%s' has been succesfully created!\n", funcPrefix, params.Name)
}
Пример #6
0
func (s *TcpSocket) handleNewVote(packet *PulsePucket) {
	var params CSCreateVoteRequest
	err := json.Unmarshal(packet.content, &params)
	if err != nil {
		fmt.Println(err)
		return
	}

	vote := storage.NewVote(params.Name, s.user.Id)

	res := storage.GetVoteResultStatus(*vote, s.user)

	go func() {
		users, _ := storage.GetUsers()
		notificationSender.Send(users, *vote)
	}()

	*events.GetNewVoteChan() <- events.NewVoteEvent{res}
}
func ListenToEvents() {
	funcPrefix := "Processing socket managing events"
	log.Debug.Printf("%s: start\n", funcPrefix)
	defer log.Debug.Printf("%s: end\n", funcPrefix)

	clients := make([]*events.SomeSocket, 0, 1024)
	clientsCounter := 0
	for {
		select {
		case newVoteEvent := <-*events.GetNewVoteChan():
			log.Debug.Printf("%s: handling vote create event\n", funcPrefix)
			for _, client := range clients {
				client.NewVoteEvent <- &newVoteEvent
			}
		case voteUpdateEvent := <-*events.GetVoteUpdateChan():
			log.Debug.Printf("%s: handling vote update event\n", funcPrefix)
			for _, client := range clients {
				client.VoteUpdEvent <- &voteUpdateEvent
			}
		case newSocketEvent := <-*events.GetNewSocketsChan():
			log.Debug.Printf("%s: handling socket connection create event\n", funcPrefix)
			clientsCounter++
			newSocketEvent.Socket.Id = strconv.Itoa(clientsCounter)
			clients = append(clients, newSocketEvent.Socket)
		case socketClosedEvent := <-*events.GetClosedSocketsChan():
			log.Debug.Printf("%s: handling socket connection close event\n", funcPrefix)
			id := socketClosedEvent.Socket.Id
			index := 0
			for i, socket := range clients {
				if socket.Id == id {
					index = i
				}
			}
			clients = append(clients[:index], clients[index+1:]...)
		}
	}
}
func createVote(w http.ResponseWriter, r *http.Request, _ httprouter.Params) {
	funcPrefix := "New vote creation"
	log.Debug.Printf("%s: start\n", funcPrefix)
	defer log.Debug.Printf("%s: end\n", funcPrefix)

	storageConnection := storage.NewStorageConnection(dbConnectionAddress)
	defer storageConnection.CloseStorageConnection()

	log.Debug.Printf("%s: authenticating user...\n", funcPrefix)
	user, error := storageConnection.Authenticate(r.Header.Get("auth_token"))
	if error != nil {
		log.Error.Printf("%s: user authentication failed\n", funcPrefix)
		w.WriteHeader(400)
		return
	}

	var params ParamSt
	log.Debug.Printf("%s: decoding params...\n", funcPrefix)
	err := json.NewDecoder(r.Body).Decode(&params)
	if err != nil {
		log.Error.Printf("%s: decoding params failed: %s\n", funcPrefix, err.Error())
		w.WriteHeader(400)
		return
	}

	log.Debug.Printf("%s: adding new vote to storage...\n", funcPrefix)
	vote, err := storageConnection.NewVote(params.Name, user.Id)
	if err != nil {
		log.Error.Printf("%s: adding vote '%s' to storage failed: %s\n", funcPrefix, params.Name, err.Error())
		return
	}

	log.Debug.Printf("%s: getting vote result status...\n", funcPrefix)
	res, err := storageConnection.GetVoteResultStatus(*vote, *user, storageConnection.UsersCount())
	if err != nil {
		log.Error.Printf("%s: getting vote result status failed: %s\n", funcPrefix, err.Error())
		w.WriteHeader(400)
		return
	}

	log.Debug.Printf("%s: getting users from storage...\n", funcPrefix)
	users, _ := storageConnection.GetUsers()
	log.Debug.Printf("%s: removing vote creator from notification list...\n", funcPrefix)
	for p, v := range users {
		if user.Id == v.Id {
			users = append(users[:p], users[p+1:]...)
			log.Debug.Printf("%s: vote creator has been found and succesfully removed from the list\n", funcPrefix)
			break
		}
	}
	log.Debug.Printf("%s: sending notifications to users...\n", funcPrefix)
	notificationSender.Send(users, res, dbConnectionAddress)

	log.Debug.Printf("%s: sending new vote event...\n", funcPrefix)
	*events.GetNewVoteChan() <- events.NewVoteEvent{Vote: res}

	log.Info.Printf("%s: new vote '%s' has been succesfully created!\n", funcPrefix, params.Name)

	w.Header().Set("Content-Type", "application/json; charset=utf-8")
	w.Header().Set("Access-Control-Allow-Origin", "*")
	w.Header().Set("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, OPTIONS")
	w.Header().Set("Access-Control-Allow-Headers", "*")
	if json.NewEncoder(w).Encode(res) != nil {
		log.Error.Printf("%s: encoding response failed\n", funcPrefix)
		w.WriteHeader(500)
	}
}