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.

89 lines
1.6 KiB

2 years ago
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. "strings"
  6. )
  7. type PointerMatcher interface {
  8. Match(str string) bool
  9. }
  10. type Pointer struct {
  11. ID string `json:"id"`
  12. Aliases []string `json:"aliases"`
  13. }
  14. func (p *Pointer) AddAlias(alias string) (added *string, removed *string) {
  15. if !strings.HasPrefix(alias, "lucifer:") {
  16. return
  17. }
  18. for _, alias2 := range p.Aliases {
  19. if alias2 == alias {
  20. return
  21. }
  22. }
  23. if strings.HasPrefix(alias, "lucifer:name:") {
  24. for i, alias2 := range p.Aliases {
  25. if strings.HasPrefix(alias2, "lucifer:name:") {
  26. p.Aliases = append(p.Aliases[:0:0], p.Aliases...)
  27. p.Aliases = append(p.Aliases[:i], p.Aliases[i+1:]...)
  28. removed = gentools.ShallowCopy(&alias2)
  29. break
  30. }
  31. }
  32. }
  33. added = gentools.ShallowCopy(&alias)
  34. p.Aliases = append(p.Aliases, alias)
  35. return
  36. }
  37. func (p *Pointer) RemoveAlias(alias string) bool {
  38. if strings.HasPrefix(alias, "lucifer:name:") {
  39. // Name cannot be removed like this.
  40. return false
  41. }
  42. for i, alias2 := range p.Aliases {
  43. if alias2 == alias {
  44. p.Aliases = append(p.Aliases[:0:0], p.Aliases...)
  45. p.Aliases = append(p.Aliases[:i], p.Aliases[i+1:]...)
  46. return true
  47. }
  48. }
  49. return false
  50. }
  51. func (p *Pointer) Name() string {
  52. for _, alias := range p.Aliases {
  53. if strings.HasPrefix(alias, "lucifer:name:") {
  54. return alias
  55. }
  56. }
  57. return ""
  58. }
  59. func (p *Pointer) Matches(matcher PointerMatcher) bool {
  60. defer func() {
  61. if err := recover(); err != nil {
  62. log.Println("[PANIC]", err)
  63. }
  64. }()
  65. if matcher.Match(p.ID) {
  66. return true
  67. }
  68. for _, alias := range p.Aliases {
  69. if matcher.Match(alias) {
  70. return true
  71. }
  72. }
  73. return false
  74. }