Feat: turn timer
This commit is contained in:
		
							
								
								
									
										60
									
								
								handlers/timer.go
									
									
									
									
									
										Normal file
									
								
							
							
						
						
									
										60
									
								
								handlers/timer.go
									
									
									
									
									
										Normal file
									
								
							| @@ -0,0 +1,60 @@ | ||||
| package handlers | ||||
|  | ||||
| import ( | ||||
| 	"gralias/models" | ||||
| 	"sync" | ||||
| 	"time" | ||||
| ) | ||||
|  | ||||
| var ( | ||||
| 	timers = make(map[string]*time.Ticker) | ||||
| 	mu     sync.Mutex | ||||
| ) | ||||
|  | ||||
| func StartTurnTimer(roomID string, duration time.Duration) { | ||||
| 	mu.Lock() | ||||
| 	defer mu.Unlock() | ||||
|  | ||||
| 	if _, exists := timers[roomID]; exists { | ||||
| 		return // Timer already running | ||||
| 	} | ||||
| 	ticker := time.NewTicker(1 * time.Second) | ||||
| 	timers[roomID] = ticker | ||||
| 	go func() { | ||||
| 		for range ticker.C { | ||||
| 			room, err := getRoomByID(roomID) | ||||
| 			if err != nil { | ||||
| 				log.Error("failed to get room by id", "error", err) | ||||
| 				StopTurnTimer(roomID) | ||||
| 				return | ||||
| 			} | ||||
| 			if room.Settings.TurnSecondsLeft == 0 { | ||||
| 				log.Info("turn time is over", "room_id", roomID) | ||||
| 				room.ChangeTurn() | ||||
| 				room.MimeDone = false | ||||
| 				if err := saveRoom(room); err != nil { | ||||
| 					log.Error("failed to save room", "error", err) | ||||
| 				} | ||||
| 				notify(models.NotifyRoomUpdatePrefix+room.ID, "") | ||||
| 				notifyBotIfNeeded(room) | ||||
| 				StopTurnTimer(roomID) | ||||
| 				return | ||||
| 			} | ||||
| 			room.Settings.TurnSecondsLeft-- | ||||
| 			if err := saveRoom(room); err != nil { | ||||
| 				log.Error("failed to save room", "error", err) | ||||
| 			} | ||||
| 			notify(models.NotifyRoomUpdatePrefix+room.ID, "") | ||||
| 		} | ||||
| 	}() | ||||
| } | ||||
|  | ||||
| func StopTurnTimer(roomID string) { | ||||
| 	mu.Lock() | ||||
| 	defer mu.Unlock() | ||||
|  | ||||
| 	if ticker, exists := timers[roomID]; exists { | ||||
| 		ticker.Stop() | ||||
| 		delete(timers, roomID) | ||||
| 	} | ||||
| } | ||||
		Reference in New Issue
	
	Block a user
	 Grail Finder
					Grail Finder