| 1 | package mapa |
| 2 | |
| 3 | import ( |
| 4 | "context" |
| 5 | "errors" |
| 6 | "strings" |
| 7 | |
| 8 | "amadan.net/oficina/mapa/internal/mapa/locale" |
| 9 | "amadan.net/oficina/mapa/internal/mapa/seal" |
| 10 | ) |
| 11 | |
| 12 | // A person's own date and number format (level-up build note 85): an |
| 13 | // offered locale's code, sealed on their member row as the time zone |
| 14 | // is, and set with an event. Unset, Mapa follows their browser. |
| 15 | |
| 16 | // ErrBadLocale is a format Mapa does not offer. |
| 17 | var ErrBadLocale = errors.New("that is not a date format Mapa offers") |
| 18 | |
| 19 | func (store *Store) openLocale(member Member) (string, error) { |
| 20 | if len(member.SealedLocale) == 0 { |
| 21 | return "", nil |
| 22 | } |
| 23 | plain, err := store.sealer.Open(seal.PurposeLocale, member.SealedLocale) |
| 24 | return string(plain), err |
| 25 | } |
| 26 | |
| 27 | // SetLocale records a person's own date and number format; "" goes back |
| 28 | // to following their browser. Saving what is already set writes |
| 29 | // nothing: no event, and no member row for a person who has none. |
| 30 | func (store *Store) SetLocale(ctx context.Context, address, |
| 31 | code string) error { |
| 32 | code = strings.TrimSpace(code) |
| 33 | if code != "" && locale.Get(code) == nil { |
| 34 | return ErrBadLocale |
| 35 | } |
| 36 | if now, err := store.ownLocaleOf(ctx, address); err != nil || |
| 37 | now == code { |
| 38 | return err |
| 39 | } |
| 40 | return store.write(ctx, func(tx *Tx) error { |
| 41 | memberID, err := tx.member(address) |
| 42 | if err != nil { |
| 43 | return err |
| 44 | } |
| 45 | var sealed []byte |
| 46 | if code != "" { |
| 47 | if sealed, err = store.sealer.Seal(seal.PurposeLocale, |
| 48 | []byte(code)); err != nil { |
| 49 | return err |
| 50 | } |
| 51 | } |
| 52 | err = tx.db.Model(&Member{}).Where("id = ?", memberID). |
| 53 | Update("sealed_locale", sealed).Error |
| 54 | if err != nil { |
| 55 | return err |
| 56 | } |
| 57 | return tx.log(memberID, ObjectMember, memberID, VerbLocaleSet, 0) |
| 58 | }) |
| 59 | } |
| 60 | |
| 61 | // ownLocaleOf is the code address has stored, "" with no member row. |
| 62 | func (store *Store) ownLocaleOf(ctx context.Context, |
| 63 | address string) (string, error) { |
| 64 | member, found, err := store.memberByAddress(store.database. |
| 65 | WithContext(ctx), normaliseAddress(address)) |
| 66 | if err != nil || !found { |
| 67 | return "", err |
| 68 | } |
| 69 | return store.openLocale(member) |
| 70 | } |
| 71 | |