| 1 | package memoria |
| 2 | |
| 3 | import ( |
| 4 | "context" |
| 5 | "encoding/json" |
| 6 | "errors" |
| 7 | "fmt" |
| 8 | "strconv" |
| 9 | "strings" |
| 10 | "time" |
| 11 | |
| 12 | "amadan.net/oficina/suite" |
| 13 | |
| 14 | "amadan.net/oficina/memoria/internal/memoria/fact" |
| 15 | "amadan.net/oficina/memoria/internal/memoria/seal" |
| 16 | ) |
| 17 | |
| 18 | // §8.10's corrections: "Is this wrong?" lists a kind's candidates, the |
| 19 | // person picks the right one (or none) and says why, and the choice is |
| 20 | // kept — as coordinates and the person's own words, never passage text. |
| 21 | |
| 22 | // ErrChoiceGone is a POSTed handle that is not among the person's |
| 23 | // current candidates: forged, someone else's, for a revised document, or |
| 24 | // for one withheld since the page was shown. Nothing is stored. |
| 25 | var ErrChoiceGone = errors.New("correction: that choice is no longer available") |
| 26 | |
| 27 | // ReportCoord is a candidate as a coordinate, with no text. |
| 28 | type ReportCoord struct { |
| 29 | DocumentID int64 `json:"document_id"` |
| 30 | Revision int `json:"revision"` |
| 31 | ChunkID int64 `json:"chunk_id"` |
| 32 | Ordinal int `json:"ordinal"` |
| 33 | Start int `json:"start"` |
| 34 | End int `json:"end"` |
| 35 | } |
| 36 | |
| 37 | func (c ReportCoord) key() string { |
| 38 | return strconv.FormatInt(c.DocumentID, 10) + "/" + strconv.Itoa(c.Revision) + "/" + |
| 39 | strconv.FormatInt(c.ChunkID, 10) + "/" + strconv.Itoa(c.Start) + "-" + strconv.Itoa(c.End) |
| 40 | } |
| 41 | |
| 42 | // CorrectionKind is one deterministic kind's candidates for the page. |
| 43 | type CorrectionKind struct { |
| 44 | Kind string |
| 45 | Items []CorrectionItem |
| 46 | } |
| 47 | |
| 48 | // Noun is the kind's plural for a heading: "Phone numbers". |
| 49 | func (k CorrectionKind) Noun() string { |
| 50 | n := factNouns[k.Kind] |
| 51 | if n == "" { |
| 52 | return k.Kind |
| 53 | } |
| 54 | return strings.ToUpper(n[:1]) + n[1:] |
| 55 | } |
| 56 | |
| 57 | // CorrectionItem is one candidate as the correction page lists it. The |
| 58 | // Span is shown — it is from a passage this person's ruled search just |
| 59 | // returned — but never travels in the form: Handle is the radio value. |
| 60 | type CorrectionItem struct { |
| 61 | Span, Label, Title, Trail string |
| 62 | Own, Shown bool |
| 63 | DocumentID int64 |
| 64 | Ordinal int |
| 65 | Handle string |
| 66 | coord ReportCoord |
| 67 | } |
| 68 | |
| 69 | // reportPayload is the sealed report: coordinates and the person's own |
| 70 | // words, and nothing else (gate 42 decrypts and checks this). |
| 71 | type reportPayload struct { |
| 72 | Query string `json:"query"` |
| 73 | Kind string `json:"kind"` |
| 74 | Qualifiers []string `json:"qualifiers"` |
| 75 | Note string `json:"note"` |
| 76 | Shown *ReportCoord `json:"shown"` |
| 77 | Chosen *ReportCoord `json:"chosen"` |
| 78 | Listed []ReportCoord `json:"listed"` |
| 79 | } |
| 80 | |
| 81 | // SearchForCorrection is the correction page's search: whole words, the |
| 82 | // §4.1 ruling and §8.8's candidates, and never §8.9's model step, |
| 83 | // whatever the query names. It returns each deterministic kind the query |
| 84 | // named that has candidates, each candidate with its opaque handle. |
| 85 | // |
| 86 | // The notices are §4.1's loud withholding: an UNKNOWN ruling must say so |
| 87 | // here as it does on the search page, or a partial list reads as whole. |
| 88 | func (s *Store) SearchForCorrection(ctx context.Context, asker suite.Subject, query string) ([]CorrectionKind, []string, error) { |
| 89 | page, err := s.search(ctx, asker, query, 25, modeCorrection) |
| 90 | if err != nil { |
| 91 | return nil, nil, err |
| 92 | } |
| 93 | revs, err := s.revisions(ctx, page.candidates) |
| 94 | if err != nil { |
| 95 | return nil, nil, err |
| 96 | } |
| 97 | shown := map[string]bool{} |
| 98 | for _, f := range page.Facts { |
| 99 | shown[strconv.FormatInt(f.DocumentID, 10)+"/"+strconv.Itoa(f.Ordinal)+"/"+f.Span] = true |
| 100 | } |
| 101 | var out []CorrectionKind |
| 102 | for _, k := range fact.Kinds() { |
| 103 | cs := page.candidates[k] |
| 104 | if fact.ModelKind(k) || len(cs) == 0 { |
| 105 | continue |
| 106 | } |
| 107 | ck := CorrectionKind{Kind: string(k)} |
| 108 | for _, c := range cs { |
| 109 | coord := ReportCoord{ |
| 110 | DocumentID: c.fact.DocumentID, Revision: revs[c.fact.DocumentID], |
| 111 | ChunkID: c.chunkID, Ordinal: c.fact.Ordinal, Start: c.start, End: c.end, |
| 112 | } |
| 113 | h, err := s.choiceHandle(asker, query, string(k), coord) |
| 114 | if err != nil { |
| 115 | return nil, nil, err |
| 116 | } |
| 117 | label := c.fact.Label |
| 118 | if !c.own { |
| 119 | label = "" |
| 120 | } |
| 121 | ck.Items = append(ck.Items, CorrectionItem{ |
| 122 | Span: c.fact.Span, Label: label, Title: c.fact.Title, Trail: c.fact.Trail, |
| 123 | Own: c.own, DocumentID: c.fact.DocumentID, Ordinal: c.fact.Ordinal, |
| 124 | Shown: shown[strconv.FormatInt(c.fact.DocumentID, 10)+"/"+strconv.Itoa(c.fact.Ordinal)+"/"+c.fact.Span], |
| 125 | Handle: h, coord: coord, |
| 126 | }) |
| 127 | } |
| 128 | out = append(out, ck) |
| 129 | } |
| 130 | return out, page.Notices, nil |
| 131 | } |
| 132 | |
| 133 | // revisions reads the current revision of every document a candidate |
| 134 | // cites, in one query. |
| 135 | func (s *Store) revisions(ctx context.Context, cands map[fact.Kind][]factCandidate) (map[int64]int, error) { |
| 136 | var ids []int64 |
| 137 | seen := map[int64]bool{} |
| 138 | for _, cs := range cands { |
| 139 | for _, c := range cs { |
| 140 | if !seen[c.fact.DocumentID] { |
| 141 | seen[c.fact.DocumentID] = true |
| 142 | ids = append(ids, c.fact.DocumentID) |
| 143 | } |
| 144 | } |
| 145 | } |
| 146 | out := map[int64]int{} |
| 147 | if len(ids) == 0 { |
| 148 | return out, nil |
| 149 | } |
| 150 | var rows []Document |
| 151 | if err := s.db.G.WithContext(ctx).Select("id", "revision").Where("id IN ?", ids).Find(&rows).Error; err != nil { |
| 152 | return nil, err |
| 153 | } |
| 154 | for _, d := range rows { |
| 155 | out[d.ID] = d.Revision |
| 156 | } |
| 157 | return out, nil |
| 158 | } |
| 159 | |
| 160 | // choiceHandle is a radio button's value: a keyed fingerprint over the |
| 161 | // asker, the query, the kind and the coordinate. It carries no value and |
| 162 | // no span, and it is useless to anyone else or for any other query. |
| 163 | func (s *Store) choiceHandle(asker suite.Subject, query, kind string, c ReportCoord) (string, error) { |
| 164 | return s.sealer.Fingerprint(seal.PurposeChoice, |
| 165 | []byte(asker.Value+"\x00"+query+"\x00"+kind+"\x00"+c.key())) |
| 166 | } |
| 167 | |
| 168 | // SaveCorrection stores one correction. It re-runs the deterministic |
| 169 | // ruled search, so the choice is checked against what this person may |
| 170 | // see now: a handle not among their current candidates is ErrChoiceGone |
| 171 | // and nothing is stored. handle "none" means "None of these". |
| 172 | func (s *Store) SaveCorrection(ctx context.Context, asker suite.Subject, query, kind, handle, note string) error { |
| 173 | kinds, _, err := s.SearchForCorrection(ctx, asker, query) |
| 174 | if err != nil { |
| 175 | return err |
| 176 | } |
| 177 | var ck *CorrectionKind |
| 178 | for i := range kinds { |
| 179 | if kinds[i].Kind == kind { |
| 180 | ck = &kinds[i] |
| 181 | } |
| 182 | } |
| 183 | if ck == nil { |
| 184 | return ErrChoiceGone |
| 185 | } |
| 186 | p := reportPayload{Query: query, Kind: kind, Qualifiers: fact.Qualifiers(query), Note: strings.TrimSpace(note)} |
| 187 | found := handle == "none" |
| 188 | for _, it := range ck.Items { |
| 189 | c := it.coord |
| 190 | p.Listed = append(p.Listed, c) |
| 191 | if it.Shown && p.Shown == nil { |
| 192 | p.Shown = &c |
| 193 | } |
| 194 | if !found && it.Handle == handle { |
| 195 | p.Chosen = &c |
| 196 | found = true |
| 197 | } |
| 198 | } |
| 199 | if !found { |
| 200 | return ErrChoiceGone |
| 201 | } |
| 202 | raw, err := json.Marshal(p) |
| 203 | if err != nil { |
| 204 | return err |
| 205 | } |
| 206 | sealed, err := s.sealer.Seal(seal.PurposeReport, raw) |
| 207 | if err != nil { |
| 208 | return err |
| 209 | } |
| 210 | print, err := s.sealer.Fingerprint(seal.PurposeReporter, []byte(asker.Value)) |
| 211 | if err != nil { |
| 212 | return err |
| 213 | } |
| 214 | return s.guarded(ctx, memberWrite, func(db *gormTx) error { |
| 215 | return db.Create(&FactReport{ReporterPrint: print, SealedReport: sealed}).Error |
| 216 | }) |
| 217 | } |
| 218 | |
| 219 | // ReportView is one of the person's own reports as /reports lists it. |
| 220 | type ReportView struct { |
| 221 | ID int64 |
| 222 | Query string |
| 223 | Kind string |
| 224 | Note string |
| 225 | Created time.Time |
| 226 | Shown *ReportLink |
| 227 | Chosen *ReportLink |
| 228 | None bool |
| 229 | } |
| 230 | |
| 231 | // ReportLink is a coordinate as a link. Status is "", "changed since" or |
| 232 | // "no longer available", decided here on the server; the link itself is |
| 233 | // a plain document URL and goes through that page's own §4.1 check. |
| 234 | type ReportLink struct { |
| 235 | Href string |
| 236 | Status string |
| 237 | } |
| 238 | |
| 239 | // Reports lists the asker's own reports, newest first. Nobody else's: |
| 240 | // the query is matched by the reporter's keyed print. |
| 241 | func (s *Store) Reports(ctx context.Context, asker suite.Subject) ([]ReportView, error) { |
| 242 | print, err := s.sealer.Fingerprint(seal.PurposeReporter, []byte(asker.Value)) |
| 243 | if err != nil { |
| 244 | return nil, err |
| 245 | } |
| 246 | var rows []FactReport |
| 247 | if err := s.db.G.WithContext(ctx).Where("reporter_print = ?", print).Order("id DESC").Find(&rows).Error; err != nil { |
| 248 | return nil, err |
| 249 | } |
| 250 | var out []ReportView |
| 251 | for _, r := range rows { |
| 252 | raw, err := s.sealer.Open(seal.PurposeReport, r.SealedReport) |
| 253 | if err != nil { |
| 254 | return nil, err |
| 255 | } |
| 256 | var p reportPayload |
| 257 | if err := json.Unmarshal(raw, &p); err != nil { |
| 258 | return nil, err |
| 259 | } |
| 260 | v := ReportView{ID: r.ID, Query: p.Query, Kind: p.Kind, Note: p.Note, Created: r.CreatedAt, None: p.Chosen == nil} |
| 261 | if v.Shown, err = s.reportLink(ctx, p.Shown); err != nil { |
| 262 | return nil, err |
| 263 | } |
| 264 | if v.Chosen, err = s.reportLink(ctx, p.Chosen); err != nil { |
| 265 | return nil, err |
| 266 | } |
| 267 | out = append(out, v) |
| 268 | } |
| 269 | return out, nil |
| 270 | } |
| 271 | |
| 272 | func (s *Store) reportLink(ctx context.Context, c *ReportCoord) (*ReportLink, error) { |
| 273 | if c == nil { |
| 274 | return nil, nil |
| 275 | } |
| 276 | l := &ReportLink{Href: fmt.Sprintf("/documents/%d#p%d", c.DocumentID, c.Ordinal)} |
| 277 | var d Document |
| 278 | err := s.db.G.WithContext(ctx).Select("id", "revision").Where("id = ?", c.DocumentID).Limit(1).Find(&d).Error |
| 279 | switch { |
| 280 | case err != nil: |
| 281 | return nil, err |
| 282 | case d.ID == 0: |
| 283 | l.Status = "no longer available" |
| 284 | case d.Revision != c.Revision: |
| 285 | l.Status = "changed since" |
| 286 | } |
| 287 | return l, nil |
| 288 | } |
| 289 | |
| 290 | // DeleteReport deletes one of the asker's own reports. Anyone else's id |
| 291 | // is ErrNotFound, which the handler answers 404. |
| 292 | func (s *Store) DeleteReport(ctx context.Context, asker suite.Subject, id int64) error { |
| 293 | print, err := s.sealer.Fingerprint(seal.PurposeReporter, []byte(asker.Value)) |
| 294 | if err != nil { |
| 295 | return err |
| 296 | } |
| 297 | return s.guarded(ctx, memberWrite, func(db *gormTx) error { |
| 298 | res := db.Where("id = ? AND reporter_print = ?", id, print).Delete(&FactReport{}) |
| 299 | if res.Error != nil { |
| 300 | return res.Error |
| 301 | } |
| 302 | if res.RowsAffected == 0 { |
| 303 | return ErrReportNotFound |
| 304 | } |
| 305 | return nil |
| 306 | }) |
| 307 | } |
| 308 | |
| 309 | // ErrReportNotFound is a report id that is not the asker's. |
| 310 | var ErrReportNotFound = errors.New("correction: no such report") |
| 311 | |