From 100bcaabf80bffce735f4fd53cd7387eb528dde2 Mon Sep 17 00:00:00 2001 From: Tulir Asokan Date: Wed, 8 Apr 2020 14:53:20 +0300 Subject: [PATCH] Add Matrix content URI parsing --- contenturi.go | 47 +++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 47 insertions(+) create mode 100644 contenturi.go diff --git a/contenturi.go b/contenturi.go new file mode 100644 index 00000000..f863b731 --- /dev/null +++ b/contenturi.go @@ -0,0 +1,47 @@ +package mautrix + +import ( + "errors" + "fmt" + "strings" +) + +var InvalidContentURI = errors.New("invalid Matrix content URI") + +type ContentURI struct { + Homeserver string + FileID string +} + +func ParseContentURI(uri string) (parsed ContentURI, err error) { + if !strings.HasPrefix(uri, "mxc://") { + err = InvalidContentURI + } else if index := strings.IndexRune(uri[6:], '/'); index == -1 || index == len(uri)-7 { + err = InvalidContentURI + } else { + parsed.Homeserver = uri[6 : 6+index] + parsed.FileID = uri[6+index+1:] + } + return +} + +func (uri *ContentURI) UnmarshalJSON(raw []byte) (err error) { + parsed, err := ParseContentURI(string(raw)) + if err != nil { + return err + } + *uri = parsed + return nil +} + +func (uri *ContentURI) MarshalJSON() ([]byte, error) { + return []byte(uri.String()), nil +} + +func (uri *ContentURI) String() string { + return fmt.Sprintf("mxc://%s/%s", uri.Homeserver, uri.FileID) +} + +func (uri *ContentURI) IsEmpty() bool { + return len(uri.Homeserver) == 0 || len(uri.FileID) == 0 +} \ No newline at end of file