id.go 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091
  1. package wire
  2. import (
  3. "encoding/json"
  4. "errors"
  5. "fmt"
  6. "net/url"
  7. "strings"
  8. )
  9. type UserID struct {
  10. Name string `json:"name,omitempty"`
  11. Domain string `json:"domain,omitempty"`
  12. Handle string `json:"handle,omitempty"`
  13. }
  14. type DeviceID struct {
  15. Name string `json:"name,omitempty"`
  16. Domain string `json:"domain,omitempty"`
  17. ClientID string `json:"client-id,omitempty"`
  18. Handle string `json:"handle,omitempty"`
  19. }
  20. func ParseUserID(value string) (id UserID, err error) {
  21. if err = json.Unmarshal([]byte(value), &id); err != nil {
  22. return
  23. }
  24. switch {
  25. case id.Handle == "":
  26. err = errors.New("handle must not be empty")
  27. case id.Name == "":
  28. err = errors.New("name must not be empty")
  29. case id.Domain == "":
  30. err = errors.New("domain must not be empty")
  31. }
  32. return
  33. }
  34. func ParseDeviceID(value string) (id DeviceID, err error) {
  35. if err = json.Unmarshal([]byte(value), &id); err != nil {
  36. return
  37. }
  38. switch {
  39. case id.Handle == "":
  40. err = errors.New("handle must not be empty")
  41. case id.Name == "":
  42. err = errors.New("name must not be empty")
  43. case id.Domain == "":
  44. err = errors.New("domain must not be empty")
  45. case id.ClientID == "":
  46. err = errors.New("client-id must not be empty")
  47. }
  48. return
  49. }
  50. type ClientID struct {
  51. Scheme string
  52. Username string
  53. DeviceID string
  54. Domain string
  55. }
  56. // ParseClientID parses a Wire clientID. The ClientID format is as follows:
  57. //
  58. // "wireapp://CzbfFjDOQrenCbDxVmgnFw!594930e9d50bb175@wire.com",
  59. //
  60. // where '!' is used as a separator between the user id & device id.
  61. func ParseClientID(clientID string) (ClientID, error) {
  62. clientIDURI, err := url.Parse(clientID)
  63. if err != nil {
  64. return ClientID{}, fmt.Errorf("invalid Wire client ID URI %q: %w", clientID, err)
  65. }
  66. if clientIDURI.Scheme != "wireapp" {
  67. return ClientID{}, fmt.Errorf("invalid Wire client ID scheme %q; expected \"wireapp\"", clientIDURI.Scheme)
  68. }
  69. fullUsername := clientIDURI.User.Username()
  70. parts := strings.SplitN(fullUsername, "!", 2)
  71. if len(parts) != 2 {
  72. return ClientID{}, fmt.Errorf("invalid Wire client ID username %q", fullUsername)
  73. }
  74. return ClientID{
  75. Scheme: clientIDURI.Scheme,
  76. Username: parts[0],
  77. DeviceID: parts[1],
  78. Domain: clientIDURI.Host,
  79. }, nil
  80. }