func (h *Hub) Run() {
	go newThreadCheck()

	for {
		select {
		case c := <-h.Register:
			h.Connections[c] = true
			l.Output(
				logrus.Fields{
					"New Connection": l.Sprintf(c),
					"Connections":    l.Sprintf(h.Connections),
				},
				"Register websocket",
				l.Debug,
			)
		case c := <-h.Unregister:
			if _, ok := h.Connections[c]; ok {
				l.Output(
					logrus.Fields{
						"New Connection": l.Sprintf(c),
						"Connections":    l.Sprintf(h.Connections),
					},
					"Unregister websocket",
					l.Debug,
				)
				delete(h.Connections, c)
				close(c.send)
			}
		case me := <-h.Broadcast:
			l.Output(
				logrus.Fields{
					"Broad Cast":  l.Sprintf(me),
					"Connections": l.Sprintf(h.Connections),
				},
				"Broad Cast websocket",
				l.Debug,
			)
			for c := range h.Connections {
				select {
				case c.send <- me:
				default:
					close(c.send)
					delete(h.Connections, c)
				}
			}
		}
	}
}
func PostApplyScoreData(teamName string, ApplyScore *PostApplyScore) (*Status, error) {
	l.PutInfo(l.I_M_PostPage, teamName, ApplyScore)

	//更新情報をGlobal変数に格納する
	defer SetPlayerCol(ApplyScore.UserIds)

	AUserIdInTheTeam := teams[teamName].UserIds[0]
	if players[AUserIdInTheTeam].Apply != 0 {
		l.Output(
			logrus.Fields{
				"User Apply": l.Sprintf(players[AUserIdInTheTeam].Apply),
			},
			"Apply score is already registered",
			l.Debug,
		)
		return &Status{"already registered"}, nil
	}
	for playerIndex, userId := range ApplyScore.UserIds {

		findQuery := bson.M{"userid": userId}
		setQuery := bson.M{"$set": bson.M{"apply": ApplyScore.Apply[playerIndex]}}
		if err = UpdateMongoData("player", findQuery, setQuery); err != nil {
			l.PutErr(err, l.Trace(), l.E_M_Update, ApplyScore.Apply[playerIndex])
			return &Status{"failed"}, err
		}
	}

	return &Status{"success"}, nil
}
// writePump pumps messages from the hub to the websocket connection.
func (c *connection) writePump() {
	ticker := time.NewTicker(pingPeriod)
	defer func() {
		ticker.Stop()
		c.ws.Close()
	}()
	for {
		select {
		case threadToResponse, ok := <-c.send:
			if !ok {
				c.write(websocket.CloseMessage, []byte{})
				return
			}
			if err := c.ws.WriteJSON(threadToResponse); err != nil {
				l.Output(
					logrus.Fields{
						l.ErrMsg:   l.ErrToStr(err),
						l.TraceMsg: l.TraceToStr(l.Trace()),
						"Thread":   l.Sprintf(threadToResponse),
					},
					"can not write JSON",
					l.Debug,
				)
				return
			}
		case <-ticker.C:
			if err := c.write(websocket.PingMessage, []byte{}); err != nil {
				l.PutErr(err, l.Trace(), l.E_R_PingMsg, websocket.PingMessage)
				return
			}
		}
	}
}
// readPump pumps messages from the websocket connection to the hub.
func (c *connection) readPump() {
	defer func() {
		H.Unregister <- c
		c.ws.Close()
	}()
	c.ws.SetReadLimit(maxMessageSize)
	c.ws.SetReadDeadline(time.Now().Add(pongWait))
	c.ws.SetPongHandler(func(string) error { c.ws.SetReadDeadline(time.Now().Add(pongWait)); return nil })
	for {

		err := c.ws.ReadJSON(&thread)
		if err != nil {
			if thread == nil {
				break
			}
			l.Output(
				logrus.Fields{
					l.ErrMsg:   l.ErrToStr(err),
					l.TraceMsg: l.TraceToStr(l.Trace()),
					"Thread":   l.Sprintf(thread),
				},
				"can not read JSON or Closed Websocket",
				l.Debug,
			)
			break
		}

		if newThread, err = m.UpdateExistingTimeLine(thread); err != nil {
			l.PutErr(err, l.Trace(), l.E_R_Upsert, thread)
		}

		H.Broadcast <- newThread
	}
}
func newThreadCheck() {
	for {
		select {
		case t := <-m.ThreadChan:
			l.Output(
				logrus.Fields{"Threa Chain": l.Sprintf(t)},
				"New Thread websocket",
				l.Debug,
			)

			H.Broadcast <- t
		}
	}
}
func getCol(req *restful.Request, resp *restful.Response) {
	col := req.PathParameter("col")

	l.Output(
		logrus.Fields{"Collection": l.Sprintf(col)},
		"Get access to collection router",
		l.Debug,
	)

	if col == "player" || col == "field" || col == "team" {
		data, err := m.GetAllColData(col)
		if err != nil {
			panic(err)
		}
		resp.WriteAsJson(data)
	}
}
func register(req *restful.Request, resp *restful.Response) {
	date := req.PathParameter("date")
	collection := req.PathParameter("collection")
	if origin := req.HeaderParameter(restful.HEADER_Origin); origin != "" {
		if len(resp.Header().Get(restful.HEADER_AccessControlAllowOrigin)) == 0 {
			resp.AddHeader(restful.HEADER_AccessControlAllowOrigin, origin)
		}
	}

	l.Output(
		logrus.Fields{
			"Date":       date,
			"Collection": collection,
			"Request":    l.Sprintf(req),
			"Response":   l.Sprintf(resp),
		},
		"Post access to register router",
		l.Debug,
	)

	switch collection {

	case "user":

		userCols := new([]m.UserCol)
		if err := req.ReadEntity(userCols); err != nil {
			resp.WriteErrorString(http.StatusBadRequest, err.Error())
			return
		}

		status, err := m.RegisterUserColData(*userCols)
		if err != nil {
			l.PutErr(err, l.Trace(), l.E_R_RegisterCol, userCols)
		}
		resp.WriteAsJson(status)

	case "team":

		teamCols := new([]m.TeamCol)
		if err := req.ReadEntity(teamCols); err != nil {
			resp.WriteErrorString(http.StatusBadRequest, err.Error())
			return
		}

		status, err := m.RegisterTeamColData(date, *teamCols)
		if err != nil {
			l.PutErr(err, l.Trace(), l.E_R_RegisterCol, teamCols)
		}
		resp.WriteAsJson(status)

	case "field":

		fieldCols := new([]m.FieldCol)
		if err := req.ReadEntity(fieldCols); err != nil {
			resp.WriteErrorString(http.StatusBadRequest, err.Error())
			return
		}

		status, err := m.RegisterFieldColData(date, *fieldCols)
		if err != nil {
			l.PutErr(err, l.Trace(), l.E_R_RegisterCol, fieldCols)
		}
		resp.WriteAsJson(status)

	case "thread":

		requestTakePictureStatus := new(m.RequestTakePictureStatus)
		if err := req.ReadEntity(requestTakePictureStatus); err != nil {
			resp.WriteErrorString(http.StatusBadRequest, err.Error())
			return
		}

		status, err := m.RegisterThreadImg(requestTakePictureStatus)
		if err != nil {
			l.PutErr(err, l.Trace(), l.E_R_RegisterCol, requestTakePictureStatus)
		}

		resp.WriteAsJson(status)
	}
}
func postOne(req *restful.Request, resp *restful.Response) {
	page := req.PathParameter("page")
	team := req.PathParameter("team")
	hole := req.PathParameter("hole")
	if origin := req.HeaderParameter(restful.HEADER_Origin); origin != "" {
		if len(resp.Header().Get(restful.HEADER_AccessControlAllowOrigin)) == 0 {
			resp.AddHeader(restful.HEADER_AccessControlAllowOrigin, origin)
		}
	}

	l.Output(
		logrus.Fields{
			"Page":     page,
			"Team":     team,
			"Hole":     hole,
			"Request":  l.Sprintf(req),
			"Response": l.Sprintf(resp),
		},
		"Post access to page router",
		l.Debug,
	)
	switch page {

	case "login":

		loginInfo := new(m.PostLogin)
		err := req.ReadEntity(loginInfo)
		if err != nil { // bad request
			resp.WriteErrorString(http.StatusBadRequest, err.Error())
			return
		}

		status, err := m.PostLoginPageData(loginInfo)
		if err != nil {
			l.PutErr(err, l.Trace(), l.E_R_PostPage, loginInfo)
		}
		resp.WriteAsJson(status)

	case "scoreViewSheet":

		definedTeam := new(m.PostDefinedTeam)
		err := req.ReadEntity(definedTeam)
		if err != nil { // bad request
			resp.WriteErrorString(http.StatusBadRequest, err.Error())
			return
		}

		status, err := m.PostScoreViewSheetPageData(team, definedTeam)
		if err != nil {
			l.PutErr(err, l.Trace(), l.E_R_PostPage, definedTeam)
		}
		resp.WriteAsJson(status)

	case "scoreEntrySheet":

		updatedTeamScore := new(m.PostTeamScore)
		err := req.ReadEntity(updatedTeamScore)
		if err != nil { // bad request
			resp.WriteErrorString(http.StatusBadRequest, err.Error())
			return
		}

		status, err := m.PostScoreEntrySheetPageData(team, hole, updatedTeamScore)
		if err != nil {
			l.PutErr(err, l.Trace(), l.E_R_PostPage, updatedTeamScore)
		}
		resp.WriteAsJson(status)

	case "applyScore":
		if hole != "" {
			return
		}
		registeredApplyScore := new(m.PostApplyScore)
		err := req.ReadEntity(registeredApplyScore)
		if err != nil {
			resp.WriteErrorString(http.StatusBadRequest, err.Error())
			return
		}

		status, err := m.PostApplyScoreData(team, registeredApplyScore)
		if err != nil {
			l.PutErr(err, l.Trace(), l.E_R_PostPage, registeredApplyScore)
		}
		resp.WriteAsJson(status)
	}
}
func PostLoginPageData(loginInfo *PostLogin) (*LoginStatus, error) {

	l.PutInfo(l.I_M_PostPage, loginInfo, nil)

	var admin bool
	_, ok := users[loginInfo.UserId]
	if ok {
		var teamName string
		for _, team := range teams {
			for _, userid := range team.UserIds {
				if userid == loginInfo.UserId {
					teamName = team.Name
				}
			}
		}

		l.Output(
			logrus.Fields{
				"User ID":   loginInfo.UserId,
				"User Name": users[loginInfo.UserId].Name,
			},
			"login success",
			l.Debug,
		)

		if players[loginInfo.UserId].Admin == true {
			admin = true
		} else {
			admin = false
		}
		loginStatus := &LoginStatus{
			Status:   "success",
			UserId:   loginInfo.UserId,
			UserName: users[loginInfo.UserId].Name,
			Team:     teamName,
			Admin:    admin,
		}
		return loginStatus, nil
	} else {
		l.Output(
			logrus.Fields{
				"User ID": loginInfo.UserId,
			},
			"login faild",
			l.Debug,
		)
		return &LoginStatus{Status: "failed"}, nil
	}
}
示例#10
0
func shutdownHook() {
	sigs := make(chan os.Signal, 1)
	signal.Notify(sigs, syscall.SIGINT, syscall.SIGTERM)
	<-sigs
	l.Output(nil, "Shutdown", l.Info)
	os.Exit(0)
}
func RequestTakePicture(userIds []string) (*RequestTakePictureStatus, error) {

	db, session := mongoConn()
	col := db.C("thread")
	defer session.Close()

	threadCol := ThreadCol{}
	for _, userId := range userIds {
		findQuery := bson.M{"imgurl": "", "userid": userId}
		if err = col.Find(findQuery).One(&threadCol); err != nil {
			l.Output(
				logrus.Fields{"User Id": userId, "User Name": users[userId].Name},
				"Need not take any picture",
				l.Debug,
			)
		}

		if len(threadCol.ThreadId) != 0 {
			requestTakePictureStatus := &RequestTakePictureStatus{
				Status:      "take a picture",
				UserId:      threadCol.UserId,
				TeamUserIds: userIds,
				Name:        users[threadCol.UserId].Name,
				Positive:    threadCol.Positive,
				ThreadId:    threadCol.ThreadId,
				ThreadMsg:   threadCol.Msg,
				PhotoUrl:    "",
			}

			return requestTakePictureStatus, nil
		}
	}
	return &RequestTakePictureStatus{Status: "success"}, nil
}
示例#12
0
func getPage(req *restful.Request, resp *restful.Response) {
	var page, team, hole string
	url := strings.Split(req.PathParameter("page"), "/")

	l.Output(
		logrus.Fields{"Page": page, "Team": team, "Hole": hole, "URL": url},
		"Get access to page router",
		l.Debug,
	)
	page = url[0]
	if len(url) > 1 {
		team = url[1]
	}
	if len(url) > 2 {
		hole = url[2]
	}

	switch page {
	case "index":
		if team != "" || hole != "" {
			return
		}
		data, err := m.GetIndexPageData()
		if err != nil {
			panic(err)
		}
		resp.WriteAsJson(data)

	case "leadersBoard":
		if team != "" || hole != "" {
			return
		}
		data, err := m.GetLeadersBoardPageData()
		if err != nil {
			panic(err)
		}
		resp.WriteAsJson(data)

	case "scoreEntrySheet":
		data, err := m.GetScoreEntrySheetPageData(team, hole)
		if err != nil {
			panic(err)
		}
		resp.WriteAsJson(data)

	case "scoreViewSheet":
		if hole != "" {
			return
		}
		data, err := m.GetScoreViewSheetPageData(team)
		if err != nil {
			panic(err)
		}
		resp.WriteAsJson(data)

	case "entireScore":

		data, err := m.GetEntireScorePageData()
		if err != nil {
			panic(err)
		}
		resp.WriteAsJson(data)

	case "timeLine":

		data, err := m.GetTimeLinePageData()
		if err != nil {
			panic(err)
		}
		resp.WriteAsJson(data)

	default:
		resp.WriteErrorString(
			http.StatusNotFound,
			"404: Page is not found.",
		)
	}
}