diff --git a/build.gradle.kts b/build.gradle.kts index 72eeb1a8f..14a553a9f 100644 --- a/build.gradle.kts +++ b/build.gradle.kts @@ -162,6 +162,7 @@ dependencies { implementation(libs.bundles.okHttp) implementation(libs.commons.lang3) implementation(libs.kotlin.coroutines) + implementation(libs.kotlin.serialization.json) implementation(libs.kotlin.stdib) implementation(libs.protobuf.java) compileOnly(libs.xz) diff --git a/javasteam-samples/src/main/java/in/dragonbra/javasteamsamples/_020_friends/SampleChatMedia.java b/javasteam-samples/src/main/java/in/dragonbra/javasteamsamples/_020_friends/SampleChatMedia.java new file mode 100644 index 000000000..d5f7b4d93 --- /dev/null +++ b/javasteam-samples/src/main/java/in/dragonbra/javasteamsamples/_020_friends/SampleChatMedia.java @@ -0,0 +1,270 @@ + package in.dragonbra.javasteamsamples._020_friends; + +import in.dragonbra.javasteam.enums.EResult; +import in.dragonbra.javasteam.steam.authentication.AuthPollResult; +import in.dragonbra.javasteam.steam.authentication.AuthSessionDetails; +import in.dragonbra.javasteam.steam.authentication.AuthenticationException; +import in.dragonbra.javasteam.steam.authentication.CredentialsAuthSession; +import in.dragonbra.javasteam.steam.authentication.SteamAuthentication; +import in.dragonbra.javasteam.steam.authentication.UserConsoleAuthenticator; +import in.dragonbra.javasteam.steam.handlers.steamcloud.ChatMediaUploadResult; +import in.dragonbra.javasteam.steam.handlers.steamcloud.SteamCloud; +import in.dragonbra.javasteam.steam.handlers.steamuser.LogOnDetails; +import in.dragonbra.javasteam.steam.handlers.steamuser.SteamUser; +import in.dragonbra.javasteam.steam.handlers.steamuser.callback.LoggedOffCallback; +import in.dragonbra.javasteam.steam.handlers.steamuser.callback.LoggedOnCallback; +import in.dragonbra.javasteam.steam.steamclient.SteamClient; +import in.dragonbra.javasteam.steam.steamclient.callbackmgr.CallbackManager; +import in.dragonbra.javasteam.steam.steamclient.callbacks.ConnectedCallback; +import in.dragonbra.javasteam.steam.steamclient.callbacks.DisconnectedCallback; +import in.dragonbra.javasteam.types.SteamID; +import in.dragonbra.javasteam.util.log.DefaultLogListener; +import in.dragonbra.javasteam.util.log.LogManager; + +import java.io.IOException; +import java.nio.file.Files; +import java.nio.file.Path; +import java.util.concurrent.CancellationException; +import java.util.concurrent.ExecutionException; + +// +// Sample 020.2: Chat media +// +// this sample logs on and sends an image or video to the chat with a friend. +// +// media doesn't go over the connection to Steam like a text message does. It is uploaded +// to the community website, and Steam then posts it to the chat for us. The website wants +// the access token of the logged-in user, so we log on with an auth session to get one. +// +// once it is sent, the sample prints where Steam stored the file, the address +// the chat message links to among it. +// +// usage: [spoiler] +// supported files are: png, jpg, gif, webm, mpg and ogv, up to 10 MiB. +// add "spoiler" to the end to hide the media in the chat until it is clicked. +// + +/** + * @author lossy + * @since 2026-11-11 + */ +@SuppressWarnings("FieldCanBeLocal") +public class SampleChatMedia implements Runnable { + + private SteamClient steamClient; + + private CallbackManager manager; + + private SteamUser steamUser; + + private SteamCloud steamCloud; + + private boolean isRunning; + + private final String user; + + private final String pass; + + private final SteamID friend; + + private final Path file; + + private final boolean spoiler; + + private String accessToken; + + public SampleChatMedia(String user, String pass, SteamID friend, Path file, boolean spoiler) { + this.user = user; + this.pass = pass; + this.friend = friend; + this.file = file; + this.spoiler = spoiler; + } + + public static void main(String[] args) { + if (args.length < 4) { + System.out.println("Sample 020: Usage: [spoiler]"); + return; + } + + SteamID friend; + try { + friend = new SteamID(Long.parseUnsignedLong(args[2])); + } catch (NumberFormatException e) { + System.out.println("Sample 020: The friend has to be a 64-bit SteamID, like 76561197960287930"); + return; + } + + Path file = Path.of(args[3]); + if (!Files.isRegularFile(file)) { + System.out.println("Sample 020: No file found at " + file.toAbsolutePath()); + return; + } + + // an optional fifth argument hides the media in the chat until it is clicked + boolean spoiler = args.length > 4 && args[4].equalsIgnoreCase("spoiler"); + + LogManager.addListener(new DefaultLogListener()); + + new SampleChatMedia(args[0], args[1], friend, file, spoiler).run(); + } + + @Override + public void run() { + // create our steamclient instance + steamClient = new SteamClient(); + + // create the callback manager which will route callbacks to function calls + manager = new CallbackManager(steamClient); + + // get the steamuser handler, which is used for logging on after successfully connecting + steamUser = steamClient.getHandler(SteamUser.class); + + // get the steamcloud handler, which is used for uploading the media + steamCloud = steamClient.getHandler(SteamCloud.class); + + // register a few callbacks we're interested in + // these are registered upon creation to a callback manager, which will then route the callbacks + // to the functions specified + manager.subscribe(ConnectedCallback.class, this::onConnected); + manager.subscribe(DisconnectedCallback.class, this::onDisconnected); + + manager.subscribe(LoggedOnCallback.class, this::onLoggedOn); + manager.subscribe(LoggedOffCallback.class, this::onLoggedOff); + + isRunning = true; + + System.out.println("Connecting to steam..."); + + // initiate the connection + steamClient.connect(); + + // create our callback handling loop + while (isRunning) { + // in order for the callbacks to get routed, they need to be handled by the manager + manager.runWaitCallbacks(1000L); + } + + } + + private void onConnected(ConnectedCallback callback) { + System.out.println("Connected to Steam! Logging in " + user + "..."); + + AuthSessionDetails authSessionDetails = new AuthSessionDetails(); + authSessionDetails.username = user; + authSessionDetails.password = pass; + authSessionDetails.persistentSession = false; + authSessionDetails.authenticator = new UserConsoleAuthenticator(); + + // get the authentication handler, which used for authenticating with Steam + SteamAuthentication auth = new SteamAuthentication(steamClient); + + try { + CredentialsAuthSession authSession = auth.beginAuthSessionViaCredentials(authSessionDetails).get(); + + AuthPollResult pollResponse = authSession.pollingWaitForResult().get(); + + LogOnDetails logOnDetails = new LogOnDetails(); + logOnDetails.setUsername(pollResponse.getAccountName()); + logOnDetails.setAccessToken(pollResponse.getRefreshToken()); + + // Set LoginID to a non-zero value if you have another client connected using the same account, + // the same private ip, and same public ip. + logOnDetails.setLoginID(149); + + steamUser.logOn(logOnDetails); + + // the access token is what signs us in to the community website, keep it for the upload. + // it expires after a day, see sample 002 for how to renew it. + accessToken = pollResponse.getAccessToken(); + } catch (Exception e) { + System.err.println(e.getMessage()); + + // List a couple of exceptions that could be important to handle. + if (e instanceof AuthenticationException) { + System.out.println("An Authentication error has occurred. " + e.getMessage()); + } + + if (e instanceof CancellationException) { + System.out.println("An Cancellation exception was raised. Usually means a timeout occurred. " + e.getMessage()); + } + + isRunning = false; + } + } + + private void onDisconnected(DisconnectedCallback callback) { + System.out.println("Disconnected from Steam"); + + isRunning = false; + } + + private void onLoggedOn(LoggedOnCallback callback) { + if (callback.getResult() != EResult.OK) { + System.out.println("Unable to login to steam: " + callback.getResult() + " / " + callback.getExtendedResult()); + + isRunning = false; + + return; + } + + System.out.println("Successfully logged on!"); + + // at this point, we'd be able to perform actions on Steam + + sendMedia(); + + // for this sample we'll just log off + // steamUser.logOff(); + } + + /** + * Uploads the file to the chat with the friend, and prints where Steam stored it. + */ + private void sendMedia() { + byte[] media; + try { + media = Files.readAllBytes(file); + } catch (IOException e) { + System.err.println("Unable to read " + file + ": " + e.getMessage()); + return; + } + + System.out.println("Sending " + file.getFileName() + " (" + media.length + " bytes) to " + friend.convertToUInt64() + "..."); + + try { + // the type of the file, and the size of an image, are worked out from the file itself. + // the upload takes a few requests, so we get a future back and wait for it here. + // to send to a group chat instead, use uploadChatMediaToChatRoom with the IDs of the group and channel. + ChatMediaUploadResult result = steamCloud.uploadChatMediaToUser( + accessToken, + friend, + media, + file.getFileName().toString(), + spoiler + ).get(); + + // nothing else to do to get it delivered, Steam has posted the media to the chat. + // the result tells where it is stored. The URL is the one the chat message links to. + // the UGC ID is unsigned, and can be used with steamCloud.requestUGCDetails to look the file up again later. + System.out.println("Sent!"); + System.out.println(" UGC ID: " + Long.toUnsignedString(result.getUgcID())); + System.out.println(" URL: " + result.getUrl()); + System.out.println(" Name: " + result.getFileName()); + System.out.println(" Size: " + result.getFileSize() + " bytes"); + System.out.println(" SHA-1: " + result.getFileSHA()); + } catch (ExecutionException e) { + // an IllegalArgumentException means the file is too large or not a supported format, + // an IOException that a request failed or that Steam turned it down, the access token being rejected for one. + System.err.println("Unable to send the media: " + e.getCause().getMessage()); + } catch (InterruptedException e) { + Thread.currentThread().interrupt(); + } + } + + private void onLoggedOff(LoggedOffCallback callback) { + System.out.println("Logged off of Steam: " + callback.getResult()); + + isRunning = false; + } +} diff --git a/src/main/java/in/dragonbra/javasteam/steam/handlers/steamcloud/ChatMediaInfo.kt b/src/main/java/in/dragonbra/javasteam/steam/handlers/steamcloud/ChatMediaInfo.kt new file mode 100644 index 000000000..c2e75ce82 --- /dev/null +++ b/src/main/java/in/dragonbra/javasteam/steam/handlers/steamcloud/ChatMediaInfo.kt @@ -0,0 +1,116 @@ +package `in`.dragonbra.javasteam.steam.handlers.steamcloud + +import `in`.dragonbra.javasteam.util.JavaSteamAddition + +/** + * The type and pixel size of an image or video, read from its header. + * Steam wants both when media is uploaded to a chat. + * + * @param mimeType The MIME type, like `image/png`. + * @param width The width in pixels, zero for a video. + * @param height The height in pixels, zero for a video. + */ +@JavaSteamAddition +internal data class ChatMediaInfo(val mimeType: String, val width: Int, val height: Int) { + + /** + * The file extension that goes with [mimeType], without a dot. + */ + val extension: String + get() = mimeType.substringAfter('/') + + companion object { + private val PNG_SIGNATURE = byteArrayOf(0x89.toByte(), 0x50, 0x4E, 0x47, 0x0D, 0x0A, 0x1A, 0x0A) + + // The EBML header that WebM files start with + private val WEBM_SIGNATURE = byteArrayOf(0x1A, 0x45, 0xDF.toByte(), 0xA3.toByte()) + + // A pack header (program stream) or a sequence header (bare video stream) + private val MPEG_SIGNATURES = listOf( + byteArrayOf(0x00, 0x00, 0x01, 0xBA.toByte()), + byteArrayOf(0x00, 0x00, 0x01, 0xB3.toByte()), + ) + + /** + * Reads the type of a PNG, JPEG or GIF image, or a WebM, MPEG or OGV video. + * The size is read for images only, Steam takes videos with a size of zero. + * + * @throws IllegalArgumentException if the data is not one of those, or its header is cut short. + */ + fun detect(data: ByteArray): ChatMediaInfo = when { + data.startsWith(PNG_SIGNATURE) -> png(data) + + data.startsWith("GIF87a") || data.startsWith("GIF89a") -> gif(data) + + data.size >= 2 && data.u8(0) == 0xFF && data.u8(1) == 0xD8 -> jpeg(data) + + data.startsWith(WEBM_SIGNATURE) -> ChatMediaInfo("video/webm", 0, 0) + + MPEG_SIGNATURES.any { data.startsWith(it) } -> ChatMediaInfo("video/mpeg", 0, 0) + + data.startsWith("OggS") -> ChatMediaInfo("video/ogv", 0, 0) + + else -> throw IllegalArgumentException( + "Unsupported media format, expected a PNG, JPEG or GIF image, or a WebM, MPEG or OGV video" + ) + } + + // The IHDR chunk always comes first, with the size as two big endian ints + private fun png(data: ByteArray): ChatMediaInfo { + require(data.size >= 24) { "Malformed PNG, the header is cut short" } + return ChatMediaInfo("image/png", data.u32be(16), data.u32be(20)) + } + + // The logical screen size follows the signature as two little endian shorts + private fun gif(data: ByteArray): ChatMediaInfo { + require(data.size >= 10) { "Malformed GIF, the header is cut short" } + return ChatMediaInfo("image/gif", data.u16le(6), data.u16le(8)) + } + + // The size is in the start of frame segment, which can sit behind any number of other segments + private fun jpeg(data: ByteArray): ChatMediaInfo { + var offset = 2 + + while (offset + 4 <= data.size) { + if (data.u8(offset) != 0xFF) { + break + } + + val marker = data.u8(offset + 1) + + when { + // Padding before a marker + marker == 0xFF -> offset++ + + // Standalone markers, they have no length + marker == 0x01 || marker in 0xD0..0xD8 -> offset += 2 + + // Start of frame. C4, C8 and CC share the range but are other things. + marker in 0xC0..0xCF && marker != 0xC4 && marker != 0xC8 && marker != 0xCC -> { + if (offset + 9 > data.size) { + break + } + return ChatMediaInfo("image/jpeg", data.u16be(offset + 7), data.u16be(offset + 5)) + } + + else -> offset += 2 + data.u16be(offset + 2) + } + } + + throw IllegalArgumentException("Malformed JPEG, no frame header found") + } + + private fun ByteArray.startsWith(prefix: ByteArray): Boolean = + size >= prefix.size && prefix.indices.all { this[it] == prefix[it] } + + private fun ByteArray.startsWith(prefix: String): Boolean = startsWith(prefix.toByteArray(Charsets.US_ASCII)) + + private fun ByteArray.u8(index: Int): Int = this[index].toInt() and 0xFF + + private fun ByteArray.u16be(index: Int): Int = (u8(index) shl 8) or u8(index + 1) + + private fun ByteArray.u16le(index: Int): Int = u8(index) or (u8(index + 1) shl 8) + + private fun ByteArray.u32be(index: Int): Int = (u16be(index) shl 16) or u16be(index + 2) + } +} diff --git a/src/main/java/in/dragonbra/javasteam/steam/handlers/steamcloud/ChatMediaUploadResult.kt b/src/main/java/in/dragonbra/javasteam/steam/handlers/steamcloud/ChatMediaUploadResult.kt new file mode 100644 index 000000000..34484c7ab --- /dev/null +++ b/src/main/java/in/dragonbra/javasteam/steam/handlers/steamcloud/ChatMediaUploadResult.kt @@ -0,0 +1,40 @@ +package `in`.dragonbra.javasteam.steam.handlers.steamcloud + +import `in`.dragonbra.javasteam.util.JavaSteamAddition + +/** + * Where Steam stored an image or video that was uploaded to a chat with + * [SteamCloud.uploadChatMediaToUser] or [SteamCloud.uploadChatMediaToChatRoom]. + */ +@JavaSteamAddition +class ChatMediaUploadResult internal constructor( + /** + * Gets the UGC ID Steam assigned to the media. It is unsigned, so large IDs read as negative. + * [SteamCloud.requestUGCDetails] looks the media up again by this ID. + */ + val ugcID: Long, + + /** + * Gets the URL the media is located at. This is the address the chat message links to. + * Empty in case Steam did not report one. + */ + val url: String, + + /** + * Gets the name of the file. + */ + val fileName: String, + + /** + * Gets the size of the file in bytes. + */ + val fileSize: Int, + + /** + * Gets the SHA-1 hash of the file, in lower case hex. + */ + val fileSHA: String, +) { + override fun toString(): String = + "ChatMediaUploadResult(ugcID=${ugcID.toULong()}, url=$url, fileName=$fileName, fileSize=$fileSize, fileSHA=$fileSHA)" +} diff --git a/src/main/java/in/dragonbra/javasteam/steam/handlers/steamcloud/ChatMediaUploader.kt b/src/main/java/in/dragonbra/javasteam/steam/handlers/steamcloud/ChatMediaUploader.kt new file mode 100644 index 000000000..b711b485c --- /dev/null +++ b/src/main/java/in/dragonbra/javasteam/steam/handlers/steamcloud/ChatMediaUploader.kt @@ -0,0 +1,222 @@ +package `in`.dragonbra.javasteam.steam.handlers.steamcloud + +import `in`.dragonbra.javasteam.util.JavaSteamAddition +import `in`.dragonbra.javasteam.util.Strings +import `in`.dragonbra.javasteam.util.Versions +import `in`.dragonbra.javasteam.util.log.LogManager +import kotlinx.serialization.json.Json +import kotlinx.serialization.json.JsonNull +import kotlinx.serialization.json.JsonObject +import kotlinx.serialization.json.JsonPrimitive +import kotlinx.serialization.json.jsonArray +import kotlinx.serialization.json.jsonObject +import okhttp3.FormBody +import okhttp3.HttpUrl +import okhttp3.HttpUrl.Companion.toHttpUrl +import okhttp3.OkHttpClient +import okhttp3.Request +import okhttp3.RequestBody.Companion.toRequestBody +import okhttp3.coroutines.executeAsync +import java.io.IOException +import java.net.URLEncoder +import java.nio.charset.StandardCharsets +import java.security.MessageDigest +import java.security.SecureRandom + +/** + * Uploads an image or video to a Steam chat through the community website, the way the web and mobile chat do. + * It takes three requests: ask where to upload, PUT the file there, then commit it to a chat. + * Steam posts the media to the chat itself once it is committed. + * + * Referenced from steam.py: https://github.com/Gobot1234/steam.py/blob/main/steam/http.py + * + * @param httpClient The client to make the requests with. + * @param communityUrl The base address of the community website. + */ +@JavaSteamAddition +internal class ChatMediaUploader( + private val httpClient: OkHttpClient, + private val communityUrl: HttpUrl = COMMUNITY_URL, +) { + + /** + * @param steamId The 64-bit SteamID of the logged-in user. + * @param accessToken The access token of the logged-in user. + * @param media The file, a PNG, JPEG or GIF image, or a WebM, MPEG or OGV video. + * @param fileName The file name, or null to make one up. + * @param spoiler Whether the media is hidden until clicked. + * @param destination The form fields that pick the chat to post to. + * @return Where Steam stored the media. + * @throws IllegalArgumentException if the media is too large or not a supported format. + * @throws IOException if a request fails, Steam turns it down, or its reply can't be understood. + */ + suspend fun upload( + steamId: Long, + accessToken: String, + media: ByteArray, + fileName: String?, + spoiler: Boolean, + destination: Map, + ): ChatMediaUploadResult { + require(media.isNotEmpty()) { "The media is empty" } + require(media.size <= MAX_SIZE) { "The media is too large to upload, the limit is 10 MiB" } + + val info = ChatMediaInfo.detect(media) + val name = fileName ?: "${System.currentTimeMillis() / 1000}_media.${info.extension}" + + // The website only checks that the sessionid cookie and form field match, so any value will do + val sessionId = Strings.toHex(ByteArray(16).also(SecureRandom()::nextBytes)).lowercase() + val loginSecure = URLEncoder.encode("${steamId.toULong()}||$accessToken", StandardCharsets.UTF_8) + val cookies = "steamLoginSecure=$loginSecure; sessionid=$sessionId" + + val fileFields = mapOf( + "sessionid" to sessionId, + "l" to "english", + "file_size" to media.size.toString(), + "file_name" to name, + "file_sha" to Strings.toHex(MessageDigest.getInstance("SHA-1").digest(media)).lowercase(), + "file_image_width" to info.width.toString(), + "file_image_height" to info.height.toString(), + "file_type" to info.mimeType, + ) + + // Ask where to upload to + val target = parseBeginResponse(post("chat/beginfileupload", cookies, fileFields)) + + // Upload the file there. The headers Steam handed out authorize it, the cookies stay home. + val putRequest = Request.Builder() + .url(target.url) + .header("User-Agent", USER_AGENT) + .apply { target.headers.forEach { (name, value) -> header(name, value) } } + .put(media.toRequestBody()) + .build() + + logger.debug("Uploading ${media.size} bytes to ${putRequest.url.host}") + + httpClient.newCall(putRequest).executeAsync().use { response -> + logger.debug("Upload answered HTTP ${response.code}") + + if (!response.isSuccessful) { + throw IOException("Uploading the media failed: HTTP ${response.code}") + } + } + + // Commit it, which posts it to the chat + val commitFields = fileFields + mapOf( + "success" to "1", + "ugcid" to target.ugcId, + "timestamp" to target.timestamp, + "hmac" to target.hmac, + "spoiler" to if (spoiler) "1" else "0", + ) + destination + + val commit = parseObject("commitfileupload", post("chat/commitfileupload", cookies, commitFields)) + + // The reply repeats what was stored and adds the address it ended up at. + // Its own ugcid is null, so the one from the first request is the one to keep. + val details = (commit["result"] as? JsonObject)?.get("details") as? JsonObject + + return ChatMediaUploadResult( + ugcID = target.ugcId.toULongOrNull()?.toLong() + ?: throw IOException("beginfileupload returned an invalid ugcid: ${target.ugcId}"), + url = details?.stringOrNull("url").orEmpty(), + fileName = details?.stringOrNull("filename") ?: name, + fileSize = media.size, + fileSHA = fileFields.getValue("file_sha"), + ) + } + + private suspend fun post(path: String, cookies: String, fields: Map): String { + val body = FormBody.Builder() + .apply { fields.forEach { (name, value) -> add(name, value) } } + .build() + + val request = Request.Builder() + .url(communityUrl.newBuilder().addPathSegments(path).build()) + .header("User-Agent", USER_AGENT) + .header("Cookie", cookies) + .post(body) + .build() + + return httpClient.newCall(request).executeAsync().use { response -> + logger.debug("$path answered HTTP ${response.code}") + + if (!response.isSuccessful) { + throw IOException("${path.substringAfterLast('/')} failed: HTTP ${response.code}") + } + + response.body.string() + } + } + + private class UploadTarget( + val url: String, + val headers: List>, + val ugcId: String, + val timestamp: String, + val hmac: String, + ) + + private fun parseBeginResponse(json: String): UploadTarget { + val root = parseObject("beginfileupload", json) + + try { + val result = root["result"]?.jsonObject + ?: throw IOException("beginfileupload returned no upload target, is the access token valid?") + + val scheme = if (result.string("use_https") in TRUTHY) "https" else "http" + + val headers = result["request_headers"]?.jsonArray.orEmpty().map { header -> + header.jsonObject.string("name") to header.jsonObject.string("value") + } + + return UploadTarget( + url = "$scheme://${result.string("url_host")}${result.string("url_path")}", + headers = headers, + ugcId = result.string("ugcid"), + timestamp = result.string("timestamp"), + hmac = root.string("hmac"), + ) + } catch (e: IllegalArgumentException) { + throw IOException("beginfileupload returned an unexpected response", e) + } + } + + /** + * Parses a reply of the website, which has to be a JSON object that doesn't report a failure. + */ + private fun parseObject(name: String, json: String): JsonObject { + val root = try { + Json.parseToJsonElement(json).jsonObject + } catch (e: IllegalArgumentException) { + // Not JSON. A login page comes back when the token is rejected. + throw IOException("$name returned an unexpected response, is the access token valid?", e) + } + + // 1 when all is well, anything else is the reason it isn't + val success = root.stringOrNull("success") + if (success != null && success !in TRUTHY) { + throw IOException("$name was turned down by Steam: success=$success") + } + + return root + } + + private fun JsonObject.stringOrNull(key: String): String? = + (this[key] as? JsonPrimitive)?.takeUnless { it is JsonNull }?.content + + private fun JsonObject.string(key: String): String = stringOrNull(key) + ?: throw IOException("beginfileupload response is missing '$key'") + + companion object { + private val logger = LogManager.getLogger(ChatMediaUploader::class.java) + + val COMMUNITY_URL: HttpUrl = "https://steamcommunity.com/".toHttpUrl() + + const val MAX_SIZE: Int = 10 * 1024 * 1024 + + private val USER_AGENT = "JavaSteam-${Versions.getVersion()}" + + private val TRUTHY = setOf("true", "1") + } +} diff --git a/src/main/java/in/dragonbra/javasteam/steam/handlers/steamcloud/SteamCloud.kt b/src/main/java/in/dragonbra/javasteam/steam/handlers/steamcloud/SteamCloud.kt index 6d5f3b68e..6d8e59b9f 100644 --- a/src/main/java/in/dragonbra/javasteam/steam/handlers/steamcloud/SteamCloud.kt +++ b/src/main/java/in/dragonbra/javasteam/steam/handlers/steamcloud/SteamCloud.kt @@ -12,17 +12,21 @@ import `in`.dragonbra.javasteam.protobufs.steamclient.SteammessagesClientmetrics import `in`.dragonbra.javasteam.protobufs.steamclient.SteammessagesCloudSteamclient.* import `in`.dragonbra.javasteam.rpc.service.ClientMetrics import `in`.dragonbra.javasteam.rpc.service.Cloud +import `in`.dragonbra.javasteam.steam.authentication.AuthPollResult import `in`.dragonbra.javasteam.steam.authentication.AuthSession +import `in`.dragonbra.javasteam.steam.authentication.SteamAuthentication import `in`.dragonbra.javasteam.steam.handlers.ClientMsgHandler import `in`.dragonbra.javasteam.steam.handlers.steamcloud.callback.ShareFileCallback import `in`.dragonbra.javasteam.steam.handlers.steamcloud.callback.SingleFileInfoCallback import `in`.dragonbra.javasteam.steam.handlers.steamcloud.callback.UGCDetailsCallback import `in`.dragonbra.javasteam.steam.handlers.steamunifiedmessages.SteamUnifiedMessages +import `in`.dragonbra.javasteam.types.SteamID import `in`.dragonbra.javasteam.types.UGCHandle import `in`.dragonbra.javasteam.util.HardwareUtils import `in`.dragonbra.javasteam.util.JavaSteamAddition import kotlinx.coroutines.* import kotlinx.coroutines.future.* +import java.io.IOException import java.util.* import java.util.concurrent.* @@ -540,6 +544,149 @@ class SteamCloud : ClientMsgHandler() { cloudService.externalStorageTransferReport(request.build()) } + /** + * Uploads an image or video to the chat with a friend. Steam posts it to the chat once it is uploaded. + * + * This goes through the community website and not the CM connection, + * so it needs the access token of the logged-in user. + * + * @param accessToken The access token, from [AuthPollResult.accessToken] or + * [SteamAuthentication.generateAccessTokenForApp]. + * @param friendSteamId The friend to send the media to. + * @param media The file, of at most 10 MiB: a PNG, JPEG or GIF image, or a WebM, MPEG or OGV video. + * Its type is read from its header. + * @param fileName The file name, or null to make one up. + * @param spoiler Whether the media is hidden until clicked. + * @return Where Steam stored the media, with the URL it can be reached at. + */ + @JavaSteamAddition + @JvmOverloads + fun uploadChatMediaToUser( + accessToken: String, + friendSteamId: SteamID, + media: ByteArray, + fileName: String? = null, + spoiler: Boolean = false, + parentScope: CoroutineScope = client.defaultScope, + ): CompletableFuture = parentScope.future { + uploadChatMediaToUser(accessToken, friendSteamId, media, fileName, spoiler) + } + + /** + * Uploads an image or video to the chat with a friend. Steam posts it to the chat once it is uploaded. + * + * This goes through the community website and not the CM connection, + * so it needs the access token of the logged-in user. + * + * @param accessToken The access token, from [AuthPollResult.accessToken] or [SteamAuthentication.generateAccessTokenForApp]. + * @param friendSteamId The friend to send the media to. + * @param media The file, of at most 10 MiB: a PNG, JPEG or GIF image, or a WebM, MPEG or OGV video. + * Its type is read from its header. + * @param fileName The file name, or null to make one up. + * @param spoiler Whether the media is hidden until clicked. + * @return Where Steam stored the media, with the URL it can be reached at. + * @throws IllegalArgumentException if the media is too large or not a supported format. + * @throws IOException if a request fails or Steam turns it down, for one when the access token is rejected. + */ + @JavaSteamAddition + suspend fun uploadChatMediaToUser( + accessToken: String, + friendSteamId: SteamID, + media: ByteArray, + fileName: String? = null, + spoiler: Boolean = false, + ): ChatMediaUploadResult = uploadChatMedia( + accessToken = accessToken, + media = media, + fileName = fileName, + spoiler = spoiler, + destination = mapOf("friend_steamid" to friendSteamId.convertToUInt64().toULong().toString()), + ) + + /** + * Uploads an image or video to a channel of a chat room group. Steam posts it to the channel once it is uploaded. + * + * This goes through the community website and not the CM connection, + * so it needs the access token of the logged-in user. + * + * @param accessToken The access token, from [AuthPollResult.accessToken] or [SteamAuthentication.generateAccessTokenForApp]. + * @param chatGroupId The ID of the chat room group. + * @param chatId The ID of the channel within the group. + * @param media The file, of at most 10 MiB: a PNG, JPEG or GIF image, or a WebM, MPEG or OGV video. + * Its type is read from its header. + * @param fileName The file name, or null to make one up. + * @param spoiler Whether the media is hidden until clicked. + * @return Where Steam stored the media, with the URL it can be reached at. + */ + @JavaSteamAddition + @JvmOverloads + fun uploadChatMediaToChatRoom( + accessToken: String, + chatGroupId: Long, + chatId: Long, + media: ByteArray, + fileName: String? = null, + spoiler: Boolean = false, + parentScope: CoroutineScope = client.defaultScope, + ): CompletableFuture = parentScope.future { + uploadChatMediaToChatRoom(accessToken, chatGroupId, chatId, media, fileName, spoiler) + } + + /** + * Uploads an image or video to a channel of a chat room group. Steam posts it to the channel once it is uploaded. + * + * This goes through the community website and not the CM connection, + * so it needs the access token of the logged-in user. + * + * @param accessToken The access token, from [AuthPollResult.accessToken] or [SteamAuthentication.generateAccessTokenForApp]. + * @param chatGroupId The ID of the chat room group. + * @param chatId The ID of the channel within the group. + * @param media The file, of at most 10 MiB: a PNG, JPEG or GIF image, or a WebM, MPEG or OGV video. + * Its type is read from its header. + * @param fileName The file name, or null to make one up. + * @param spoiler Whether the media is hidden until clicked. + * @return Where Steam stored the media, with the URL it can be reached at. + * @throws IllegalArgumentException if the media is too large or not a supported format. + * @throws IOException if a request fails or Steam turns it down, for one when the access token is rejected. + */ + @JavaSteamAddition + suspend fun uploadChatMediaToChatRoom( + accessToken: String, + chatGroupId: Long, + chatId: Long, + media: ByteArray, + fileName: String? = null, + spoiler: Boolean = false, + ): ChatMediaUploadResult = uploadChatMedia( + accessToken = accessToken, + media = media, + fileName = fileName, + spoiler = spoiler, + destination = mapOf( + "chat_group_id" to chatGroupId.toULong().toString(), + "chat_id" to chatId.toULong().toString(), + ), + ) + + private suspend fun uploadChatMedia( + accessToken: String, + media: ByteArray, + fileName: String?, + spoiler: Boolean, + destination: Map, + ): ChatMediaUploadResult { + val steamId = requireNotNull(client.steamID) { "No SteamID, the client is not logged on" } + + return ChatMediaUploader(client.configuration.httpClient).upload( + steamId = steamId.convertToUInt64(), + accessToken = accessToken, + media = media, + fileName = fileName, + spoiler = spoiler, + destination = destination, + ) + } + /** * Handles a client message. This should not be called directly. * @param packetMsg The packet message that contains the data. diff --git a/src/test/java/in/dragonbra/javasteam/steam/handlers/steamcloud/ChatMediaInfoTest.kt b/src/test/java/in/dragonbra/javasteam/steam/handlers/steamcloud/ChatMediaInfoTest.kt new file mode 100644 index 000000000..1ab11c9ec --- /dev/null +++ b/src/test/java/in/dragonbra/javasteam/steam/handlers/steamcloud/ChatMediaInfoTest.kt @@ -0,0 +1,139 @@ +package `in`.dragonbra.javasteam.steam.handlers.steamcloud + +import org.junit.jupiter.api.Assertions +import org.junit.jupiter.api.Test +import java.io.ByteArrayOutputStream +import java.io.DataOutputStream + +class ChatMediaInfoTest { + + @Test + fun readsPng() { + Assertions.assertEquals(ChatMediaInfo("image/png", 640, 480), ChatMediaInfo.detect(png(640, 480))) + } + + @Test + fun readsGif() { + Assertions.assertEquals(ChatMediaInfo("image/gif", 500, 281), ChatMediaInfo.detect(gif(500, 281))) + Assertions.assertEquals("image/gif", ChatMediaInfo.detect(gif(1, 1, version = "GIF87a")).mimeType) + } + + @Test + fun readsJpeg() { + Assertions.assertEquals(ChatMediaInfo("image/jpeg", 1920, 1080), ChatMediaInfo.detect(jpeg(1920, 1080))) + } + + @Test + fun readsProgressiveJpegBehindOtherSegments() { + // The frame header is not the first segment, and C4 before it is a huffman table and not a frame + val data = jpeg(800, 600, frameMarker = 0xC2, segmentsBefore = listOf(0xE1 to 40, 0xDB to 67, 0xC4 to 30)) + + Assertions.assertEquals(ChatMediaInfo("image/jpeg", 800, 600), ChatMediaInfo.detect(data)) + } + + @Test + fun readsVideosWithoutASize() { + val webm = byteArrayOf(0x1A, 0x45, 0xDF.toByte(), 0xA3.toByte(), 0x01, 0x00, 0x00, 0x00) + val mpegProgramStream = byteArrayOf(0x00, 0x00, 0x01, 0xBA.toByte(), 0x44, 0x00, 0x04, 0x00) + val mpegVideoStream = byteArrayOf(0x00, 0x00, 0x01, 0xB3.toByte(), 0x14, 0x00, 0xF0.toByte(), 0x13) + val ogv = "OggS".toByteArray() + ByteArray(23) + + Assertions.assertEquals(ChatMediaInfo("video/webm", 0, 0), ChatMediaInfo.detect(webm)) + Assertions.assertEquals(ChatMediaInfo("video/mpeg", 0, 0), ChatMediaInfo.detect(mpegProgramStream)) + Assertions.assertEquals(ChatMediaInfo("video/mpeg", 0, 0), ChatMediaInfo.detect(mpegVideoStream)) + Assertions.assertEquals(ChatMediaInfo("video/ogv", 0, 0), ChatMediaInfo.detect(ogv)) + } + + @Test + fun namesTheExtensionAfterTheType() { + Assertions.assertEquals("png", ChatMediaInfo.detect(png(1, 1)).extension) + Assertions.assertEquals("jpeg", ChatMediaInfo.detect(jpeg(1, 1)).extension) + Assertions.assertEquals("ogv", ChatMediaInfo.detect("OggS".toByteArray()).extension) + } + + @Test + fun rejectsOtherFormats() { + val mp4 = byteArrayOf(0x00, 0x00, 0x00, 0x18) + "ftypmp42".toByteArray() + + Assertions.assertThrows(IllegalArgumentException::class.java) { ChatMediaInfo.detect(ByteArray(0)) } + Assertions.assertThrows(IllegalArgumentException::class.java) { ChatMediaInfo.detect("RIFF....WEBPVP8 ".toByteArray()) } + Assertions.assertThrows(IllegalArgumentException::class.java) { ChatMediaInfo.detect("BM plus some bitmap".toByteArray()) } + Assertions.assertThrows(IllegalArgumentException::class.java) { ChatMediaInfo.detect(mp4) } + } + + @Test + fun rejectsHeadersCutShort() { + Assertions.assertThrows(IllegalArgumentException::class.java) { ChatMediaInfo.detect(png(640, 480).copyOf(20)) } + Assertions.assertThrows(IllegalArgumentException::class.java) { ChatMediaInfo.detect(gif(32, 16).copyOf(8)) } + Assertions.assertThrows(IllegalArgumentException::class.java) { + ChatMediaInfo.detect( + jpeg( + 640, + 480 + ).copyOf(24) + ) + } + + // A JPEG that never gets to a frame header + Assertions.assertThrows(IllegalArgumentException::class.java) { + ChatMediaInfo.detect(byteArrayOf(0xFF.toByte(), 0xD8.toByte(), 0xFF.toByte(), 0xD9.toByte())) + } + } + + companion object { + /** + * The signature and IHDR chunk of a PNG. + */ + fun png(width: Int, height: Int): ByteArray = build { + write(byteArrayOf(0x89.toByte(), 0x50, 0x4E, 0x47, 0x0D, 0x0A, 0x1A, 0x0A)) + writeInt(13) + writeBytes("IHDR") + writeInt(width) + writeInt(height) + write(byteArrayOf(8, 6, 0, 0, 0)) + } + + /** + * The header and logical screen descriptor of a GIF. + */ + fun gif(width: Int, height: Int, version: String = "GIF89a"): ByteArray = build { + writeBytes(version) + writeShort(Integer.reverseBytes(width) ushr 16) + writeShort(Integer.reverseBytes(height) ushr 16) + write(byteArrayOf(0, 0, 0)) + } + + /** + * A JPEG up to and including its frame header. + * + * @param segmentsBefore Marker and payload size of segments to put ahead of the frame header. + */ + fun jpeg( + width: Int, + height: Int, + frameMarker: Int = 0xC0, + segmentsBefore: List> = listOf(0xE0 to 14), + ): ByteArray = build { + writeShort(0xFFD8) + + segmentsBefore.forEach { (marker, payloadSize) -> + writeShort(0xFF00 or marker) + writeShort(payloadSize + 2) + write(ByteArray(payloadSize)) + } + + writeShort(0xFF00 or frameMarker) + writeShort(17) + writeByte(8) + writeShort(height) + writeShort(width) + write(ByteArray(10)) + } + + private fun build(block: DataOutputStream.() -> Unit): ByteArray { + val bytes = ByteArrayOutputStream() + DataOutputStream(bytes).use(block) + return bytes.toByteArray() + } + } +} diff --git a/src/test/java/in/dragonbra/javasteam/steam/handlers/steamcloud/ChatMediaUploaderTest.kt b/src/test/java/in/dragonbra/javasteam/steam/handlers/steamcloud/ChatMediaUploaderTest.kt new file mode 100644 index 000000000..1f1dffc40 --- /dev/null +++ b/src/test/java/in/dragonbra/javasteam/steam/handlers/steamcloud/ChatMediaUploaderTest.kt @@ -0,0 +1,330 @@ +package `in`.dragonbra.javasteam.steam.handlers.steamcloud + +import kotlinx.coroutines.runBlocking +import mockwebserver3.MockResponse +import mockwebserver3.MockWebServer +import mockwebserver3.RecordedRequest +import okhttp3.OkHttpClient +import org.junit.jupiter.api.AfterEach +import org.junit.jupiter.api.Assertions.assertArrayEquals +import org.junit.jupiter.api.Assertions.assertEquals +import org.junit.jupiter.api.Assertions.assertNull +import org.junit.jupiter.api.Assertions.assertThrows +import org.junit.jupiter.api.Assertions.assertTrue +import org.junit.jupiter.api.BeforeEach +import org.junit.jupiter.api.Test +import java.io.IOException +import java.net.URLDecoder +import java.nio.charset.StandardCharsets +import java.security.MessageDigest + +class ChatMediaUploaderTest { + + private lateinit var server: MockWebServer + + private lateinit var uploader: ChatMediaUploader + + @BeforeEach + fun setUp() { + server = MockWebServer() + server.start() + + uploader = ChatMediaUploader(OkHttpClient(), server.url("/")) + } + + @AfterEach + fun tearDown() { + server.close() + } + + @Test + fun uploadsToAFriendInThreeRequests() { + enqueueUpload(fileName = "cat.png") + + upload(media = PNG, fileName = "cat.png", spoiler = true) + + assertEquals(3, server.requestCount) + + // Ask where to upload to + val begin = server.takeRequest() + val beginFields = begin.formFields() + assertEquals("POST", begin.method) + assertEquals("/chat/beginfileupload", begin.url.encodedPath) + assertEquals("english", beginFields["l"]) + assertEquals("cat.png", beginFields["file_name"]) + assertEquals(PNG.size.toString(), beginFields["file_size"]) + assertEquals(sha1(PNG), beginFields["file_sha"]) + assertEquals("image/png", beginFields["file_type"]) + assertEquals("735", beginFields["file_image_width"]) + assertEquals("561", beginFields["file_image_height"]) + + // The login cookie is the SteamID and token, url encoded. The session cookie matches the form field. + val cookies = begin.cookies() + assertEquals("$STEAM_ID%7C%7C$ACCESS_TOKEN", cookies["steamLoginSecure"]) + assertEquals(beginFields["sessionid"], cookies["sessionid"]) + assertTrue(cookies["sessionid"]!!.matches(Regex("[0-9a-f]{32}"))) + + // Upload the file, with the headers Steam handed out and without our cookies + val put = server.takeRequest() + assertEquals("PUT", put.method) + assertEquals(UPLOAD_PATH, put.url.encodedPath) + assertEquals("image/png", put.headers["Content-Type"]) + assertEquals(PNG.size.toString(), put.headers["Content-Length"]) + assertEquals("inline; filename*=UTF-8''cat.png;", put.headers["Content-Disposition"]) + assertEquals("inline; filename*=UTF-8''cat.png;", put.headers["x-ms-blob-content-disposition"]) + assertEquals("SharedKey steamugctest:c2lnbmF0dXJl", put.headers["Authorization"]) + assertEquals("Wed, 11 Nov 2026 22:27:30 GMT", put.headers["x-ms-date"]) + assertEquals("2017-04-17", put.headers["x-ms-version"]) + assertEquals("BlockBlob", put.headers["x-ms-blob-type"]) + assertNull(put.headers["Cookie"]) + assertArrayEquals(PNG, put.body!!.toByteArray()) + + // Commit it to the chat + val commit = server.takeRequest() + val commitFields = commit.formFields() + assertEquals("POST", commit.method) + assertEquals("/chat/commitfileupload", commit.url.encodedPath) + assertEquals(cookies, commit.cookies()) + assertEquals("1", commitFields["success"]) + assertEquals(UGC_ID, commitFields["ugcid"]) + assertEquals(TIMESTAMP, commitFields["timestamp"]) + assertEquals(HMAC, commitFields["hmac"]) + assertEquals("1", commitFields["spoiler"]) + assertEquals(FRIEND, commitFields["friend_steamid"]) + + // Everything from the first request is sent again + beginFields.forEach { (name, value) -> assertEquals(value, commitFields[name], name) } + } + + @Test + fun returnsWhereSteamStoredTheMedia() { + enqueueUpload(fileName = "cat.png") + + val result = upload(media = PNG, fileName = "cat.png") + + // The ID is over the signed maximum, so it reads as negative + assertEquals(UGC_ID, result.ugcID.toULong().toString()) + assertEquals("https://images.steamusercontent.com/ugc/$UGC_ID/${sha1(PNG).uppercase()}/", result.url) + assertEquals("cat.png", result.fileName) + assertEquals(PNG.size, result.fileSize) + assertEquals(sha1(PNG), result.fileSHA) + } + + @Test + fun returnsWhatItKnowsWhenTheCommitReplyHasNoDetails() { + server.enqueue(beginResponse(fileName = "cat.png")) + server.enqueue(MockResponse.Builder().code(201).build()) + server.enqueue(MockResponse.Builder().body("""{"success":1}""").build()) + + val result = upload(media = PNG, fileName = "cat.png") + + assertEquals(UGC_ID, result.ugcID.toULong().toString()) + assertEquals("", result.url) + assertEquals("cat.png", result.fileName) + assertEquals(PNG.size, result.fileSize) + } + + @Test + fun makesUpAFileNameFromTheType() { + enqueueUpload() + + upload(media = GIF, fileName = null) + + val fields = server.takeRequest().formFields() + assertTrue(fields["file_name"]!!.matches(Regex("\\d+_media\\.gif")), fields["file_name"]) + assertEquals("image/gif", fields["file_type"]) + + // Skip the upload itself, then check the commit + server.takeRequest() + assertEquals("0", server.takeRequest().formFields()["spoiler"]) + } + + @Test + fun uploadsAVideoWithoutASize() { + enqueueUpload() + + upload(media = byteArrayOf(0x1A, 0x45, 0xDF.toByte(), 0xA3.toByte(), 0x01, 0x02, 0x03, 0x04)) + + val fields = server.takeRequest().formFields() + assertEquals("video/webm", fields["file_type"]) + assertEquals("0", fields["file_image_width"]) + assertEquals("0", fields["file_image_height"]) + assertTrue(fields["file_name"]!!.endsWith("_media.webm"), fields["file_name"]) + } + + @Test + fun rejectsUnsupportedMedia() { + assertThrows(IllegalArgumentException::class.java) { upload(media = "not an image".toByteArray()) } + assertThrows(IllegalArgumentException::class.java) { upload(media = ByteArray(0)) } + + assertEquals(0, server.requestCount) + } + + @Test + fun rejectsMediaOverTheSizeLimit() { + val tooLarge = PNG.copyOf(ChatMediaUploader.MAX_SIZE + 1) + + assertThrows(IllegalArgumentException::class.java) { upload(media = tooLarge) } + + assertEquals(0, server.requestCount) + } + + @Test + fun failsWhenTheTokenIsRejected() { + server.enqueue(MockResponse.Builder().code(401).build()) + + assertThrows(IOException::class.java) { upload() } + + assertEquals(1, server.requestCount) + } + + @Test + fun failsWhenSteamAnswersWithALoginPage() { + server.enqueue(MockResponse.Builder().body("Sign In").build()) + + assertThrows(IOException::class.java) { upload() } + + assertEquals(1, server.requestCount) + } + + // What a turned down request looks like is a guess, only successful replies have been seen + @Test + fun failsWhenSteamTurnsDownTheBegin() { + server.enqueue(MockResponse.Builder().body("""{"success":15}""").build()) + + val e = assertThrows(IOException::class.java) { upload() } + + assertTrue(e.message!!.contains("success=15"), e.message) + assertEquals(1, server.requestCount) + } + + @Test + fun failsWhenTheReplyHasNoUploadTarget() { + server.enqueue(MockResponse.Builder().body("""{"success":1}""").build()) + + assertThrows(IOException::class.java) { upload() } + + assertEquals(1, server.requestCount) + } + + @Test + fun doesNotCommitWhenTheUploadFails() { + server.enqueue(beginResponse()) + server.enqueue(MockResponse.Builder().code(500).build()) + + assertThrows(IOException::class.java) { upload() } + + assertEquals(2, server.requestCount) + } + + @Test + fun failsWhenTheCommitFails() { + server.enqueue(beginResponse()) + server.enqueue(MockResponse.Builder().code(201).build()) + server.enqueue(MockResponse.Builder().code(400).build()) + + assertThrows(IOException::class.java) { upload() } + } + + // As above, the shape of a turned down commit is a guess + @Test + fun failsWhenSteamTurnsDownTheCommit() { + server.enqueue(beginResponse()) + server.enqueue(MockResponse.Builder().code(201).build()) + server.enqueue(MockResponse.Builder().body("""{"success":2}""").build()) + + val e = assertThrows(IOException::class.java) { upload() } + + assertTrue(e.message!!.contains("success=2"), e.message) + } + + private fun upload( + media: ByteArray = PNG, + fileName: String? = null, + spoiler: Boolean = false, + ): ChatMediaUploadResult = runBlocking { + uploader.upload( + steamId = STEAM_ID, + accessToken = ACCESS_TOKEN, + media = media, + fileName = fileName, + spoiler = spoiler, + destination = mapOf("friend_steamid" to FRIEND), + ) + } + + private fun enqueueUpload(fileName: String = "cat.png") { + server.enqueue(beginResponse(fileName)) + // The storage answers a finished upload with a 201 and no body + server.enqueue(MockResponse.Builder().code(201).build()) + server.enqueue(commitResponse(fileName)) + } + + // Steam's reply, down to the escaped slashes, the bare timestamp and the success that shows up twice. + // The real one has use_https set to 1 and a storage host, here it has to point at the plain http test server. + private fun beginResponse(fileName: String = "cat.png"): MockResponse = MockResponse.Builder() + .addHeader("Content-Type", "application/json; charset=utf-8") + .body( + """{"success":1,"result":{"storage_system":1,"ugcid":"$UGC_ID","timestamp":$TIMESTAMP,""" + + """"url_host":"${server.hostName}:${server.port}",""" + + """"url_path":"${UPLOAD_PATH.replace("/", "\\/")}","use_https":0,""" + + """"request_headers":[{"name":"Content-Type","value":"image\/png"},""" + + """{"name":"Content-Length","value":"${PNG.size}"},""" + + """{"name":"Content-Disposition","value":"inline; filename*=UTF-8''$fileName;"},""" + + """{"name":"x-ms-blob-content-disposition","value":"inline; filename*=UTF-8''$fileName;"},""" + + """{"name":"Authorization","value":"SharedKey steamugctest:c2lnbmF0dXJl"},""" + + """{"name":"x-ms-date","value":"Wed, 11 Nov 2026 22:27:30 GMT"},""" + + """{"name":"x-ms-version","value":"2017-04-17"},""" + + """{"name":"x-ms-blob-type","value":"BlockBlob"}],"success":1,"rwgrsn":-2},""" + + """"hmac":"$HMAC","timestamp":$TIMESTAMP}""" + ) + .build() + + // Steam's reply. The ugcid is null in it, and the timestamp is quoted where the first reply had it bare. + private fun commitResponse(fileName: String = "cat.png"): MockResponse = MockResponse.Builder() + .addHeader("Content-Type", "application/json; charset=utf-8") + .body( + """{"success":1,"result":{"details":{"appid":744350,"ugcid":null,"filename":"$fileName",""" + + """"timestamp":"$TIMESTAMP","file_size":${PNG.size},""" + + """"url":"https:\/\/images.steamusercontent.com\/ugc\/$UGC_ID\/${sha1(PNG).uppercase()}\/",""" + + """"steamid_creator":"$STEAM_ID","flags":16,"platforms_to_sync":[],""" + + """"file_sha":"${sha1(PNG)}","compressed_file_size":${PNG.size}},""" + + """"rangecheck_host":null,"success":1,"rwgrsn":-2}}""" + ) + .build() + + private fun RecordedRequest.formFields(): Map = body!!.utf8().split('&').associate { + val (name, value) = it.split('=', limit = 2) + URLDecoder.decode(name, StandardCharsets.UTF_8) to URLDecoder.decode(value, StandardCharsets.UTF_8) + } + + private fun RecordedRequest.cookies(): Map = headers["Cookie"]!!.split("; ").associate { + val (name, value) = it.split('=', limit = 2) + name to value + } + + private fun sha1(data: ByteArray): String = + MessageDigest.getInstance("SHA-1").digest(data).joinToString("") { "%02x".format(it) } + + private companion object { + const val STEAM_ID = 76561198000000000L + + const val FRIEND = "76561198000000001" + + const val ACCESS_TOKEN = "header.payload.signature" + + // Over the signed 64-bit maximum, like the IDs Steam hands out + const val UGC_ID = "15000000000000000001" + + const val TIMESTAMP = "1794436050" + + const val HMAC = "0123456789abcdef0123456789abcdef" + + const val UPLOAD_PATH = "/cloud/AB/95/84/12/744350/372_5_0D289C3F_898ED_1.dat" + + // Just the headers, which is all that gets read + val PNG: ByteArray = ChatMediaInfoTest.png(735, 561) + + val GIF: ByteArray = ChatMediaInfoTest.gif(32, 16) + } +}