Created
October 12, 2024 01:09
-
-
Save PurpShell/23a12bd905348407032c781b0a419d05 to your computer and use it in GitHub Desktop.
a command that (partially works and) downloads mxc media
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package connector | |
import ( | |
"encoding/base64" | |
"encoding/json" | |
"fmt" | |
"log" | |
"net/url" | |
"os" | |
"strings" | |
"maunium.net/go/mautrix/bridgev2/commands" | |
"maunium.net/go/mautrix/event" | |
"maunium.net/go/mautrix/id" | |
) | |
var cmdDownload = &commands.FullHandler{ | |
Func: fnDownload, | |
Name: "download", | |
Help: commands.HelpMeta{ | |
Description: "download media", | |
Args: "<_mxc-url_>", | |
}, | |
} | |
func fnDownload(ce *commands.Event) { | |
if len(ce.Args) == 0 { | |
ce.Reply("Usage: `$cmdprefix download <mxc url>`") | |
return | |
} | |
uri := ce.Args[0] | |
parsedUrl, err := url.Parse(uri) | |
if err != nil { | |
log.Printf("Failed to parse URL: %v", err) | |
return | |
} | |
queryParams := parsedUrl.Query() | |
// Get specific query parameter by key | |
fileInfoJSONB64 := queryParams.Get("encryptedFileInfoJSON") | |
if len(fileInfoJSONB64)%4 != 0 { | |
fileInfoJSONB64 += strings.Repeat("=", 4-(len(fileInfoJSONB64)%4)) | |
} | |
fileInfoJSON, err := base64.URLEncoding.DecodeString(fileInfoJSONB64) | |
if err != nil { | |
log.Printf("Failed to turn b64url to json: %v", err) | |
return | |
} | |
encryptedFile := event.EncryptedFileInfo{} | |
err = json.Unmarshal(fileInfoJSON, &encryptedFile) | |
if err != nil { | |
log.Printf("Failed to parse encrypted file info: %v", err) | |
return | |
} | |
parsedUrl.RawQuery = "" | |
err = ce.Bridge.Bot.DownloadMediaToFile(ce.Ctx, id.ContentURIString(parsedUrl.String()), &encryptedFile, true, func(file *os.File) error { | |
ce.Reply(fmt.Sprintf("Saved to %v", file.Name())) | |
return nil | |
}) | |
if err != nil { | |
log.Fatalf("Failed to parse encrypted file info: %v", err) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment