| 1 | package web |
| 2 | |
| 3 | import ( |
| 4 | "context" |
| 5 | "encoding/json" |
| 6 | "errors" |
| 7 | "net/http" |
| 8 | "strconv" |
| 9 | "strings" |
| 10 | "sync" |
| 11 | "time" |
| 12 | |
| 13 | "github.com/go-chi/chi/v5" |
| 14 | |
| 15 | "amadan.net/oficina/base/internal/equipo" |
| 16 | "amadan.net/oficina/base/internal/store" |
| 17 | ) |
| 18 | |
| 19 | // asker is "Ask Base anything": the chat with Equipo's Assistant, relayed |
| 20 | // server to server with each member's own device bearer. Nil when |
| 21 | // BASE_EQUIPO_ORIGIN is unset. |
| 22 | type asker struct { |
| 23 | client *equipo.Client |
| 24 | seal equipo.Sealer |
| 25 | // label is the device name a member sees when approving Base in Equipo. |
| 26 | label string |
| 27 | // hosts holds a *memberConn per member id: their lock, held while |
| 28 | // their connection changes or their host is registered (lockMember), |
| 29 | // and their connection's generation (changeLink). |
| 30 | hosts sync.Map |
| 31 | // oficina holds a *sync.Mutex per member id, held while Ask is set up |
| 32 | // with Oficina ID for them (askOficinaLock). |
| 33 | oficina sync.Map |
| 34 | // zone is the team's IANA time zone (BASE_TIMEZONE), which Equipo |
| 35 | // writes the Assistant's times in unless the person has one of their |
| 36 | // own; zones holds, per member id, where telling Equipo has got to |
| 37 | // (zoneFor). |
| 38 | zone string |
| 39 | zoneMu sync.Mutex |
| 40 | zones map[string]*zoneTold |
| 41 | // uploads is the upload relay's slots (ask_files.go). |
| 42 | uploads *uploads |
| 43 | } |
| 44 | |
| 45 | // askRoutes mounts the chat, behind the member gate and Base's CSRF check. |
| 46 | func (a *app) askRoutes(r chi.Router) { |
| 47 | r.Get("/ask", a.askPageView) |
| 48 | r.Get("/ask/state", a.askStateJSON) |
| 49 | r.Get("/ask/events", a.askEvents) |
| 50 | r.Post("/ask/messages", a.askSend) |
| 51 | r.Post("/ask/attachments", a.askUpload) |
| 52 | r.Post("/ask/attachments/discard", a.askDiscard) |
| 53 | r.Delete("/ask/attachments/{id}", a.askDeleteAttachment) |
| 54 | r.Get("/ask/attachments/{id}", a.askAttachment(false)) |
| 55 | r.Head("/ask/attachments/{id}", a.askAttachment(false)) |
| 56 | r.Get("/ask/attachments/{id}/preview", a.askAttachment(true)) |
| 57 | r.Head("/ask/attachments/{id}/preview", a.askAttachment(true)) |
| 58 | r.Post("/ask/turns/{id}/cancel", a.askCancel) |
| 59 | r.Post("/ask/cards/{id}/answer", a.askAnswer) |
| 60 | r.Post("/ask/cards/{id}/carry_on", a.askCarryOn) |
| 61 | r.Post("/ask/connect", a.askConnectStart) |
| 62 | r.Get("/ask/connect", a.askConnectPage) |
| 63 | r.Post("/ask/connect/check", a.askConnectCheck) |
| 64 | r.Post("/ask/disconnect", a.askDisconnect) |
| 65 | r.Post("/ask/dock", a.askDock) |
| 66 | r.Get("/ask/oficina/connect", a.askOficinaConnect) |
| 67 | r.Get("/ask/oficina/done", a.askOficinaDone) |
| 68 | r.Post(askOficinaPath, a.askOficina) |
| 69 | } |
| 70 | |
| 71 | // askDock is POST /ask/dock: on a wide screen the X closes Ask Base, docked |
| 72 | // beside Home (open=0), and the Base button or the field opens it again |
| 73 | // (open=1), kept for the member on every device. Plain forms, so they work |
| 74 | // without scripts; the script posts them by fetch and gets a 204. |
| 75 | func (a *app) askDock(w http.ResponseWriter, r *http.Request) { |
| 76 | me, _ := CurrentMember(r) |
| 77 | var closed bool |
| 78 | switch r.PostFormValue("open") { |
| 79 | case "1": |
| 80 | case "0": |
| 81 | closed = true |
| 82 | default: |
| 83 | http.Error(w, "bad request", http.StatusBadRequest) |
| 84 | return |
| 85 | } |
| 86 | if err := store.SetAskClosed(r.Context(), a.db, me.ID, closed); err != nil { |
| 87 | a.logger.Error("ask: dock", "err", err) |
| 88 | http.Error(w, "unavailable", http.StatusServiceUnavailable) |
| 89 | return |
| 90 | } |
| 91 | if wantsJSON(r) { |
| 92 | w.WriteHeader(http.StatusNoContent) |
| 93 | return |
| 94 | } |
| 95 | http.Redirect(w, r, "/", http.StatusSeeOther) |
| 96 | } |
| 97 | |
| 98 | // newAsker is the chat with the Equipo at origin, for the team at zone |
| 99 | // (BASE_TIMEZONE), which Base tells Equipo for each member (zoneFor). |
| 100 | func newAsker(origin, instanceKey, name string, zone *time.Location) *asker { |
| 101 | a := &asker{client: equipo.New(origin), seal: equipo.NewSealer(instanceKey), label: "Base (" + name + ")", |
| 102 | zones: map[string]*zoneTold{}, uploads: newUploads(uploadBounds)} |
| 103 | a.client.FileTimeout = uploadBounds.Upstream |
| 104 | if zone != nil { |
| 105 | a.zone = zone.String() |
| 106 | } |
| 107 | return a |
| 108 | } |
| 109 | |
| 110 | // The states of a member's chat. Connect: nothing connected; pending: a |
| 111 | // sign-in code waits for approval in Equipo; expired and refused: that code |
| 112 | // can no longer be approved; failed: Base could not keep the bearer it got; ready: a live bearer; reconnect: Equipo |
| 113 | // refused the bearer or it expired; unavailable: Equipo did not answer. |
| 114 | // Norunner and oldrunner are ready, but the person has no runner that can |
| 115 | // answer the Assistant (none, or one too old): the conversation shows, |
| 116 | // with a note saying so. |
| 117 | const ( |
| 118 | askConnect = "connect" |
| 119 | askPending = "pending" |
| 120 | askExpired = "expired" |
| 121 | askRefused = "refused" |
| 122 | askFailed = "failed" |
| 123 | askReady = "ready" |
| 124 | askReconnect = "reconnect" |
| 125 | askUnavailable = "unavailable" |
| 126 | askNoRunner = "norunner" |
| 127 | askRunnerTooOld = "oldrunner" |
| 128 | ) |
| 129 | |
| 130 | // chatting reports whether state shows the conversation. |
| 131 | func chatting(state string) bool { |
| 132 | return state == askReady || state == askNoRunner || state == askRunnerTooOld |
| 133 | } |
| 134 | |
| 135 | // deviceSecrets is what Base keeps sealed for a member's Equipo device: |
| 136 | // the Ed25519 seed, the device secret, the challenge and the nonce it |
| 137 | // proves with (kept, so a lost exchange answer can be asked for again), |
| 138 | // and the bearer once it has one. A key set up with Oficina ID (Via |
| 139 | // "oficina") has no secret, challenge or nonce; it keeps instead the |
| 140 | // cookie of the Equipo session it ends with, which Base never sends |
| 141 | // anywhere again and never signs out (signing out would end the key). |
| 142 | type deviceSecrets struct { |
| 143 | Seed []byte `json:"seed"` |
| 144 | Secret string `json:"secret"` |
| 145 | Challenge string `json:"challenge"` |
| 146 | Nonce string `json:"nonce"` |
| 147 | Token string `json:"token,omitempty"` |
| 148 | Via string `json:"via,omitempty"` |
| 149 | SessionName string `json:"session_name,omitempty"` |
| 150 | SessionValue string `json:"session_value,omitempty"` |
| 151 | } |
| 152 | |
| 153 | func (a *app) sealSecrets(memberID string, s deviceSecrets) ([]byte, error) { |
| 154 | raw, err := json.Marshal(s) |
| 155 | if err != nil { |
| 156 | return nil, err |
| 157 | } |
| 158 | return a.ask.seal.Seal(memberID, raw) |
| 159 | } |
| 160 | |
| 161 | // askLink reads the member's link and its secrets, and the state they put |
| 162 | // the chat in, without calling Equipo. A link to another Equipo, or sealed |
| 163 | // under another instance key, counts as none. |
| 164 | func (a *app) askLink(ctx context.Context, me store.Member) (store.EquipoLink, deviceSecrets, string, error) { |
| 165 | var sec deviceSecrets |
| 166 | l, ok, err := store.EquipoLinkFor(ctx, a.db, me.ID) |
| 167 | if err != nil { |
| 168 | return l, sec, "", err |
| 169 | } |
| 170 | if !ok || l.Origin != a.ask.client.Origin() { |
| 171 | return store.EquipoLink{}, sec, askConnect, nil |
| 172 | } |
| 173 | raw, err := a.ask.seal.Open(me.ID, l.Sealed) |
| 174 | if err != nil || json.Unmarshal(raw, &sec) != nil { |
| 175 | return store.EquipoLink{}, deviceSecrets{}, askConnect, nil |
| 176 | } |
| 177 | live := time.Now().Before(l.ExpiresAt) |
| 178 | switch { |
| 179 | case l.State == store.EquipoPending && live: |
| 180 | return l, sec, askPending, nil |
| 181 | case l.State == store.EquipoPending: |
| 182 | return l, sec, askExpired, nil |
| 183 | case l.State == store.EquipoConnected && live && sec.Token != "": |
| 184 | return l, sec, askReady, nil |
| 185 | } |
| 186 | return l, sec, askReconnect, nil |
| 187 | } |
| 188 | |
| 189 | // askLost records that Equipo refused the bearer of the member's device |
| 190 | // dev, and forgets the member's host token (Equipo no longer speaks for |
| 191 | // them), unless the link has moved on to another device since. |
| 192 | func (a *app) askLost(ctx context.Context, me store.Member, dev string) { |
| 193 | defer a.lockMember(me.ID)() |
| 194 | if err := store.LoseEquipoLink(context.WithoutCancel(ctx), a.db, me.ID, dev); err != nil { |
| 195 | a.logger.Error("ask: mark lost", "err", err) |
| 196 | } |
| 197 | } |
| 198 | |
| 199 | // askView is the chat as a page or the panel draws it. |
| 200 | type askView struct { |
| 201 | State string |
| 202 | // Next is where connecting comes back to: home, settings or ask. |
| 203 | Next string |
| 204 | // Equipo is the "Open Equipo" link. |
| 205 | Equipo string |
| 206 | // Zone is Base's time zone, the IANA name, for the day a job started |
| 207 | // on (startedText) when the script draws it. |
| 208 | Zone string |
| 209 | Messages []equipo.Message |
| 210 | // Jobs are the job cards, each with the cards that belong to it; |
| 211 | // Cards every other card shown. |
| 212 | Jobs []jobView |
| 213 | Cards []equipo.Card |
| 214 | Turn *equipo.Turn |
| 215 | Status string |
| 216 | Key string |
| 217 | Problem string |
| 218 | // Text is what the person wrote and Equipo did not take, kept in the |
| 219 | // field. |
| 220 | Text string |
| 221 | // Unread is a conversation Home did not read (its chat was closed, or |
| 222 | // Equipo was slow to answer): drawn without saying it is empty, for |
| 223 | // the panel's script to read. |
| 224 | Unread bool |
| 225 | // Notice is a line the chat says once (how connecting Oficina ended), |
| 226 | // in the conversation after its newest line (NoticeAfter). |
| 227 | Notice string |
| 228 | // CanAttach says the person's runner can take files: the paperclip |
| 229 | // shows (with scripts) only then. |
| 230 | CanAttach bool |
| 231 | // base is Base's own origin: the only place a connect-Oficina link may |
| 232 | // go and keep its rel. |
| 233 | base string |
| 234 | // offerAt is the newest reply of the Assistant's, which ends with the |
| 235 | // open connect cards' buttons (OffersAt); "" when there is none. |
| 236 | offerAt string |
| 237 | } |
| 238 | |
| 239 | // NoticeAfter is the id of the line the notice follows: the newest |
| 240 | // message, "" when there is none. |
| 241 | func (v askView) NoticeAfter() string { |
| 242 | if len(v.Messages) == 0 { |
| 243 | return "" |
| 244 | } |
| 245 | return v.Messages[len(v.Messages)-1].ID |
| 246 | } |
| 247 | |
| 248 | // connectOffer is an open connect card as the chat draws it: a button, |
| 249 | // going to Base's own connect page, at the end of the Assistant's newest |
| 250 | // reply. The snapshot does not say which turn raised a card, so a fresh |
| 251 | // read puts it after the newest reply; the panel's script does the same, |
| 252 | // and holds one that comes while its turn's reply streams until it lands |
| 253 | // (ask.js, offer). |
| 254 | type connectOffer struct { |
| 255 | ID string |
| 256 | Revision int64 |
| 257 | URL string |
| 258 | } |
| 259 | |
| 260 | // offerOf is card c as a button: an open connect card with a link to |
| 261 | // Base's own connect page (the rel CleanAt keeps for that alone). |
| 262 | func offerOf(c equipo.Card) (connectOffer, bool) { |
| 263 | if c.Kind != equipo.CardConnect || !c.Open() { |
| 264 | return connectOffer{}, false |
| 265 | } |
| 266 | for _, l := range c.Links { |
| 267 | if l.Rel == equipo.LinkOficinaConnect { |
| 268 | return connectOffer{ID: c.ID, Revision: c.Revision, URL: l.URL}, true |
| 269 | } |
| 270 | } |
| 271 | return connectOffer{}, false |
| 272 | } |
| 273 | |
| 274 | func (v askView) offers() []connectOffer { |
| 275 | var out []connectOffer |
| 276 | for _, c := range v.Cards { |
| 277 | if o, ok := offerOf(c); ok { |
| 278 | out = append(out, o) |
| 279 | } |
| 280 | } |
| 281 | return out |
| 282 | } |
| 283 | |
| 284 | // OffersAt are the buttons that end message id: the open connect cards', |
| 285 | // when id is the Assistant's newest reply. |
| 286 | func (v askView) OffersAt(id string) []connectOffer { |
| 287 | if id == "" || id != v.offerAt { |
| 288 | return nil |
| 289 | } |
| 290 | return v.offers() |
| 291 | } |
| 292 | |
| 293 | // LooseOffers are the buttons drawn on their own, at the end of the |
| 294 | // conversation: with no reply of the Assistant's to end, all of them. |
| 295 | func (v askView) LooseOffers() []connectOffer { |
| 296 | if v.offerAt != "" { |
| 297 | return nil |
| 298 | } |
| 299 | return v.offers() |
| 300 | } |
| 301 | |
| 302 | // LooseCards are the cards drawn as cards of their own: every card but |
| 303 | // the connect cards drawn as buttons. |
| 304 | func (v askView) LooseCards() []equipo.Card { |
| 305 | var out []equipo.Card |
| 306 | for _, c := range v.Cards { |
| 307 | if _, ok := offerOf(c); !ok { |
| 308 | out = append(out, c) |
| 309 | } |
| 310 | } |
| 311 | return out |
| 312 | } |
| 313 | |
| 314 | // jobView is a job card as the chat draws it, a pill, with the cards that |
| 315 | // belong to it (Card.Job): under the pill while they wait on the person, |
| 316 | // in its view once they have ended. Cards carries them all, for the |
| 317 | // panel's script to place. |
| 318 | type jobView struct { |
| 319 | equipo.Card |
| 320 | Cards []equipo.Card `json:"cards"` |
| 321 | } |
| 322 | |
| 323 | // OpenCards are the job's cards that wait on the person, drawn under its |
| 324 | // pill. |
| 325 | func (j jobView) OpenCards() []equipo.Card { |
| 326 | var out []equipo.Card |
| 327 | for _, c := range j.Cards { |
| 328 | if c.Open() { |
| 329 | out = append(out, c) |
| 330 | } |
| 331 | } |
| 332 | return out |
| 333 | } |
| 334 | |
| 335 | // EndedCards are the job's cards that have ended (answered, resolved), |
| 336 | // listed in its view: each its question and how it ended. |
| 337 | func (j jobView) EndedCards() []equipo.Card { |
| 338 | var out []equipo.Card |
| 339 | for _, c := range j.Cards { |
| 340 | if !c.Open() { |
| 341 | out = append(out, c) |
| 342 | } |
| 343 | } |
| 344 | return out |
| 345 | } |
| 346 | |
| 347 | // Go is where to see the job's work, for templates: its link beside the |
| 348 | // pill, or nil. |
| 349 | func (j jobView) Go() *equipo.Link { |
| 350 | if l, ok := j.Card.Go(); ok { |
| 351 | return &l |
| 352 | } |
| 353 | return nil |
| 354 | } |
| 355 | |
| 356 | // Equipo is the job's own page in Equipo, for templates: the job view's |
| 357 | // title links there (plan decision D3), or nil. |
| 358 | func (j jobView) Equipo() *equipo.Link { |
| 359 | if l, ok := j.Card.Equipo(); ok { |
| 360 | return &l |
| 361 | } |
| 362 | return nil |
| 363 | } |
| 364 | |
| 365 | // startedText says when a job started (plan decision D19): how long ago |
| 366 | // in minutes or hours, then from a day on, the day in Base's time zone |
| 367 | // loc (nil: at as given). A start a little in the future, a clock behind |
| 368 | // Equipo's, is just now. ask.js has the twin (startedText), and moves it |
| 369 | // on every minute. |
| 370 | func startedText(at, now time.Time, loc *time.Location) string { |
| 371 | switch d := now.Sub(at); { |
| 372 | case d < time.Minute: |
| 373 | return "Started just now" |
| 374 | case d < 2*time.Minute: |
| 375 | return "Started 1 minute ago" |
| 376 | case d < time.Hour: |
| 377 | return "Started " + strconv.Itoa(int(d/time.Minute)) + " minutes ago" |
| 378 | case d < 2*time.Hour: |
| 379 | return "Started 1 hour ago" |
| 380 | case d < 24*time.Hour: |
| 381 | return "Started " + strconv.Itoa(int(d/time.Hour)) + " hours ago" |
| 382 | } |
| 383 | if loc != nil { |
| 384 | at = at.In(loc) |
| 385 | } |
| 386 | return "Started on " + at.Format("2 January") |
| 387 | } |
| 388 | |
| 389 | // Shows reports whether the block for states (space-separated) shows now. |
| 390 | func (v askView) Shows(states string) bool { |
| 391 | for _, s := range strings.Fields(states) { |
| 392 | if s == v.State { |
| 393 | return true |
| 394 | } |
| 395 | } |
| 396 | return false |
| 397 | } |
| 398 | |
| 399 | // homeState is the state Home and Settings show, read without calling |
| 400 | // Equipo: a code that can no longer be approved is as good as none. |
| 401 | func homeState(state string) string { |
| 402 | if state == askExpired || state == askRefused || state == askFailed { |
| 403 | return askConnect |
| 404 | } |
| 405 | return state |
| 406 | } |
| 407 | |
| 408 | func (a *app) newAskView(state, next string) askView { |
| 409 | v := askView{base: a.cfg.Origin, State: state, Next: next, Equipo: a.ask.client.Origin() + "/", Key: equipo.NewKey()} |
| 410 | if a.cfg.Timezone != nil { |
| 411 | v.Zone = a.cfg.Timezone.String() |
| 412 | } |
| 413 | return v |
| 414 | } |
| 415 | |
| 416 | // turnStatus is the line under the conversation while a turn runs. A |
| 417 | // team_update turn is quiet (plan decision D9): it has none. |
| 418 | func turnStatus(t *equipo.Turn) string { |
| 419 | switch { |
| 420 | case t == nil || t.Kind == equipo.TurnTeamUpdate: |
| 421 | return "" |
| 422 | case t.State == equipo.TurnWaiting: |
| 423 | return "Ask Base can't answer right now. It will as soon as it can." |
| 424 | } |
| 425 | return "Thinking…" |
| 426 | } |
| 427 | |
| 428 | // failedFiles are the words for a turn that failed for its files, by |
| 429 | // Equipo's reason (copy review 13, pending); ask.js has the same |
| 430 | // (failedFiles). Any other failure keeps "That didn't get an answer. Try |
| 431 | // again.", which only the panel's script says, as it happens. |
| 432 | var failedFiles = map[string]string{ |
| 433 | "attachment_unavailable": "A file didn’t arrive whole. Attach it again.", |
| 434 | "runner_storage_full": "There’s no room left for these files. Try fewer or smaller ones.", |
| 435 | "runner_too_old": "Files can’t be read right now. Send it again without them.", |
| 436 | } |
| 437 | |
| 438 | // fill puts a snapshot in the view: the messages, the jobs in the |
| 439 | // snapshot's order with the cards that belong to each under it, every |
| 440 | // other card to show, and the newest turn that has not ended, of those the |
| 441 | // person sees running (never a quiet team_update turn, plan decision D9). |
| 442 | func (v *askView) fill(s equipo.Snapshot) { |
| 443 | v.Messages = make([]equipo.Message, len(s.Messages)) |
| 444 | for i, m := range s.Messages { |
| 445 | v.Messages[i] = m.Clean() |
| 446 | } |
| 447 | v.CanAttach = s.CanAttach |
| 448 | var shown []equipo.Card |
| 449 | jobs := map[string]int{} |
| 450 | for _, c := range s.Cards { |
| 451 | p, ok := c.CleanAt(v.base) |
| 452 | switch { |
| 453 | case !ok || !p.Shown(): |
| 454 | case p.Kind == equipo.CardConnect && !p.Open(): |
| 455 | // Connected: a fresh read no longer offers it (the chat says |
| 456 | // so once, oficinaNotes). |
| 457 | case p.Kind == equipo.CardJob: |
| 458 | if _, dup := jobs[p.ID]; !dup { |
| 459 | jobs[p.ID] = len(v.Jobs) |
| 460 | v.Jobs = append(v.Jobs, jobView{Card: p, Cards: []equipo.Card{}}) |
| 461 | } |
| 462 | default: |
| 463 | shown = append(shown, p) |
| 464 | } |
| 465 | } |
| 466 | for _, c := range shown { |
| 467 | if i, ok := jobs[c.Job]; ok && c.Job != "" { |
| 468 | v.Jobs[i].Cards = append(v.Jobs[i].Cards, c) |
| 469 | } else { |
| 470 | v.Cards = append(v.Cards, c) |
| 471 | } |
| 472 | } |
| 473 | for i := len(s.Messages) - 1; i >= 0; i-- { |
| 474 | if s.Messages[i].Role != "person" { |
| 475 | v.offerAt = s.Messages[i].ID |
| 476 | break |
| 477 | } |
| 478 | } |
| 479 | for i := len(s.Turns) - 1; i >= 0; i-- { |
| 480 | if equipo.InFlight(s.Turns[i].State) && s.Turns[i].Kind != equipo.TurnTeamUpdate { |
| 481 | t := s.Turns[i] |
| 482 | v.Turn = &t |
| 483 | break |
| 484 | } |
| 485 | } |
| 486 | v.Status = turnStatus(v.Turn) |
| 487 | // With nothing running, the turn of the person's newest message, if it |
| 488 | // failed for its files, unanswered, says so (the page without scripts, and the panel |
| 489 | // as it reads the conversation afresh). |
| 490 | if v.Turn == nil && len(s.Messages) > 0 && s.Messages[len(s.Messages)-1].Role == "person" { |
| 491 | for _, t := range s.Turns { |
| 492 | if t.ID == s.Messages[len(s.Messages)-1].TurnID && t.State == equipo.TurnFailed { |
| 493 | v.Status = failedFiles[t.Reason] |
| 494 | } |
| 495 | } |
| 496 | } |
| 497 | } |
| 498 | |
| 499 | // askSnapshot reads the member's conversation into v, moving v.State to |
| 500 | // reconnect or unavailable when Equipo refuses or does not answer, and to |
| 501 | // norunner when the person has no runner that can answer. Once Equipo |
| 502 | // has answered, it records who the bearer speaks for, and registers the |
| 503 | // member's host if Equipo does not hold it yet. |
| 504 | func (a *app) askSnapshot(r *http.Request, me store.Member, l store.EquipoLink, token string, v *askView) int64 { |
| 505 | return a.askSnapshotWithin(r, me, l, token, v, 0) |
| 506 | } |
| 507 | |
| 508 | // askSnapshotWithin is askSnapshot giving Equipo at most wait to answer |
| 509 | // (0: the client's own limit). Past it, v stays as it was, marked Unread. |
| 510 | func (a *app) askSnapshotWithin(r *http.Request, me store.Member, l store.EquipoLink, token string, v *askView, wait time.Duration) int64 { |
| 511 | ctx := r.Context() |
| 512 | if wait > 0 { |
| 513 | var cancel context.CancelFunc |
| 514 | ctx, cancel = context.WithTimeout(ctx, wait) |
| 515 | defer cancel() |
| 516 | } |
| 517 | s, err := a.ask.client.Snapshot(ctx, token) |
| 518 | switch { |
| 519 | case err != nil && wait > 0 && errors.Is(ctx.Err(), context.DeadlineExceeded) && r.Context().Err() == nil: |
| 520 | a.logger.Warn("ask: snapshot slow", "wait", wait) |
| 521 | v.Unread = true |
| 522 | return 0 |
| 523 | case errors.Is(err, equipo.ErrUnauthenticated): |
| 524 | a.askLost(r.Context(), me, l.DeviceID) |
| 525 | v.State = askReconnect |
| 526 | return 0 |
| 527 | case err != nil: |
| 528 | a.logger.Warn("ask: snapshot", "err", err) |
| 529 | v.State = askUnavailable |
| 530 | return 0 |
| 531 | } |
| 532 | v.fill(s) |
| 533 | if !s.Available { |
| 534 | v.State = askNoRunner |
| 535 | } |
| 536 | if s.Me.Address != "" && s.Me.Address != l.Person { |
| 537 | if err := store.SetEquipoPerson(r.Context(), a.db, me.ID, l.DeviceID, s.Me.Address); err != nil { |
| 538 | a.logger.Error("ask: equipo person", "err", err) |
| 539 | } |
| 540 | } |
| 541 | a.hostFor(r.Context(), me, l.DeviceID, token, false) |
| 542 | return s.Cursor |
| 543 | } |
| 544 | |
| 545 | type askPage struct { |
| 546 | Name string |
| 547 | Ask askView |
| 548 | } |
| 549 | |
| 550 | // askPageView is GET /ask: the whole conversation as a page, which works |
| 551 | // with scripts off. |
| 552 | func (a *app) askPageView(w http.ResponseWriter, r *http.Request) { |
| 553 | me, _ := CurrentMember(r) |
| 554 | l, sec, state, err := a.askLink(r.Context(), me) |
| 555 | if err != nil { |
| 556 | a.logger.Error("ask: link", "err", err) |
| 557 | http.Error(w, "unavailable", http.StatusServiceUnavailable) |
| 558 | return |
| 559 | } |
| 560 | v := a.newAskView(homeState(state), "ask") |
| 561 | if state == askReady { |
| 562 | a.askSnapshot(r, me, l, sec.Token, &v) |
| 563 | } |
| 564 | if r.URL.Query().Get("problem") != "" && v.State == askReady { |
| 565 | v.Problem = "That didn't send. Try again." |
| 566 | } |
| 567 | w.Header().Set("Cache-Control", "no-store") |
| 568 | a.render(w, r, "ask", askPage{Name: a.cfg.Name, Ask: v}) |
| 569 | } |
| 570 | |
| 571 | // askRunnerPage answers a form Equipo refused for want of a runner (state |
| 572 | // norunner or oldrunner): /ask as it is now, with that note, and the |
| 573 | // person's text and its key kept in the field, so sending it again is |
| 574 | // the same message. |
| 575 | func (a *app) askRunnerPage(w http.ResponseWriter, r *http.Request, c askConn, state string) { |
| 576 | l, _, _, err := a.askLink(r.Context(), c.me) |
| 577 | if err != nil { |
| 578 | a.logger.Error("ask: link", "err", err) |
| 579 | http.Error(w, "unavailable", http.StatusServiceUnavailable) |
| 580 | return |
| 581 | } |
| 582 | v := a.newAskView(askReady, "ask") |
| 583 | a.askSnapshot(r, c.me, l, c.token, &v) |
| 584 | if chatting(v.State) { |
| 585 | v.State = state |
| 586 | } |
| 587 | v.Text, v.Key = r.PostFormValue("text"), askKey(r.PostFormValue("key")) |
| 588 | w.Header().Set("Cache-Control", "no-store") |
| 589 | if err := a.pages.PageTheme(w, http.StatusConflict, "ask", askPage{Name: a.cfg.Name, Ask: v}, themeOf(r)); err != nil { |
| 590 | a.logger.Error("render", "page", "ask", "err", err) |
| 591 | } |
| 592 | } |
| 593 | |
| 594 | // askStateJSON is GET /ask/state: what the panel draws, and the cursor its |
| 595 | // event stream starts after. |
| 596 | func (a *app) askStateJSON(w http.ResponseWriter, r *http.Request) { |
| 597 | me, _ := CurrentMember(r) |
| 598 | l, sec, state, err := a.askLink(r.Context(), me) |
| 599 | if err != nil { |
| 600 | a.logger.Error("ask: link", "err", err) |
| 601 | http.Error(w, "unavailable", http.StatusServiceUnavailable) |
| 602 | return |
| 603 | } |
| 604 | v := a.newAskView(homeState(state), "home") |
| 605 | var cursor int64 |
| 606 | if state == askReady { |
| 607 | cursor = a.askSnapshot(r, me, l, sec.Token, &v) |
| 608 | } |
| 609 | // RenewAfter is when the native app should set Ask up again with a |
| 610 | // fresh Oficina ID assertion: "" for a key from the code flow. |
| 611 | for i, m := range v.Messages { |
| 612 | v.Messages[i] = asDrawn(r, m) |
| 613 | } |
| 614 | renew := "" |
| 615 | if at := renewAfter(l, sec); !at.IsZero() && state != askConnect { |
| 616 | renew = at.Format(time.RFC3339) |
| 617 | } |
| 618 | out := struct { |
| 619 | State string `json:"state"` |
| 620 | Messages []equipo.Message `json:"messages"` |
| 621 | Jobs []jobView `json:"jobs"` |
| 622 | Cards []equipo.Card `json:"cards"` |
| 623 | Turn *equipo.Turn `json:"turn"` |
| 624 | Status string `json:"status"` |
| 625 | Cursor int64 `json:"cursor"` |
| 626 | RenewAfter string `json:"renew_after"` |
| 627 | EquipoOrigin string `json:"equipo_origin"` |
| 628 | // Disconnected: the member disconnected Ask, so no app sets it up |
| 629 | // again by itself. |
| 630 | Disconnected bool `json:"disconnected"` |
| 631 | // CanAttach: the person's runner can take files, so the paperclip |
| 632 | // may show. |
| 633 | CanAttach bool `json:"can_attach"` |
| 634 | }{v.State, append([]equipo.Message{}, v.Messages...), append([]jobView{}, v.Jobs...), append([]equipo.Card{}, v.Cards...), v.Turn, v.Status, cursor, |
| 635 | renew, a.ask.client.Origin(), me.AskDisconnected, v.CanAttach && v.State == askReady} |
| 636 | writeJSON(w, http.StatusOK, out) |
| 637 | } |
| 638 | |
| 639 | func writeJSON(w http.ResponseWriter, status int, v any) { |
| 640 | w.Header().Set("Content-Type", "application/json") |
| 641 | w.Header().Set("Cache-Control", "no-store") |
| 642 | w.WriteHeader(status) |
| 643 | _ = json.NewEncoder(w).Encode(v) |
| 644 | } |
| 645 | |