func (s *Service) handleCounter(msg sarif.Message) { if msg.Text == "" { s.ReplyBadRequest(msg, errors.New("Please specify a counter name!")) return } name := msg.Text cnt, err := s.counterGet(name) if err != nil { s.ReplyInternalError(msg, err) return } newCnt := cnt if msg.IsAction("cmd/decrement") { newCnt-- } else if msg.IsAction("cmd/increment") { newCnt++ } if newCnt != cnt { if err := s.counterSet(name, newCnt); err != nil { s.ReplyInternalError(msg, err) return } } s.Reply(msg, sarif.CreateMessage("counter/changed/"+name, &counterMessage{name, newCnt})) }
func (s *Server) clientIsAllowed(client string, msg sarif.Message) bool { allowed, ok := s.cfg.AllowedActions[client] if !ok { return true } for _, action := range allowed { if msg.IsAction(action) { return true } } return false }
func checkErr(reply sarif.Message, ok bool) error { if !ok { return ErrNoReply } if reply.IsAction("err/notfound") { return ErrNotFound } if reply.IsAction("err") { return errors.New(reply.Text) } return nil }
func (s *Service) handleQuestionAnswer(msg sarif.Message) { if msg.IsAction("question/answer/ultimate") { reply := "Wrong. The answer is 42." if msg.Text == "42" { reply = "Precisely." } s.Reply(msg, sarif.Message{ Action: "question/accepted", Text: reply, }) return } s.Reply(msg, sarif.Message{ Action: "err/question/unknown", Text: "I can't remember asking you a question.", }) }
func (s *Service) handleLog(msg sarif.Message) { targets := make(map[string]struct{}) for action, target := range s.Cfg.Actions { if msg.IsAction(action) { targets[target] = struct{}{} } } lm := LogMessage{time.Now(), msg} s.mutex.Lock() defer s.mutex.Unlock() for target := range targets { if target == "" { continue } raw, _ := json.Marshal(lm) if err := s.writeTarget(target, string(raw)); err != nil { log.Println("[log] write error:", err) } } }
func (s *Service) handleEventNew(msg sarif.Message) { isTargeted := msg.IsAction("event/new") var e Event e.Text = msg.Text e.Time = time.Now() e.Value = 1 if s, v, ok := parseDataFromAction(msg.Action, "event/new"); ok { e.Action, e.Value = s, v } if err := msg.DecodePayload(&e); err != nil && isTargeted { s.ReplyBadRequest(msg, err) return } if err := msg.DecodePayload(&e.Meta); err != nil { s.ReplyBadRequest(msg, err) return } if e.Time.IsZero() { e.Time = time.Now() } if _, err := s.Store.Put(e.Key(), &e); err != nil { s.Log("err/internal", "could not store finished task: "+err.Error()) return } if isTargeted { reply := sarif.Message{Action: "event/created"} if err := reply.EncodePayload(e); err != nil { s.ReplyInternalError(msg, err) return } reply.Text = "New event: " + e.String() s.Reply(msg, reply) } }