github.com/kyleu/dbaudit@v0.0.2-0.20240321155047-ff2f2c940496/app/lib/user/accounts.go (about) 1 // Package user - Content managed by Project Forge, see [projectforge.md] for details. 2 package user 3 4 import ( 5 "cmp" 6 "slices" 7 "strings" 8 9 "github.com/samber/lo" 10 11 "github.com/kyleu/dbaudit/app/util" 12 ) 13 14 type Accounts []*Account 15 16 func (a Accounts) String() string { 17 return strings.Join(lo.Map(a, func(x *Account, _ int) string { 18 return x.String() 19 }), ",") 20 } 21 22 func (a Accounts) TitleString() string { 23 return strings.Join(lo.Map(a, func(x *Account, _ int) string { 24 return x.TitleString() 25 }), ",") 26 } 27 28 func (a Accounts) Images() []string { 29 ret := make(util.KeyVals[string], 0, len(a)) 30 lo.ForEach(a, func(x *Account, _ int) { 31 if x.Picture != "" { 32 ret = append(ret, &util.KeyVal[string]{Key: x.Provider, Val: x.Picture}) 33 } 34 }) 35 return ret.Values() 36 } 37 38 func (a Accounts) Image() string { 39 if is := a.Images(); len(is) > 0 { 40 return is[0] 41 } 42 return "" 43 } 44 45 func (a Accounts) Sort() { 46 slices.SortFunc(a, func(l *Account, r *Account) int { 47 if l.Provider == r.Provider { 48 return cmp.Compare(strings.ToLower(l.Email), strings.ToLower(r.Email)) 49 } 50 return cmp.Compare(l.Provider, r.Provider) 51 }) 52 } 53 54 func (a Accounts) GetByProvider(p string) Accounts { 55 return lo.Filter(a, func(x *Account, _ int) bool { 56 return x.Provider == p 57 }) 58 } 59 60 func (a Accounts) GetByProviderDomain(p string, d string) *Account { 61 return lo.FindOrElse(a, nil, func(x *Account) bool { 62 return x.Provider == p && x.Domain() == d 63 }) 64 } 65 66 func (a Accounts) Matches(match string) bool { 67 if match == "" || match == "*" { 68 return true 69 } 70 if strings.Contains(match, ",") { 71 return lo.ContainsBy(util.StringSplitAndTrim(match, ","), func(x string) bool { 72 return a.Matches(x) 73 }) 74 } 75 prv, acct := util.StringSplit(match, ':', true) 76 for _, x := range a { 77 if x.Provider == prv { 78 if acct == "" { 79 return true 80 } 81 return strings.HasSuffix(x.Email, acct) 82 } 83 } 84 return false 85 } 86 87 func (a Accounts) Purge(keys ...string) Accounts { 88 ret := make(Accounts, 0, len(a)) 89 for _, ss := range a { 90 hit := false 91 for _, key := range keys { 92 if ss.Provider == key { 93 hit = true 94 } 95 } 96 if !hit { 97 ret = append(ret, ss) 98 } 99 } 100 return ret 101 } 102 103 func AccountsFromString(s string) Accounts { 104 return lo.Map(util.StringSplitAndTrim(s, ","), func(x string, _ int) *Account { 105 return accountFromString(x) 106 }) 107 }