From 0ff8e968ca2aa7f2109f25249e29b07b15fee944 Mon Sep 17 00:00:00 2001
From: Philipp Heckel <pheckel@datto.com>
Date: Wed, 15 Jun 2022 20:51:42 -0400
Subject: [PATCH] Docs

---
 server/server_matrix.go | 46 +++++++++++++++++++++++++++++++----------
 1 file changed, 35 insertions(+), 11 deletions(-)

diff --git a/server/server_matrix.go b/server/server_matrix.go
index c20aff46..3bc59d35 100644
--- a/server/server_matrix.go
+++ b/server/server_matrix.go
@@ -15,16 +15,27 @@ const (
 	matrixPushKeyHeader = "X-Matrix-Pushkey"
 )
 
-type matrixMessage struct {
-	Notification *matrixNotification `json:"notification"`
-}
-
-type matrixNotification struct {
-	Devices []*matrixDevice `json:"devices"`
-}
-
-type matrixDevice struct {
-	PushKey string `json:"pushkey"`
+// matrixRequest represents a Matrix message, as it is sent to a Push Gateway (as per
+// this spec: https://spec.matrix.org/v1.2/push-gateway-api/).
+//
+// From the message, we only require the "pushkey", as it represents our target topic URL.
+// A message may look like this (excerpt):
+//    {
+//      "notification": {
+//        "devices": [
+//           {
+//              "pushkey": "https://ntfy.sh/upDAHJKFFDFD?up=1",
+//              ...
+//           }
+//        ]
+//      }
+//    }
+type matrixRequest struct {
+	Notification *struct {
+		Devices []*struct {
+			PushKey string `json:"pushkey"`
+		} `json:"devices"`
+	} `json:"notification"`
 }
 
 type matrixResponse struct {
@@ -43,6 +54,19 @@ func (e errMatrix) Error() string {
 	return fmt.Sprintf("message with push key %s rejected", e.pushKey)
 }
 
+// newRequestFromMatrixJSON reads the request body as a Matrix JSON message, parses the "pushkey", and creates a new
+// HTTP request that looks like a normal ntfy request from it.
+//
+// It basically converts a Matrix push gatewqy request:
+//
+//    POST /_matrix/push/v1/notify HTTP/1.1
+//    { "notification": { "devices": [ { "pushkey": "https://ntfy.sh/upDAHJKFFDFD?up=1", ... } ] } }
+//
+// to a ntfy request, looking like this:
+//
+//    POST /upDAHJKFFDFD?up=1 HTTP/1.1
+//    { "notification": { "devices": [ { "pushkey": "https://ntfy.sh/upDAHJKFFDFD?up=1", ... } ] } }
+//
 func newRequestFromMatrixJSON(r *http.Request, baseURL string, messageLimit int) (*http.Request, error) {
 	if baseURL == "" {
 		return nil, errHTTPInternalErrorMissingBaseURL
@@ -52,7 +76,7 @@ func newRequestFromMatrixJSON(r *http.Request, baseURL string, messageLimit int)
 		return nil, err
 	}
 	defer r.Body.Close()
-	var m matrixMessage
+	var m matrixRequest
 	if err := json.NewDecoder(body).Decode(&m); err != nil {
 		return nil, errHTTPBadRequestMatrixMessageInvalid
 	} else if m.Notification == nil || len(m.Notification.Devices) == 0 || m.Notification.Devices[0].PushKey == "" {