| 1 |
// Copyright (c) 2021 Tulir Asokan |
| 2 |
// |
| 3 |
// This Source Code Form is subject to the terms of the Mozilla Public |
| 4 |
// License, v. 2.0. If a copy of the MPL was not distributed with this |
| 5 |
// file, You can obtain one at http://mozilla.org/MPL/2.0/. |
| 6 |
|
| 7 |
package id |
| 8 |
|
| 9 |
import ( |
| 10 |
"errors" |
| 11 |
"fmt" |
| 12 |
"net/url" |
| 13 |
"strings" |
| 14 |
) |
| 15 |
|
| 16 |
// Errors that can happen when parsing matrix: URIs |
| 17 |
var ( |
| 18 |
ErrInvalidScheme = errors.New("matrix URI scheme must be exactly 'matrix'") |
| 19 |
ErrInvalidPartCount = errors.New("matrix URIs must have exactly 2 or 4 segments") |
| 20 |
ErrInvalidFirstSegment = errors.New("invalid identifier in first segment of matrix URI") |
| 21 |
ErrEmptySecondSegment = errors.New("the second segment of the matrix URI must not be empty") |
| 22 |
ErrInvalidThirdSegment = errors.New("invalid identifier in third segment of matrix URI") |
| 23 |
ErrEmptyFourthSegment = errors.New("the fourth segment of the matrix URI must not be empty when the third segment is present") |
| 24 |
) |
| 25 |
|
| 26 |
// Errors that can happen when parsing matrix.to URLs |
| 27 |
var ( |
| 28 |
ErrNotMatrixTo = errors.New("that URL is not a matrix.to URL") |
| 29 |
ErrInvalidMatrixToPartCount = errors.New("matrix.to URLs must have exactly 1 or 2 segments") |
| 30 |
ErrEmptyMatrixToPrimaryIdentifier = errors.New("the primary identifier in the matrix.to URL is empty") |
| 31 |
ErrInvalidMatrixToPrimaryIdentifier = errors.New("the primary identifier in the matrix.to URL has an invalid sigil") |
| 32 |
ErrInvalidMatrixToSecondaryIdentifier = errors.New("the secondary identifier in the matrix.to URL has an invalid sigil") |
| 33 |
) |
| 34 |
|
| 35 |
var ErrNotMatrixToOrMatrixURI = errors.New("that URL is not a matrix.to URL nor matrix: URI") |
| 36 |
|
| 37 |
// MatrixURI contains the result of parsing a matrix: URI using ParseMatrixURI |
| 38 |
type MatrixURI struct { |
| 39 |
Sigil1 rune |
| 40 |
Sigil2 rune |
| 41 |
MXID1 string |
| 42 |
MXID2 string |
| 43 |
Via []string |
| 44 |
Action string |
| 45 |
} |
| 46 |
|
| 47 |
// SigilToPathSegment contains a mapping from Matrix identifier sigils to matrix: URI path segments. |
| 48 |
var SigilToPathSegment = map[rune]string{ |
| 49 |
'$': "e", |
| 50 |
'#': "r", |
| 51 |
'!': "roomid", |
| 52 |
'@': "u", |
| 53 |
} |
| 54 |
|
| 55 |
func (uri *MatrixURI) getQuery() url.Values { |
| 56 |
q := make(url.Values) |
| 57 |
if uri.Via != nil && len(uri.Via) > 0 { |
| 58 |
q["via"] = uri.Via |
| 59 |
} |
| 60 |
if len(uri.Action) > 0 { |
| 61 |
q.Set("action", uri.Action) |
| 62 |
} |
| 63 |
return q |
| 64 |
} |
| 65 |
|
| 66 |
// String converts the parsed matrix: URI back into the string representation. |
| 67 |
func (uri *MatrixURI) String() string { |
| 68 |
parts := []string{ |
| 69 |
SigilToPathSegment[uri.Sigil1], |
| 70 |
uri.MXID1, |
| 71 |
} |
| 72 |
if uri.Sigil2 != 0 { |
| 73 |
parts = append(parts, SigilToPathSegment[uri.Sigil2], uri.MXID2) |
| 74 |
} |
| 75 |
return (&url.URL{ |
| 76 |
Scheme: "matrix", |
| 77 |
Opaque: strings.Join(parts, "/"), |
| 78 |
RawQuery: uri.getQuery().Encode(), |
| 79 |
}).String() |
| 80 |
} |
| 81 |
|
| 82 |
// MatrixToURL converts to parsed matrix: URI into a matrix.to URL |
| 83 |
func (uri *MatrixURI) MatrixToURL() string { |
| 84 |
fragment := fmt.Sprintf("#/%s", url.QueryEscape(uri.PrimaryIdentifier())) |
| 85 |
if uri.Sigil2 != 0 { |
| 86 |
fragment = fmt.Sprintf("%s/%s", fragment, url.QueryEscape(uri.SecondaryIdentifier())) |
| 87 |
} |
| 88 |
query := uri.getQuery().Encode() |
| 89 |
if len(query) > 0 { |
| 90 |
fragment = fmt.Sprintf("%s?%s", fragment, query) |
| 91 |
} |
| 92 |
// It would be nice to use URL{...}.String() here, but figuring out the Fragment vs RawFragment stuff is a pain |
| 93 |
return fmt.Sprintf("https://matrix.to/%s", fragment) |
| 94 |
} |
| 95 |
|
| 96 |
// PrimaryIdentifier returns the first Matrix identifier in the URI. |
| 97 |
// Currently room IDs, room aliases and user IDs can be in the primary identifier slot. |
| 98 |
func (uri *MatrixURI) PrimaryIdentifier() string { |
| 99 |
return fmt.Sprintf("%c%s", uri.Sigil1, uri.MXID1) |
| 100 |
} |
| 101 |
|
| 102 |
// SecondaryIdentifier returns the second Matrix identifier in the URI. |
| 103 |
// Currently only event IDs can be in the secondary identifier slot. |
| 104 |
func (uri *MatrixURI) SecondaryIdentifier() string { |
| 105 |
if uri.Sigil2 == 0 { |
| 106 |
return "" |
| 107 |
} |
| 108 |
return fmt.Sprintf("%c%s", uri.Sigil2, uri.MXID2) |
| 109 |
} |
| 110 |
|
| 111 |
// UserID returns the user ID from the URI if the primary identifier is a user ID. |
| 112 |
func (uri *MatrixURI) UserID() UserID { |
| 113 |
if uri.Sigil1 == '@' { |
| 114 |
return UserID(uri.PrimaryIdentifier()) |
| 115 |
} |
| 116 |
return "" |
| 117 |
} |
| 118 |
|
| 119 |
// RoomID returns the room ID from the URI if the primary identifier is a room ID. |
| 120 |
func (uri *MatrixURI) RoomID() RoomID { |
| 121 |
if uri.Sigil1 == '!' { |
| 122 |
return RoomID(uri.PrimaryIdentifier()) |
| 123 |
} |
| 124 |
return "" |
| 125 |
} |
| 126 |
|
| 127 |
// RoomAlias returns the room alias from the URI if the primary identifier is a room alias. |
| 128 |
func (uri *MatrixURI) RoomAlias() RoomAlias { |
| 129 |
if uri.Sigil1 == '#' { |
| 130 |
return RoomAlias(uri.PrimaryIdentifier()) |
| 131 |
} |
| 132 |
return "" |
| 133 |
} |
| 134 |
|
| 135 |
// EventID returns the event ID from the URI if the primary identifier is a room ID or alias and the secondary identifier is an event ID. |
| 136 |
func (uri *MatrixURI) EventID() EventID { |
| 137 |
if (uri.Sigil1 == '!' || uri.Sigil1 == '#') && uri.Sigil2 == '$' { |
| 138 |
return EventID(uri.SecondaryIdentifier()) |
| 139 |
} |
| 140 |
return "" |
| 141 |
} |
| 142 |
|
| 143 |
// ParseMatrixURIOrMatrixToURL parses the given matrix.to URL or matrix: URI into a unified representation. |
| 144 |
func ParseMatrixURIOrMatrixToURL(uri string) (*MatrixURI, error) { |
| 145 |
parsed, err := url.Parse(uri) |
| 146 |
if err != nil { |
| 147 |
return nil, fmt.Errorf("failed to parse URI: %w", err) |
| 148 |
} |
| 149 |
if parsed.Scheme == "matrix" { |
| 150 |
return ProcessMatrixURI(parsed) |
| 151 |
} else if strings.HasSuffix(parsed.Hostname(), "matrix.to") { |
| 152 |
return ProcessMatrixToURL(parsed) |
| 153 |
} else { |
| 154 |
return nil, ErrNotMatrixToOrMatrixURI |
| 155 |
} |
| 156 |
} |
| 157 |
|
| 158 |
// ParseMatrixURI implements the matrix: URI parsing algorithm. |
| 159 |
// |
| 160 |
// Currently specified in https://github.com/matrix-org/matrix-doc/blob/master/proposals/2312-matrix-uri.md#uri-parsing-algorithm |
| 161 |
func ParseMatrixURI(uri string) (*MatrixURI, error) { |
| 162 |
// Step 1: parse the URI according to RFC 3986 |
| 163 |
parsed, err := url.Parse(uri) |
| 164 |
if err != nil { |
| 165 |
return nil, fmt.Errorf("failed to parse URI: %w", err) |
| 166 |
} |
| 167 |
return ProcessMatrixURI(parsed) |
| 168 |
} |
| 169 |
|
| 170 |
// ProcessMatrixURI implements steps 2-7 of the matrix: URI parsing algorithm |
| 171 |
// (i.e. everything except parsing the URI itself, which is done with url.Parse or ParseMatrixURI) |
| 172 |
func ProcessMatrixURI(uri *url.URL) (*MatrixURI, error) { |
| 173 |
// Step 2: check that scheme is exactly `matrix` |
| 174 |
if uri.Scheme != "matrix" { |
| 175 |
return nil, ErrInvalidScheme |
| 176 |
} |
| 177 |
|
| 178 |
// Step 3: split the path into segments separated by / |
| 179 |
parts := strings.Split(uri.Opaque, "/") |
| 180 |
|
| 181 |
// Step 4: Check that the URI contains either 2 or 4 segments |
| 182 |
if len(parts) != 2 && len(parts) != 4 { |
| 183 |
return nil, ErrInvalidPartCount |
| 184 |
} |
| 185 |
|
| 186 |
var parsed MatrixURI |
| 187 |
|
| 188 |
// Step 5: Construct the top-level Matrix identifier |
| 189 |
// a: find the sigil from the first segment |
| 190 |
switch parts[0] { |
| 191 |
case "u", "user": |
| 192 |
parsed.Sigil1 = '@' |
| 193 |
case "r", "room": |
| 194 |
parsed.Sigil1 = '#' |
| 195 |
case "roomid": |
| 196 |
parsed.Sigil1 = '!' |
| 197 |
default: |
| 198 |
return nil, fmt.Errorf("%w: '%s'", ErrInvalidFirstSegment, parts[0]) |
| 199 |
} |
| 200 |
// b: find the identifier from the second segment |
| 201 |
if len(parts[1]) == 0 { |
| 202 |
return nil, ErrEmptySecondSegment |
| 203 |
} |
| 204 |
parsed.MXID1 = parts[1] |
| 205 |
|
| 206 |
// Step 6: if the first part is a room and the URI has 4 segments, construct a second level identifier |
| 207 |
if (parsed.Sigil1 == '!' || parsed.Sigil1 == '#') && len(parts) == 4 { |
| 208 |
// a: find the sigil from the third segment |
| 209 |
switch parts[2] { |
| 210 |
case "e", "event": |
| 211 |
parsed.Sigil2 = '$' |
| 212 |
default: |
| 213 |
return nil, fmt.Errorf("%w: '%s'", ErrInvalidThirdSegment, parts[0]) |
| 214 |
} |
| 215 |
|
| 216 |
// b: find the identifier from the fourth segment |
| 217 |
if len(parts[3]) == 0 { |
| 218 |
return nil, ErrEmptyFourthSegment |
| 219 |
} |
| 220 |
parsed.MXID2 = parts[3] |
| 221 |
} |
| 222 |
|
| 223 |
// Step 7: parse the query and extract via and action items |
| 224 |
via, ok := uri.Query()["via"] |
| 225 |
if ok && len(via) > 0 { |
| 226 |
parsed.Via = via |
| 227 |
} |
| 228 |
action, ok := uri.Query()["action"] |
| 229 |
if ok && len(action) > 0 { |
| 230 |
parsed.Action = action[len(action)-1] |
| 231 |
} |
| 232 |
|
| 233 |
return &parsed, nil |
| 234 |
} |
| 235 |
|
| 236 |
// ParseMatrixToURL parses a matrix.to URL into the same container as ParseMatrixURI parses matrix: URIs. |
| 237 |
func ParseMatrixToURL(uri string) (*MatrixURI, error) { |
| 238 |
parsed, err := url.Parse(uri) |
| 239 |
if err != nil { |
| 240 |
return nil, fmt.Errorf("failed to parse URL: %w", err) |
| 241 |
} |
| 242 |
return ProcessMatrixToURL(parsed) |
| 243 |
} |
| 244 |
|
| 245 |
// ProcessMatrixToURL is the equivalent of ProcessMatrixURI for matrix.to URLs. |
| 246 |
func ProcessMatrixToURL(uri *url.URL) (*MatrixURI, error) { |
| 247 |
if !strings.HasSuffix(uri.Hostname(), "matrix.to") { |
| 248 |
return nil, ErrNotMatrixTo |
| 249 |
} |
| 250 |
|
| 251 |
initialSplit := strings.SplitN(uri.Fragment, "?", 2) |
| 252 |
parts := strings.Split(initialSplit[0], "/") |
| 253 |
if len(initialSplit) > 1 { |
| 254 |
uri.RawQuery = initialSplit[1] |
| 255 |
} |
| 256 |
|
| 257 |
if len(parts) < 2 || len(parts) > 3 { |
| 258 |
return nil, ErrInvalidMatrixToPartCount |
| 259 |
} |
| 260 |
|
| 261 |
if len(parts[1]) == 0 { |
| 262 |
return nil, ErrEmptyMatrixToPrimaryIdentifier |
| 263 |
} |
| 264 |
|
| 265 |
var parsed MatrixURI |
| 266 |
|
| 267 |
parsed.Sigil1 = rune(parts[1][0]) |
| 268 |
parsed.MXID1 = parts[1][1:] |
| 269 |
_, isKnown := SigilToPathSegment[parsed.Sigil1] |
| 270 |
if !isKnown { |
| 271 |
return nil, ErrInvalidMatrixToPrimaryIdentifier |
| 272 |
} |
| 273 |
|
| 274 |
if len(parts) == 3 && len(parts[2]) > 0 { |
| 275 |
parsed.Sigil2 = rune(parts[2][0]) |
| 276 |
parsed.MXID2 = parts[2][1:] |
| 277 |
_, isKnown = SigilToPathSegment[parsed.Sigil2] |
| 278 |
if !isKnown { |
| 279 |
return nil, ErrInvalidMatrixToSecondaryIdentifier |
| 280 |
} |
| 281 |
} |
| 282 |
|
| 283 |
via, ok := uri.Query()["via"] |
| 284 |
if ok && len(via) > 0 { |
| 285 |
parsed.Via = via |
| 286 |
} |
| 287 |
action, ok := uri.Query()["action"] |
| 288 |
if ok && len(action) > 0 { |
| 289 |
parsed.Action = action[len(action)-1] |
| 290 |
} |
| 291 |
|
| 292 |
return &parsed, nil |
| 293 |
} |