You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

102 lines
1.8 KiB

2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
  1. package device
  2. import (
  3. "git.aiterp.net/lucifer3/server/internal/gentools"
  4. "log"
  5. "sort"
  6. "strings"
  7. )
  8. var exclusivePrefixes = []string{
  9. "lucifer:name:",
  10. "lucifer:icon:",
  11. "lucifer:room:",
  12. "lucifer:group:",
  13. }
  14. type PointerMatcher interface {
  15. Match(str string) bool
  16. }
  17. type Pointer struct {
  18. ID string `json:"id"`
  19. Aliases []string `json:"aliases"`
  20. }
  21. func (p *Pointer) AddAlias(alias string) (added *string, removed *string) {
  22. if !strings.HasPrefix(alias, "lucifer:") {
  23. return
  24. }
  25. for _, alias2 := range p.Aliases {
  26. if alias2 == alias {
  27. return
  28. }
  29. }
  30. for _, prefix := range exclusivePrefixes {
  31. if strings.HasPrefix(alias, prefix) {
  32. for i, alias2 := range p.Aliases {
  33. if strings.HasPrefix(alias2, prefix) {
  34. p.Aliases = append(p.Aliases[:0:0], p.Aliases...)
  35. p.Aliases = append(p.Aliases[:i], p.Aliases[i+1:]...)
  36. removed = gentools.ShallowCopy(&alias2)
  37. break
  38. }
  39. }
  40. break
  41. }
  42. }
  43. added = gentools.ShallowCopy(&alias)
  44. p.Aliases = append(p.Aliases, alias)
  45. sort.Strings(p.Aliases)
  46. return
  47. }
  48. func (p *Pointer) RemoveAlias(alias string) bool {
  49. if strings.HasPrefix(alias, "lucifer:name:") {
  50. // Name cannot be removed like this.
  51. return false
  52. }
  53. for i, alias2 := range p.Aliases {
  54. if alias2 == alias {
  55. p.Aliases = append(p.Aliases[:0:0], p.Aliases...)
  56. p.Aliases = append(p.Aliases[:i], p.Aliases[i+1:]...)
  57. return true
  58. }
  59. }
  60. return false
  61. }
  62. func (p *Pointer) Name() string {
  63. for _, alias := range p.Aliases {
  64. if strings.HasPrefix(alias, "lucifer:name:") {
  65. return alias
  66. }
  67. }
  68. return ""
  69. }
  70. func (p *Pointer) Matches(matcher PointerMatcher) bool {
  71. defer func() {
  72. if err := recover(); err != nil {
  73. log.Println("[PANIC]", err)
  74. }
  75. }()
  76. if matcher.Match(p.ID) {
  77. return true
  78. }
  79. for _, alias := range p.Aliases {
  80. if matcher.Match(alias) {
  81. return true
  82. }
  83. }
  84. return false
  85. }