Download main.go from Spocklet/pomodo: direct link, hf CLI and curl.
- Browser
- Download file 17.7 kB
-
https://huggingface.co/spaces/Spocklet/pomodo/resolve/main/main.go
- Command line
-
hf download hf://spaces/Spocklet/pomodo/main.go
-
curl -L -o main.go https://huggingface.co/spaces/Spocklet/pomodo/resolve/main/main.go
17.7 kB
| package main | |
| import ( | |
| "flag" | |
| "fmt" | |
| "log" | |
| "net/http" | |
| "sort" | |
| "strings" | |
| "sync" | |
| "time" | |
| "github.com/gorilla/websocket" | |
| ) | |
| // --- CONFIG --- | |
| var addr = flag.String("addr", ":8080", "http service address") | |
| // --- DATA STRUCTURES --- | |
| // The JSON object sent to all clients | |
| type RoomState struct { | |
| TimeLeft int `json:"timeLeft"` | |
| TotalTime int `json:"totalTime"` // To show progress bar | |
| IsRunning bool `json:"isRunning"` | |
| Mode string `json:"mode"` // "WORK", "BREAK", "MEETING" | |
| Users []string `json:"users"` // List of connected names | |
| TimerEnded bool `json:"timerEnded"` // Triggers the "Pick Next" UI | |
| } | |
| // Internal User tracking | |
| type Client struct { | |
| Conn *websocket.Conn | |
| Name string | |
| } | |
| type Room struct { | |
| Name string | |
| Clients map[*websocket.Conn]*Client | |
| State RoomState | |
| Broadcast chan bool // Signal to push update | |
| Mutex sync.Mutex | |
| StopChan chan bool | |
| } | |
| type Manager struct { | |
| Rooms map[string]*Room | |
| Mutex sync.Mutex | |
| } | |
| var manager = Manager{Rooms: make(map[string]*Room)} | |
| var upgrader = websocket.Upgrader{CheckOrigin: func(r *http.Request) bool { return true }} | |
| // --- SERVER MAIN --- | |
| func main() { | |
| flag.Parse() | |
| http.HandleFunc("/", serveHome) | |
| http.HandleFunc("/ws/", serveWs) | |
| fmt.Printf("/// CUCKOO CLONE RUNNING ///\n") | |
| fmt.Printf("Share this link: http://localhost%s/team-name\n", *addr) | |
| log.Fatal(http.ListenAndServe(*addr, nil)) | |
| } | |
| // --- ROOM LOGIC --- | |
| func (m *Manager) GetRoom(name string) *Room { | |
| m.Mutex.Lock() | |
| defer m.Mutex.Unlock() | |
| if room, ok := m.Rooms[name]; ok { | |
| return room | |
| } | |
| newRoom := &Room{ | |
| Name: name, | |
| Clients: make(map[*websocket.Conn]*Client), | |
| State: RoomState{TimeLeft: 1500, TotalTime: 1500, IsRunning: false, Mode: "WORK", TimerEnded: false}, | |
| Broadcast: make(chan bool), | |
| StopChan: make(chan bool), | |
| } | |
| m.Rooms[name] = newRoom | |
| go newRoom.Run() | |
| return newRoom | |
| } | |
| func (r *Room) Run() { | |
| for { | |
| <-r.Broadcast | |
| r.PushState() | |
| } | |
| } | |
| func (r *Room) PushState() { | |
| r.Mutex.Lock() | |
| defer r.Mutex.Unlock() | |
| // Build user list | |
| var userNames []string | |
| for _, c := range r.Clients { | |
| if c.Name != "" { | |
| userNames = append(userNames, c.Name) | |
| } | |
| } | |
| sort.Strings(userNames) | |
| r.State.Users = userNames | |
| // Send to all | |
| for conn := range r.Clients { | |
| err := conn.WriteJSON(r.State) | |
| if err != nil { | |
| conn.Close() | |
| delete(r.Clients, conn) | |
| } | |
| } | |
| } | |
| func (r *Room) StartTimer() { | |
| r.Mutex.Lock() | |
| if r.State.IsRunning { | |
| r.Mutex.Unlock() | |
| return | |
| } | |
| r.State.IsRunning = true | |
| r.State.TimerEnded = false | |
| r.Mutex.Unlock() | |
| r.Broadcast <- true | |
| go func() { | |
| ticker := time.NewTicker(1 * time.Second) | |
| defer ticker.Stop() | |
| for { | |
| select { | |
| case <-r.StopChan: | |
| return | |
| case <-ticker.C: | |
| r.Mutex.Lock() | |
| if !r.State.IsRunning { | |
| r.Mutex.Unlock() | |
| return | |
| } | |
| if r.State.TimeLeft > 0 { | |
| r.State.TimeLeft-- | |
| r.Mutex.Unlock() | |
| r.Broadcast <- true | |
| } else { | |
| // Time is up! | |
| r.State.IsRunning = false | |
| r.State.TimerEnded = true | |
| r.Mutex.Unlock() | |
| r.Broadcast <- true | |
| return | |
| } | |
| } | |
| } | |
| }() | |
| } | |
| func (r *Room) StopTimer() { | |
| r.Mutex.Lock() | |
| if r.State.IsRunning { | |
| r.State.IsRunning = false | |
| go func() { r.StopChan <- true }() | |
| } | |
| r.Mutex.Unlock() | |
| r.Broadcast <- true | |
| } | |
| func (r *Room) SetMode(minutes int, mode string) { | |
| r.StopTimer() // Ensure stopped | |
| r.Mutex.Lock() | |
| r.State.TimeLeft = minutes * 60 | |
| r.State.TotalTime = minutes * 60 | |
| r.State.Mode = mode | |
| r.State.TimerEnded = false | |
| r.Mutex.Unlock() | |
| r.Broadcast <- true | |
| } | |
| // --- WEBSOCKET HANDLER --- | |
| func serveWs(w http.ResponseWriter, r *http.Request) { | |
| parts := strings.Split(r.URL.Path, "/") | |
| if len(parts) < 3 { | |
| return | |
| } | |
| roomName := parts[2] | |
| room := manager.GetRoom(roomName) | |
| ws, err := upgrader.Upgrade(w, r, nil) | |
| if err != nil { | |
| return | |
| } | |
| client := &Client{Conn: ws, Name: ""} | |
| room.Mutex.Lock() | |
| room.Clients[ws] = client | |
| room.Mutex.Unlock() | |
| // Wait for login | |
| for { | |
| var msg map[string]interface{} | |
| err := ws.ReadJSON(&msg) | |
| if err != nil { | |
| room.Mutex.Lock() | |
| delete(room.Clients, ws) | |
| room.Mutex.Unlock() | |
| room.Broadcast <- true // Update user list on disconnect | |
| break | |
| } | |
| action, _ := msg["type"].(string) | |
| // HANDLE ACTIONS | |
| switch action { | |
| case "LOGIN": | |
| name, _ := msg["name"].(string) | |
| // Simple sanitization | |
| if len(name) > 12 { | |
| name = name[:12] | |
| } | |
| client.Name = name | |
| room.Broadcast <- true | |
| case "START": | |
| room.StartTimer() | |
| case "STOP": | |
| room.StopTimer() | |
| case "SET": | |
| dur, _ := msg["duration"].(float64) | |
| mode, _ := msg["mode"].(string) | |
| room.SetMode(int(dur), mode) | |
| } | |
| } | |
| } | |
| // --- HTML SERVING --- | |
| func serveHome(w http.ResponseWriter, r *http.Request) { | |
| if r.URL.Path == "/" { | |
| http.Redirect(w, r, "/dev-team", http.StatusFound) | |
| return | |
| } | |
| roomName := strings.TrimPrefix(r.URL.Path, "/") | |
| html := strings.Replace(htmlContent, "{{ROOM_NAME}}", roomName, -1) | |
| w.Write([]byte(html)) | |
| } | |
| // --- FRONTEND CODE --- | |
| var htmlContent = ` | |
| <!DOCTYPE html> | |
| <html lang="en"> | |
| <head> | |
| <meta charset="UTF-8"> | |
| <meta name="viewport" content="width=device-width, initial-scale=1.0"> | |
| <title>Team Timer</title> | |
| <style> | |
| :root { --bg: #121212; --card: #1e1e1e; --text: #eee; --accent: #3498db; --work: #e74c3c; --break: #2ecc71; } | |
| body { background: var(--bg); color: var(--text); font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif; margin: 0; display: flex; flex-direction: column; align-items: center; justify-content: center; height: 100vh; overflow: hidden; } | |
| /* Layout */ | |
| .app-container { width: 90%; max-width: 450px; text-align: center; } | |
| .card { background: var(--card); border-radius: 20px; padding: 30px; box-shadow: 0 10px 30px rgba(0,0,0,0.5); border: 1px solid #333; position: relative; } | |
| /* Login Overlay */ | |
| #login-overlay { position: absolute; top:0; left:0; width:100%; height:100%; background: var(--card); border-radius: 20px; display: flex; flex-direction: column; align-items: center; justify-content: center; z-index: 10; transition: opacity 0.3s; } | |
| input { background: #333; border: 1px solid #444; color: white; padding: 12px; border-radius: 8px; font-size: 1.1rem; width: 70%; text-align: center; margin-bottom: 15px; } | |
| .btn-primary { background: var(--accent); color: white; border: none; padding: 12px 25px; border-radius: 8px; font-weight: bold; cursor: pointer; font-size: 1rem; } | |
| /* Timer UI */ | |
| .room-tag { text-transform: uppercase; letter-spacing: 2px; font-size: 0.8rem; color: #666; margin-bottom: 10px; } | |
| #timer { font-size: 5.5rem; font-weight: 800; line-height: 1; margin: 10px 0; font-variant-numeric: tabular-nums; } | |
| .mode-label { font-size: 1.2rem; font-weight: bold; opacity: 0.8; } | |
| /* Dynamic Colors */ | |
| .color-work { color: var(--work); text-shadow: 0 0 30px rgba(231, 76, 60, 0.2); } | |
| .color-break { color: var(--break); text-shadow: 0 0 30px rgba(46, 204, 113, 0.2); } | |
| /* Progress Bar */ | |
| .progress-track { width: 100%; height: 6px; background: #333; border-radius: 3px; margin: 20px 0; overflow: hidden; } | |
| .progress-fill { height: 100%; background: #666; width: 100%; transition: width 1s linear; } | |
| /* Controls */ | |
| .controls { min-height: 60px; display: flex; justify-content: center; align-items: center; gap: 10px; } | |
| .btn-icon { background: #333; border: none; color: white; width: 50px; height: 50px; border-radius: 50%; font-size: 1.2rem; cursor: pointer; display: flex; align-items: center; justify-content: center; transition: 0.2s; } | |
| .btn-icon:hover { background: #444; transform: scale(1.1); } | |
| .btn-big { width: 60px; height: 60px; font-size: 1.5rem; background: var(--text); color: var(--bg); } | |
| /* Pick Next Grid */ | |
| #pick-next { display: none; flex-direction: column; gap: 15px; animation: fadeIn 0.5s; width: 100%; } | |
| /* Grid for presets */ | |
| .grid-presets { display: grid; grid-template-columns: 1fr 1fr 1fr; gap: 8px; width: 100%; } | |
| .pick-btn { background: #333; border: 1px solid #444; color: #ccc; padding: 15px 5px; border-radius: 10px; cursor: pointer; display: flex; flex-direction: column; align-items: center; gap: 5px; transition: 0.2s; } | |
| .pick-btn:hover { background: #444; border-color: #666; } | |
| .pick-btn span { font-size: 0.8rem; opacity: 0.7; } | |
| .pick-btn b { font-size: 1.1rem; } | |
| /* Custom Input Row */ | |
| .custom-row { display: flex; gap: 10px; justify-content: center; align-items: center; background: #252525; padding: 10px; border-radius: 12px; } | |
| .custom-input { width: 50px; padding: 8px; margin: 0; background: #121212; border: 1px solid #444; color: white; text-align: center; border-radius: 6px; font-weight: bold; } | |
| .btn-small { padding: 8px 12px; font-size: 0.8rem; border-radius: 6px; background: #333; border: 1px solid #444; color: #ddd; cursor: pointer; } | |
| .btn-small:hover { background: #444; } | |
| /* User List */ | |
| .user-list { margin-top: 30px; display: flex; justify-content: center; flex-wrap: wrap; gap: 8px; } | |
| .user-pill { background: #252525; padding: 5px 12px; border-radius: 15px; font-size: 0.85rem; border: 1px solid #333; display: flex; align-items: center; gap: 6px; } | |
| .dot { width: 8px; height: 8px; background: #444; border-radius: 50%; } | |
| .dot.active { background: #2ecc71; box-shadow: 0 0 5px #2ecc71; } | |
| .online-count { margin-top: 10px; font-size: 0.8rem; color: #555; } | |
| .hidden { display: none !important; } | |
| @keyframes fadeIn { from { opacity: 0; transform: translateY(10px); } to { opacity: 1; transform: translateY(0); } } | |
| </style> | |
| </head> | |
| <body> | |
| <div class="app-container"> | |
| <div class="card"> | |
| <!-- 1. LOGIN SCREEN --> | |
| <div id="login-overlay"> | |
| <h3>Who are you?</h3> | |
| <input type="text" id="username" placeholder="Enter your name" maxlength="12"> | |
| <button class="btn-primary" onclick="login()">Join Room</button> | |
| </div> | |
| <!-- 2. MAIN INTERFACE --> | |
| <div class="room-tag">ROOM: {{ROOM_NAME}}</div> | |
| <div id="mode-label" class="mode-label">WORK</div> | |
| <div id="timer" class="color-work">25:00</div> | |
| <div class="progress-track"> | |
| <div id="progress" class="progress-fill"></div> | |
| </div> | |
| <!-- Normal Controls --> | |
| <div id="active-controls" class="controls"> | |
| <button class="btn-icon" onclick="resetTimer()" title="Reset">↺</button> | |
| <button id="toggle-btn" class="btn-icon btn-big" onclick="toggleTimer()">▶</button> | |
| <button class="btn-icon" onclick="forcePick()" title="Change Mode">☰</button> | |
| </div> | |
| <!-- Pick Next Screen (Replaces controls when timer ends) --> | |
| <div id="pick-next"> | |
| <!-- Presets --> | |
| <div class="grid-presets"> | |
| <div class="pick-btn" onclick="setMode(25, 'WORK')"> | |
| <b>25</b> <span>Work</span> | |
| </div> | |
| <div class="pick-btn" onclick="setMode(5, 'BREAK')"> | |
| <b>5</b> <span>Break</span> | |
| </div> | |
| <div class="pick-btn" onclick="setMode(15, 'LONG BREAK')"> | |
| <b>15</b> <span>Long</span> | |
| </div> | |
| </div> | |
| <!-- Custom Input --> | |
| <div class="custom-row"> | |
| <input type="number" id="custom-min" class="custom-input" value="50" min="1" max="180"> | |
| <span style="font-size: 0.8rem; opacity: 0.5;">min</span> | |
| <button class="btn-small" onclick="startCustom('WORK')">Work</button> | |
| <button class="btn-small" onclick="startCustom('BREAK')">Break</button> | |
| </div> | |
| </div> | |
| </div> | |
| <!-- 3. USER LIST --> | |
| <div class="user-list" id="user-list"> | |
| <!-- Populated via JS --> | |
| </div> | |
| <div class="online-count" id="online-count">Waiting for team...</div> | |
| </div> | |
| <!-- I have removed the audio sound which did jumpscare me once, I will add a pleasant sound later hopefully --> | |
| <script> | |
| const ROOM = "{{ROOM_NAME}}"; | |
| const PROTO = window.location.protocol === 'https:' ? 'wss:' : 'ws:'; | |
| const WS_URL = PROTO + '//' + window.location.host + '/ws/' + ROOM; | |
| let ws; | |
| let myName = ""; | |
| let lastState = {}; | |
| let localShowPick = false; // Prevents the menu from closing when server says "stopped" | |
| const alarm = document.getElementById('alarm-sound'); | |
| // Handle Login Enter Key | |
| document.getElementById("username").addEventListener("keyup", function(event) { | |
| if (event.key === "Enter") login(); | |
| }); | |
| function login() { | |
| const input = document.getElementById('username'); | |
| if(!input.value.trim()) return; | |
| myName = input.value.trim(); | |
| // Hide login | |
| document.getElementById('login-overlay').style.opacity = '0'; | |
| setTimeout(() => document.getElementById('login-overlay').classList.add('hidden'), 300); | |
| connect(); | |
| } | |
| function connect() { | |
| ws = new WebSocket(WS_URL); | |
| ws.onopen = () => { | |
| // Send Login Packet | |
| ws.send(JSON.stringify({ type: "LOGIN", name: myName })); | |
| }; | |
| ws.onmessage = (event) => { | |
| const state = JSON.parse(event.data); | |
| render(state); | |
| lastState = state; | |
| }; | |
| ws.onclose = () => { | |
| document.getElementById('online-count').textContent = "Disconnected. Reconnecting..."; | |
| setTimeout(connect, 2000); | |
| }; | |
| } | |
| function render(state) { | |
| // 1. Timer Logic | |
| const m = Math.floor(state.timeLeft / 60).toString().padStart(2, '0'); | |
| const s = (state.timeLeft % 60).toString().padStart(2, '0'); | |
| const timerEl = document.getElementById('timer'); | |
| timerEl.textContent = m + ":" + s; | |
| // 2. Mode & Color | |
| document.getElementById('mode-label').textContent = state.mode; | |
| if(state.mode === 'WORK') timerEl.className = 'color-work'; | |
| else timerEl.className = 'color-break'; | |
| // 3. Progress Bar | |
| const pct = state.totalTime > 0 ? (state.timeLeft / state.totalTime) * 100 : 0; | |
| document.getElementById('progress').style.width = pct + "%"; | |
| // 4. Controls vs Pick Next Logic | |
| const controls = document.getElementById('active-controls'); | |
| const pickNext = document.getElementById('pick-next'); | |
| const toggleBtn = document.getElementById('toggle-btn'); | |
| // Play Sound if just finished | |
| if(state.timerEnded && !lastState.timerEnded) { | |
| alarm.play().catch(e => console.log("Audio blocked")); | |
| } | |
| // Auto-close menu if timer starts running | |
| if(state.isRunning) { | |
| localShowPick = false; | |
| } | |
| // Show menu if timer naturally ended OR user manually forced the menu open | |
| const showMenu = state.timerEnded || localShowPick; | |
| if(showMenu) { | |
| controls.classList.add('hidden'); | |
| pickNext.style.display = 'flex'; // Show the voting/picking container | |
| pickNext.classList.remove('hidden'); | |
| } else { | |
| pickNext.style.display = 'none'; | |
| controls.classList.remove('hidden'); | |
| toggleBtn.textContent = state.isRunning ? "❚❚" : "▶"; | |
| } | |
| // 5. User List | |
| const listEl = document.getElementById('user-list'); | |
| listEl.innerHTML = ""; | |
| if(state.users) { | |
| state.users.forEach(u => { | |
| const div = document.createElement('div'); | |
| div.className = 'user-pill'; | |
| // Highlight myself | |
| const isMe = u === myName ? " (You)" : ""; | |
| div.innerHTML = '<div class="dot active"></div>' + u + isMe; | |
| listEl.appendChild(div); | |
| }); | |
| document.getElementById('online-count').textContent = state.users.length + " people online"; | |
| } | |
| } | |
| // --- ACTIONS --- | |
| function send(payload) { | |
| if(ws && ws.readyState === WebSocket.OPEN) { | |
| ws.send(JSON.stringify(payload)); | |
| } | |
| } | |
| function toggleTimer() { | |
| if (lastState.isRunning) send({type: 'STOP'}); | |
| else send({type: 'START'}); | |
| } | |
| function resetTimer() { | |
| // Reset acts like a pause + refill | |
| send({type: 'STOP'}); | |
| send({type: 'SET', duration: lastState.totalTime/60, mode: lastState.mode}); | |
| } | |
| function forcePick() { | |
| // 1. Tell server to stop | |
| send({type: 'STOP'}); | |
| // 2. Force local menu to stay open even if server says "Not Ended" | |
| localShowPick = true; | |
| // 3. Immediately update UI (optional, but makes it snappy) | |
| document.getElementById('active-controls').classList.add('hidden'); | |
| document.getElementById('pick-next').style.display = 'flex'; | |
| document.getElementById('pick-next').classList.remove('hidden'); | |
| } | |
| function setMode(mins, modeName) { | |
| // Closing the menu is handled by the server update (Timer Not Ended + IsRunning=False) | |
| // But we must clear our local override | |
| localShowPick = false; | |
| send({type: 'SET', duration: mins, mode: modeName}); | |
| } | |
| function startCustom(mode) { | |
| const val = document.getElementById('custom-min').value; | |
| const mins = parseInt(val); | |
| if(mins > 0) { | |
| setMode(mins, mode); | |
| } | |
| } | |
| </script> | |
| </body> | |
| </html> | |
| ` |