oficina / home Public

Clone
git clone https://amadan.net/oficina/home

Plain git — no account needed to clone.

Download

Download this file

1package home
2
3import (
4 "context"
5 "io"
6 "net/http"
7 "net/url"
8 "sort"
9 "strings"
10 "time"
11
12 "amadan.net/oficina/home/dashboard"
13 "github.com/go-json-experiment/json"
14)
15
16type dashboardRow struct {
17 dashboard.Item
18 App, AppID, Icon, When, DateTime string
19}
20type dashboardPage struct {
21 Apps []catalogApp
22 Teams []dashboardTeam
23 Team dashboardTeam
24 Documents, Events []dashboardRow
25 Sources []dashboardResult
26 DocumentsComplete, EventsComplete bool
27}
28
29func (a *App) handleDashboard(w http.ResponseWriter, r *http.Request) {
30 if len(a.runtime.dashboard) == 0 {
31 a.render(w, r, 200, "directory.html", map[string]any{"Apps": directoryCatalog(*a.runtime)})
32 return
33 }
34 subject, session, ok := a.dashboardSession(r)
35 if !ok {
36 http.Error(w, "Unable to load your dashboard", 400)
37 return
38 }
39 q, e := url.ParseQuery(r.URL.RawQuery)
40 if e != nil || len(q) > 2 || len(q["team"]) > 1 || len(q["dashboard"]) > 1 || len(q["refresh"]) > 1 || (q.Has("refresh") && (q.Get("refresh") != "1" || q.Has("dashboard"))) {
41 http.NotFound(w, r)
42 return
43 }
44 for k := range q {
45 if k != "team" && k != "dashboard" && k != "refresh" {
46 http.NotFound(w, r)
47 return
48 }
49 }
50 selected := q.Get("team")
51 if selected == "" {
52 var valid bool
53 selected, valid = a.selectedDashboardTeam(r, session)
54 if !valid {
55 http.NotFound(w, r)
56 return
57 }
58 if selected == "" {
59 selected = a.runtime.dashboard[0].ID
60 }
61 }
62 team, ok := a.dashboardTeam(selected)
63 if !ok {
64 http.NotFound(w, r)
65 return
66 }
67 a.rememberDashboardTeam(w, session, team.ID)
68 key := dashboardCacheKey(subject, session, team.ID)
69 now := time.Now()
70 a.dash.mu.Lock()
71 a.dash.sweep(now)
72 // The callback returns to the ordinary URL. A ready, browser-bound
73 // pending request takes precedence over a still-fresh cached page.
74 nonce := q.Get("dashboard")
75 if nonce == "" && !q.Has("refresh") {
76 if candidate := dashboardNonce(r); candidate != "" {
77 if pending, ok := a.dash.pending[candidate]; ok && pending.Tokens != nil {
78 nonce = candidate
79 }
80 }
81 }
82 cached, found := a.dash.cache[key]
83 if nonce == "" && !q.Has("refresh") && found && now.Sub(cached.At) < 30*time.Second {
84 a.dash.mu.Unlock()
85 a.renderDashboard(w, r, team, cached.Results)
86 return
87 }
88 if nonce != "" {
89 pending, present := a.dash.pending[nonce]
90 if !present || nonce != dashboardNonce(r) || pending.Tokens == nil || pending.Subject != subject || pending.Session != session || pending.Team != team.ID {
91 a.dash.mu.Unlock()
92 http.Error(w, "Dashboard refresh expired. Return to Oficina and try again.", 400)
93 return
94 }
95 delete(a.dash.pending, nonce)
96 a.dash.mu.Unlock()
97 http.SetCookie(w, &http.Cookie{Name: dashboardCookie, Path: "/", Value: "", MaxAge: -1, Secure: true, HttpOnly: true, SameSite: http.SameSiteNoneMode})
98 results := a.pullDashboard(r.Context(), team, pending.Tokens)
99 a.dash.mu.Lock()
100 a.dash.sweep(time.Now())
101 if len(a.dash.cache) >= 256 {
102 for k := range a.dash.cache {
103 delete(a.dash.cache, k)
104 break
105 }
106 }
107 cachedAt := time.Now()
108 a.dash.cache[key] = dashboardCache{Results: results, At: cachedAt}
109 // Drop content even when nobody visits Home again.
110 time.AfterFunc(120*time.Second, func() {
111 a.dash.mu.Lock()
112 defer a.dash.mu.Unlock()
113 if current, ok := a.dash.cache[key]; ok && current.At.Equal(cachedAt) {
114 delete(a.dash.cache, key)
115 }
116 })
117 a.dash.mu.Unlock()
118 // Old callbacks may still carry the nonce in the URL during a rollout.
119 // New callbacks finish here, at the canonical URL, without another hop.
120 if q.Has("dashboard") {
121 http.Redirect(w, r, "/?team="+url.QueryEscape(team.ID), http.StatusSeeOther)
122 } else {
123 a.renderDashboard(w, r, team, results)
124 }
125 return
126 }
127 if len(a.dash.pending) >= 256 {
128 a.dash.mu.Unlock()
129 http.Error(w, "Dashboard busy. Please try again.", 503)
130 return
131 }
132 nonce, e = dashboard.ID()
133 if e != nil {
134 a.dash.mu.Unlock()
135 http.Error(w, "Dashboard unavailable", 503)
136 return
137 }
138 // A new tab replaces only this browser's pending flow, never another viewer's.
139 if previous := dashboardNonce(r); previous != "" {
140 delete(a.dash.pending, previous)
141 }
142 a.dash.pending[nonce] = dashboardPending{Subject: subject, Session: session, Team: team.ID, Expires: now.Add(5 * time.Minute)}
143 a.dash.mu.Unlock()
144 http.SetCookie(w, &http.Cookie{Name: dashboardCookie, Path: "/", Value: nonce, MaxAge: 300, Secure: true, HttpOnly: true, SameSite: http.SameSiteNoneMode})
145 http.Redirect(w, r, a.origins.Credential+"/dashboard/authorize?"+url.Values{"team": {team.ID}, "nonce": {nonce}}.Encode(), http.StatusSeeOther)
146}
147func (a *App) pullDashboard(parent context.Context, team dashboardTeam, tokens map[string]string) []dashboardResult {
148 ctx, cancel := context.WithTimeout(parent, 3*time.Second)
149 defer cancel()
150 results := make(chan dashboardResult, len(team.Sources))
151 for _, source := range team.Sources {
152 go func(s dashboardSource) {
153 result := dashboardResult{Source: s, Status: "Could not load. Refresh or open the app."}
154 defer func() { results <- result }()
155 select {
156 case a.dash.slots <- struct{}{}:
157 defer func() { <-a.dash.slots }()
158 case <-ctx.Done():
159 result.Status = "Not loaded yet. Refresh to try again."
160 return
161 }
162 req, e := http.NewRequestWithContext(ctx, http.MethodGet, s.Origin+dashboard.Path, nil)
163 if e != nil {
164 return
165 }
166 req.Header.Set("Authorization", "Bearer "+tokens[s.Origin])
167 req.Header.Set("Accept", "application/json")
168 req.Header.Set("Cache-Control", "no-store")
169 response, e := a.dash.client.Do(req)
170 if e != nil {
171 return
172 }
173 defer response.Body.Close()
174 if response.StatusCode == 403 {
175 result.Status = "Connect your Oficina account in this app to see your work."
176 return
177 }
178 if response.StatusCode != 200 || !dashboardNoStore(response.Header.Values("Cache-Control")) {
179 return
180 }
181 b, e := io.ReadAll(io.LimitReader(response.Body, dashboard.MaxBody+1))
182 if e != nil || len(b) > dashboard.MaxBody {
183 return
184 }
185 var data dashboard.Response
186 if json.Unmarshal(b, &data, json.RejectUnknownMembers(true)) != nil || !data.Valid(s.Origin, team.ID, s.kind()) {
187 return
188 }
189 result.Response = data
190 result.Status = ""
191 }(source)
192 }
193 out := make([]dashboardResult, 0, len(team.Sources))
194 for range team.Sources {
195 out = append(out, <-results)
196 }
197 sort.Slice(out, func(i, j int) bool { return out[i].Source.App < out[j].Source.App })
198 return out
199}
200func (a *App) renderDashboard(w http.ResponseWriter, r *http.Request, team dashboardTeam, results []dashboardResult) {
201 page := dashboardPage{Apps: directoryCatalog(*a.runtime), Teams: a.runtime.dashboard, Team: team, Sources: results, DocumentsComplete: false, EventsComplete: false}
202 // Every launcher belongs to this explicit grouping; no global preview fallback.
203 page.Apps = nil
204 for _, source := range team.launchers() {
205 for _, app := range directoryCatalog(*a.runtime) {
206 if app.Name == source.Name() {
207 app.Href = source.Origin + "/"
208 app.Status = ""
209 page.Apps = append(page.Apps, app)
210 }
211 }
212 }
213 documentProviders, eventProviders, documentFailures, eventFailures := 0, 0, 0, 0
214 for _, result := range results {
215 if result.Source.kind() == "events" {
216 eventProviders++
217 } else {
218 documentProviders++
219 }
220 if result.Status != "" {
221 if result.Source.kind() == "events" {
222 eventFailures++
223 } else {
224 documentFailures++
225 }
226 continue
227 }
228 for _, item := range result.Response.Items {
229 row := dashboardRow{Item: item, App: result.Source.Name(), AppID: result.Source.App, Icon: versioned("/static/brand/" + result.Source.App + ".svg")}
230 if result.Source.kind() == "documents" {
231 row.When = item.Updated.UTC().Format("2 Jan 2006, 15:04 UTC")
232 row.DateTime = item.Updated.Format(time.RFC3339)
233 page.Documents = append(page.Documents, row)
234 } else {
235 loc, _ := time.LoadLocation(result.Response.Timezone)
236 row.When = item.Start.In(loc).Format("Mon 2 Jan, 15:04 MST")
237 row.DateTime = item.Start.Format(time.RFC3339)
238 if item.AllDay {
239 row.When = item.StartDate + " · All day"
240 row.DateTime = item.StartDate
241 }
242 page.Events = append(page.Events, row)
243 }
244 }
245 }
246 page.DocumentsComplete = documentProviders > 0 && documentFailures == 0
247 page.EventsComplete = eventProviders > 0 && eventFailures == 0
248 sort.SliceStable(page.Documents, func(i, j int) bool {
249 if page.Documents[i].Updated.Equal(page.Documents[j].Updated) {
250 return page.Documents[i].URL < page.Documents[j].URL
251 }
252 return page.Documents[i].Updated.After(page.Documents[j].Updated)
253 })
254 if len(page.Documents) > 20 {
255 page.Documents = page.Documents[:20]
256 }
257 sort.SliceStable(page.Events, func(i, j int) bool { return page.Events[i].Start.Before(page.Events[j].Start) })
258 a.render(w, r, 200, "dashboard.html", page)
259}
260
261func dashboardNoStore(headers []string) bool {
262 found := false
263 for _, header := range headers {
264 for _, raw := range strings.Split(header, ",") {
265 directive := strings.ToLower(strings.TrimSpace(raw))
266 if directive == "no-store" {
267 found = true
268 }
269 if directive == "public" || strings.HasPrefix(directive, "s-maxage=") || strings.HasPrefix(directive, "max-age=") {
270 return false
271 }
272 }
273 }
274 return found
275}
276