From 7c4d7f5b8506263db9f47ace471967fa0c6b6f54 Mon Sep 17 00:00:00 2001 From: LossyDragon Date: Wed, 17 Jun 2026 17:02:47 -0500 Subject: [PATCH 1/3] Try adding media upload --- build.gradle.kts | 2 + .../handlers/steamcloud/ChatMediaModels.kt | 26 +++ .../steam/handlers/steamcloud/SteamCloud.kt | 200 ++++++++++++++++++ 3 files changed, 228 insertions(+) create mode 100644 src/main/java/in/dragonbra/javasteam/steam/handlers/steamcloud/ChatMediaModels.kt diff --git a/build.gradle.kts b/build.gradle.kts index 72eeb1a8f..0d0390a7d 100644 --- a/build.gradle.kts +++ b/build.gradle.kts @@ -9,6 +9,7 @@ plugins { alias(libs.plugins.kotlin.dokka) alias(libs.plugins.kotlin.jvm) alias(libs.plugins.kotlin.kotlinter) + alias(libs.plugins.kotlin.serialization) alias(libs.plugins.maven.publish) alias(libs.plugins.protobuf.gradle) id("jacoco") @@ -162,6 +163,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/src/main/java/in/dragonbra/javasteam/steam/handlers/steamcloud/ChatMediaModels.kt b/src/main/java/in/dragonbra/javasteam/steam/handlers/steamcloud/ChatMediaModels.kt new file mode 100644 index 000000000..c4921eed2 --- /dev/null +++ b/src/main/java/in/dragonbra/javasteam/steam/handlers/steamcloud/ChatMediaModels.kt @@ -0,0 +1,26 @@ +package `in`.dragonbra.javasteam.steam.handlers.steamcloud + +import kotlinx.serialization.SerialName +import kotlinx.serialization.Serializable + +@Serializable +internal data class BeginFileUploadResponse( + val result: BeginFileUploadResult, + val hmac: String, +) + +@Serializable +internal data class BeginFileUploadResult( + @SerialName("use_https") val useHttps: Boolean, + @SerialName("url_host") val urlHost: String, + @SerialName("url_path") val urlPath: String, + @SerialName("request_headers") val requestHeaders: List, + val ugcid: String, + val timestamp: String, +) + +@Serializable +internal data class CdnRequestHeader( + val name: String, + val value: String, +) 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..1013cf48f 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,6 +12,7 @@ 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.handlers.ClientMsgHandler import `in`.dragonbra.javasteam.steam.handlers.steamcloud.callback.ShareFileCallback @@ -21,10 +22,21 @@ import `in`.dragonbra.javasteam.steam.handlers.steamunifiedmessages.SteamUnified import `in`.dragonbra.javasteam.types.UGCHandle import `in`.dragonbra.javasteam.util.HardwareUtils import `in`.dragonbra.javasteam.util.JavaSteamAddition +import `in`.dragonbra.javasteam.util.Versions import kotlinx.coroutines.* import kotlinx.coroutines.future.* +import kotlinx.serialization.json.Json +import okhttp3.FormBody +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.util.* import java.util.concurrent.* +import kotlin.random.Random /** * This handler is used for interacting with remote storage and user generated content. @@ -540,6 +552,194 @@ class SteamCloud : ClientMsgHandler() { cloudService.externalStorageTransferReport(request.build()) } + /** + * Uploads an image to a Steam friend's direct message chat. + * The upload is a three-step process: begin > CDN PUT > commit. + * The access token from [AuthPollResult.accessToken] is used to authenticate the community web requests. + * Referenced from: https://github.com/Gobot1234/steam.py/blob/main/steam/http.py + * @param accessToken The access token obtained after login. + * @param friendSteamId The 64-bit SteamID of the friend to send the image to. + * @param imageBytes The raw image bytes. + * @param fileName The file name (e.g. "image.jpg"). + * @param fileType The image type without a dot (e.g. "jpeg", "png"). + * @param imageWidth The width of the image in pixels. + * @param imageHeight The height of the image in pixels. + * @param spoiler Whether the image should be marked as a spoiler. + * @return The UGC ID assigned to the uploaded file. + */ + @JavaSteamAddition + @JvmOverloads + fun uploadChatMediaToUser( + accessToken: String, + friendSteamId: Long, + imageBytes: ByteArray, + fileName: String, + fileType: String, + imageWidth: Int, + imageHeight: Int, + spoiler: Boolean = false, + parentScope: CoroutineScope = CoroutineScope(Dispatchers.IO), + ): CompletableFuture = parentScope.future { + uploadChatMedia( + accessToken = accessToken, + imageBytes = imageBytes, + fileName = fileName, + fileType = fileType, + imageWidth = imageWidth, + imageHeight = imageHeight, + spoiler = spoiler, + destinationParams = mapOf("friend_steamid" to friendSteamId.toString()), + ) + } + + /** + * Uploads an image to a Steam chat room channel. + * The upload is a three-step process: begin > CDN PUT > commit. + * The access token from [AuthPollResult.accessToken] is used to authenticate the community web requests. + * @param accessToken The access token obtained after login. + * @param chatGroupId The chat group (lobby) ID. + * @param chatId The chat channel ID within the group. + * @param imageBytes The raw image bytes. + * @param fileName The file name (e.g. "image.jpg"). + * @param fileType The image type without a dot (e.g. "jpeg", "png"). + * @param imageWidth The width of the image in pixels. + * @param imageHeight The height of the image in pixels. + * @param spoiler Whether the image should be marked as a spoiler. + * @return The UGC ID assigned to the uploaded file. + */ + @JavaSteamAddition + @JvmOverloads + fun uploadChatMediaToChatRoom( + accessToken: String, + chatGroupId: Long, + chatId: Long, + imageBytes: ByteArray, + fileName: String, + fileType: String, + imageWidth: Int, + imageHeight: Int, + spoiler: Boolean = false, + parentScope: CoroutineScope = CoroutineScope(Dispatchers.IO), + ): CompletableFuture = parentScope.future { + uploadChatMedia( + accessToken = accessToken, + imageBytes = imageBytes, + fileName = fileName, + fileType = fileType, + imageWidth = imageWidth, + imageHeight = imageHeight, + spoiler = spoiler, + destinationParams = mapOf( + "chat_group_id" to chatGroupId.toString(), + "chat_id" to chatId.toString(), + ), + ) + } + + @JavaSteamAddition + private suspend fun uploadChatMedia( + accessToken: String, + imageBytes: ByteArray, + fileName: String, + fileType: String, + imageWidth: Int, + imageHeight: Int, + spoiler: Boolean, + destinationParams: Map, + ): Long { + val httpClient = client.configuration.httpClient + val steamId = requireNotNull(client.steamID?.convertToUInt64()) { "No SteamID. (Not logged in)" } + + val sessionId = Random.nextBytes(16) + .joinToString("") { "%02x".format(it) } + val fileSha = MessageDigest.getInstance("SHA-1") + .digest(imageBytes) + .joinToString("") { "%02x".format(it) } + + val loginSecure = URLEncoder.encode("$steamId||$accessToken", StandardCharsets.UTF_8) + val cookieHeader = "steamLoginSecure=$loginSecure; sessionid=$sessionId" + val userAgent = "JavaSteam-${Versions.getVersion()}" + + // beginfileupload - get cdn upload url and headers + val beginBody = FormBody.Builder() + .add("sessionid", sessionId) + .add("l", "english") + .add("file_size", imageBytes.size.toString()) + .add("file_name", fileName) + .add("file_sha", fileSha) + .add("file_image_width", imageWidth.toString()) + .add("file_image_height", imageHeight.toString()) + .add("file_type", fileType) + .build() + + val beginRequest = Request.Builder() + .url("https://steamcommunity.com/chat/beginfileupload") + .header("User-Agent", userAgent) + .header("Cookie", cookieHeader) + .post(beginBody) + .build() + + val beginJson = httpClient.newCall(beginRequest).executeAsync().use { response -> + if (!response.isSuccessful) { + throw IOException("beginfileupload failed: HTTP ${response.code}") + } + response.body.string() + } + + val beginResult = Json.decodeFromString(beginJson) + + // PUT the image bytes directly to the CDN + val protocol = if (beginResult.result.useHttps) "https" else "http" + val uploadUrl = "$protocol://${beginResult.result.urlHost}${beginResult.result.urlPath}" + + val putBuilder = Request.Builder() + .url(uploadUrl) + .header("User-Agent", userAgent) + .put(imageBytes.toRequestBody()) + + beginResult.result.requestHeaders.forEach { putBuilder.header(it.name, it.value) } + + httpClient.newCall(putBuilder.build()).executeAsync().use { response -> + if (!response.isSuccessful) { + throw IOException("CDN upload failed: HTTP ${response.code}") + } + } + + // commitfileupload - deliver the image to the target chat + val commitBodyBuilder = FormBody.Builder() + .add("sessionid", sessionId) + .add("l", "english") + .add("file_size", imageBytes.size.toString()) + .add("file_name", fileName) + .add("file_sha", fileSha) + .add("file_image_width", imageWidth.toString()) + .add("file_image_height", imageHeight.toString()) + .add("file_type", fileType) + .add("success", "1") + .add("ugcid", beginResult.result.ugcid) + .add("timestamp", beginResult.result.timestamp) + .add("hmac", beginResult.hmac) + .add("spoiler", if (spoiler) "1" else "0") + + destinationParams.forEach { (k, v) -> commitBodyBuilder.add(k, v) } + + val body = commitBodyBuilder.build() + val commitRequest = Request.Builder() + .url("https://steamcommunity.com/chat/commitfileupload") + .header("User-Agent", userAgent) + .header("Cookie", cookieHeader) + .post(body) + .build() + + httpClient.newCall(commitRequest).executeAsync().use { response -> + if (!response.isSuccessful) { + throw IOException("commitfileupload failed: HTTP ${response.code}") + } + } + + return beginResult.result.ugcid.toLong() + } + /** * Handles a client message. This should not be called directly. * @param packetMsg The packet message that contains the data. From 08523d07781b7616b7770d32cc8d7165bfd627a1 Mon Sep 17 00:00:00 2001 From: LossyDragon Date: Wed, 11 Nov 2026 16:24:56 -0600 Subject: [PATCH 2/3] rebase and redo media uploader branch --- build.gradle.kts | 1 - .../_020_friends/SampleChatMedia.java | 300 ++++++++++++++++++ .../handlers/steamcloud/ChatMediaInfo.kt | 113 +++++++ .../handlers/steamcloud/ChatMediaModels.kt | 26 -- .../handlers/steamcloud/ChatMediaUploader.kt | 178 +++++++++++ .../steam/handlers/steamcloud/SteamCloud.kt | 283 +++++++---------- .../handlers/steamcloud/ChatMediaInfoTest.kt | 139 ++++++++ .../steamcloud/ChatMediaUploaderTest.kt | 245 ++++++++++++++ 8 files changed, 1090 insertions(+), 195 deletions(-) create mode 100644 javasteam-samples/src/main/java/in/dragonbra/javasteamsamples/_020_friends/SampleChatMedia.java create mode 100644 src/main/java/in/dragonbra/javasteam/steam/handlers/steamcloud/ChatMediaInfo.kt delete mode 100644 src/main/java/in/dragonbra/javasteam/steam/handlers/steamcloud/ChatMediaModels.kt create mode 100644 src/main/java/in/dragonbra/javasteam/steam/handlers/steamcloud/ChatMediaUploader.kt create mode 100644 src/test/java/in/dragonbra/javasteam/steam/handlers/steamcloud/ChatMediaInfoTest.kt create mode 100644 src/test/java/in/dragonbra/javasteam/steam/handlers/steamcloud/ChatMediaUploaderTest.kt diff --git a/build.gradle.kts b/build.gradle.kts index 0d0390a7d..14a553a9f 100644 --- a/build.gradle.kts +++ b/build.gradle.kts @@ -9,7 +9,6 @@ plugins { alias(libs.plugins.kotlin.dokka) alias(libs.plugins.kotlin.jvm) alias(libs.plugins.kotlin.kotlinter) - alias(libs.plugins.kotlin.serialization) alias(libs.plugins.maven.publish) alias(libs.plugins.protobuf.gradle) id("jacoco") 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..1e6b333b9 --- /dev/null +++ b/javasteam-samples/src/main/java/in/dragonbra/javasteamsamples/_020_friends/SampleChatMedia.java @@ -0,0 +1,300 @@ + 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.SteamCloud; +import in.dragonbra.javasteam.steam.handlers.steamcloud.callback.UGCDetailsCallback; +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.types.UGCHandle; +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 asks Steam for the details of the upload and prints +// the address the file is stored at. +// +// 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 + + try { + UGCHandle ugcHandle = sendMedia(); + + if (ugcHandle != null) { + printDetails(ugcHandle); + } + } catch (InterruptedException e) { + Thread.currentThread().interrupt(); + } + + // for this sample we'll just log off + // steamUser.logOff(); + } + + /** + * Uploads the file to the chat with the friend. + * + * @return the handle of the uploaded file, or null if it could not be sent. + */ + private UGCHandle sendMedia() throws InterruptedException { + byte[] media; + try { + media = Files.readAllBytes(file); + } catch (IOException e) { + System.err.println("Unable to read " + file + ": " + e.getMessage()); + return null; + } + + 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. + long ugcId = 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 + System.out.println("Sent! Steam stored it with UGC ID " + Long.toUnsignedString(ugcId)); + + return new UGCHandle(ugcId); + } catch (ExecutionException e) { + // an IllegalArgumentException means the file is too large or not a supported format, + // an IOException that a request failed, the access token being rejected for one. + System.err.println("Unable to send the media: " + e.getCause().getMessage()); + return null; + } + } + + /** + * Asks Steam where the uploaded file ended up. + */ + private void printDetails(UGCHandle ugcHandle) throws InterruptedException { + try { + // the upload only hands back an ID. The details of what is stored behind it, the address + // it can be downloaded from among them, can be asked for over the connection to Steam. + UGCDetailsCallback details = steamCloud.requestUGCDetails(ugcHandle).get(); + + if (details.getResult() != EResult.OK) { + System.out.println("Unable to get the details of the upload: " + details.getResult()); + return; + } + + System.out.println(" URL: " + details.getUrl()); + System.out.println(" Name: " + details.getFileName()); + System.out.println(" Size: " + details.getFileSize() + " bytes"); + System.out.println(" SHA-1: " + details.getFileSHA()); + System.out.println(" Uploaded: " + details.getTimestamp()); + } catch (ExecutionException e) { + // the media was still sent, we just couldn't look it up + System.err.println("Unable to get the details of the upload: " + e.getCause().getMessage()); + } + } + + 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..efc3b19af --- /dev/null +++ b/src/main/java/in/dragonbra/javasteam/steam/handlers/steamcloud/ChatMediaInfo.kt @@ -0,0 +1,113 @@ +package `in`.dragonbra.javasteam.steam.handlers.steamcloud + +/** + * 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. + */ +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/ChatMediaModels.kt b/src/main/java/in/dragonbra/javasteam/steam/handlers/steamcloud/ChatMediaModels.kt deleted file mode 100644 index c4921eed2..000000000 --- a/src/main/java/in/dragonbra/javasteam/steam/handlers/steamcloud/ChatMediaModels.kt +++ /dev/null @@ -1,26 +0,0 @@ -package `in`.dragonbra.javasteam.steam.handlers.steamcloud - -import kotlinx.serialization.SerialName -import kotlinx.serialization.Serializable - -@Serializable -internal data class BeginFileUploadResponse( - val result: BeginFileUploadResult, - val hmac: String, -) - -@Serializable -internal data class BeginFileUploadResult( - @SerialName("use_https") val useHttps: Boolean, - @SerialName("url_host") val urlHost: String, - @SerialName("url_path") val urlPath: String, - @SerialName("request_headers") val requestHeaders: List, - val ugcid: String, - val timestamp: String, -) - -@Serializable -internal data class CdnRequestHeader( - val name: String, - val value: String, -) 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..3445050ff --- /dev/null +++ b/src/main/java/in/dragonbra/javasteam/steam/handlers/steamcloud/ChatMediaUploader.kt @@ -0,0 +1,178 @@ +package `in`.dragonbra.javasteam.steam.handlers.steamcloud + +import `in`.dragonbra.javasteam.util.Strings +import `in`.dragonbra.javasteam.util.Versions +import kotlinx.serialization.json.Json +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. + */ +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 The UGC ID Steam assigned to the media. + * @throws IllegalArgumentException if the media is too large or not a supported format. + * @throws IOException if a request fails or Steam's reply can't be understood. + */ + suspend fun upload( + steamId: Long, + accessToken: String, + media: ByteArray, + fileName: String?, + spoiler: Boolean, + destination: Map, + ): Long { + 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() + + httpClient.newCall(putRequest).executeAsync().use { response -> + 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 + + post("chat/commitfileupload", cookies, commitFields) + + return target.ugcId.toULongOrNull()?.toLong() + ?: throw IOException("beginfileupload returned an invalid ugcid: ${target.ugcId}") + } + + 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 -> + 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, + ) + + // Read field by field, Steam is loose about whether numbers and booleans are quoted + private fun parseBeginResponse(json: String): UploadTarget { + try { + val root = Json.parseToJsonElement(json).jsonObject + 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) { + // Not JSON, or not the shape expected. A login page comes back when the token is rejected. + throw IOException("beginfileupload returned an unexpected response", e) + } + } + + private fun JsonObject.string(key: String): String = (this[key] as? JsonPrimitive)?.content + ?: throw IOException("beginfileupload response is missing '$key'") + + companion object { + 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 1013cf48f..fe54b0f47 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 @@ -14,29 +14,21 @@ 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 `in`.dragonbra.javasteam.util.Versions import kotlinx.coroutines.* import kotlinx.coroutines.future.* -import kotlinx.serialization.json.Json -import okhttp3.FormBody -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.util.* import java.util.concurrent.* -import kotlin.random.Random /** * This handler is used for interacting with remote storage and user generated content. @@ -553,59 +545,78 @@ class SteamCloud : ClientMsgHandler() { } /** - * Uploads an image to a Steam friend's direct message chat. - * The upload is a three-step process: begin > CDN PUT > commit. - * The access token from [AuthPollResult.accessToken] is used to authenticate the community web requests. - * Referenced from: https://github.com/Gobot1234/steam.py/blob/main/steam/http.py - * @param accessToken The access token obtained after login. - * @param friendSteamId The 64-bit SteamID of the friend to send the image to. - * @param imageBytes The raw image bytes. - * @param fileName The file name (e.g. "image.jpg"). - * @param fileType The image type without a dot (e.g. "jpeg", "png"). - * @param imageWidth The width of the image in pixels. - * @param imageHeight The height of the image in pixels. - * @param spoiler Whether the image should be marked as a spoiler. - * @return The UGC ID assigned to the uploaded file. + * 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 The UGC ID Steam assigned to the media. */ @JavaSteamAddition @JvmOverloads fun uploadChatMediaToUser( accessToken: String, - friendSteamId: Long, - imageBytes: ByteArray, - fileName: String, - fileType: String, - imageWidth: Int, - imageHeight: Int, + friendSteamId: SteamID, + media: ByteArray, + fileName: String? = null, spoiler: Boolean = false, - parentScope: CoroutineScope = CoroutineScope(Dispatchers.IO), + parentScope: CoroutineScope = client.defaultScope, ): CompletableFuture = parentScope.future { - uploadChatMedia( - accessToken = accessToken, - imageBytes = imageBytes, - fileName = fileName, - fileType = fileType, - imageWidth = imageWidth, - imageHeight = imageHeight, - spoiler = spoiler, - destinationParams = mapOf("friend_steamid" to friendSteamId.toString()), - ) + uploadChatMediaToUser(accessToken, friendSteamId, media, fileName, spoiler) } /** - * Uploads an image to a Steam chat room channel. - * The upload is a three-step process: begin > CDN PUT > commit. - * The access token from [AuthPollResult.accessToken] is used to authenticate the community web requests. - * @param accessToken The access token obtained after login. - * @param chatGroupId The chat group (lobby) ID. - * @param chatId The chat channel ID within the group. - * @param imageBytes The raw image bytes. - * @param fileName The file name (e.g. "image.jpg"). - * @param fileType The image type without a dot (e.g. "jpeg", "png"). - * @param imageWidth The width of the image in pixels. - * @param imageHeight The height of the image in pixels. - * @param spoiler Whether the image should be marked as a spoiler. - * @return The UGC ID assigned to the uploaded file. + * 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 The UGC ID Steam assigned to the media. + * @throws IllegalArgumentException if the media is too large or not a supported format. + * @throws IOException if a request fails, for one when the access token is rejected. + */ + @JavaSteamAddition + suspend fun uploadChatMediaToUser( + accessToken: String, + friendSteamId: SteamID, + media: ByteArray, + fileName: String? = null, + spoiler: Boolean = false, + ): Long = 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 The UGC ID Steam assigned to the media. */ @JavaSteamAddition @JvmOverloads @@ -613,131 +624,67 @@ class SteamCloud : ClientMsgHandler() { accessToken: String, chatGroupId: Long, chatId: Long, - imageBytes: ByteArray, - fileName: String, - fileType: String, - imageWidth: Int, - imageHeight: Int, + media: ByteArray, + fileName: String? = null, spoiler: Boolean = false, - parentScope: CoroutineScope = CoroutineScope(Dispatchers.IO), + parentScope: CoroutineScope = client.defaultScope, ): CompletableFuture = parentScope.future { - uploadChatMedia( - accessToken = accessToken, - imageBytes = imageBytes, - fileName = fileName, - fileType = fileType, - imageWidth = imageWidth, - imageHeight = imageHeight, - spoiler = spoiler, - destinationParams = mapOf( - "chat_group_id" to chatGroupId.toString(), - "chat_id" to chatId.toString(), - ), - ) + 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 The UGC ID Steam assigned to the media. + * @throws IllegalArgumentException if the media is too large or not a supported format. + * @throws IOException if a request fails, 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, + ): Long = 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, - imageBytes: ByteArray, - fileName: String, - fileType: String, - imageWidth: Int, - imageHeight: Int, + media: ByteArray, + fileName: String?, spoiler: Boolean, - destinationParams: Map, + destination: Map, ): Long { - val httpClient = client.configuration.httpClient - val steamId = requireNotNull(client.steamID?.convertToUInt64()) { "No SteamID. (Not logged in)" } - - val sessionId = Random.nextBytes(16) - .joinToString("") { "%02x".format(it) } - val fileSha = MessageDigest.getInstance("SHA-1") - .digest(imageBytes) - .joinToString("") { "%02x".format(it) } - - val loginSecure = URLEncoder.encode("$steamId||$accessToken", StandardCharsets.UTF_8) - val cookieHeader = "steamLoginSecure=$loginSecure; sessionid=$sessionId" - val userAgent = "JavaSteam-${Versions.getVersion()}" - - // beginfileupload - get cdn upload url and headers - val beginBody = FormBody.Builder() - .add("sessionid", sessionId) - .add("l", "english") - .add("file_size", imageBytes.size.toString()) - .add("file_name", fileName) - .add("file_sha", fileSha) - .add("file_image_width", imageWidth.toString()) - .add("file_image_height", imageHeight.toString()) - .add("file_type", fileType) - .build() - - val beginRequest = Request.Builder() - .url("https://steamcommunity.com/chat/beginfileupload") - .header("User-Agent", userAgent) - .header("Cookie", cookieHeader) - .post(beginBody) - .build() - - val beginJson = httpClient.newCall(beginRequest).executeAsync().use { response -> - if (!response.isSuccessful) { - throw IOException("beginfileupload failed: HTTP ${response.code}") - } - response.body.string() - } - - val beginResult = Json.decodeFromString(beginJson) - - // PUT the image bytes directly to the CDN - val protocol = if (beginResult.result.useHttps) "https" else "http" - val uploadUrl = "$protocol://${beginResult.result.urlHost}${beginResult.result.urlPath}" + val steamId = requireNotNull(client.steamID) { "No SteamID, the client is not logged on" } - val putBuilder = Request.Builder() - .url(uploadUrl) - .header("User-Agent", userAgent) - .put(imageBytes.toRequestBody()) - - beginResult.result.requestHeaders.forEach { putBuilder.header(it.name, it.value) } - - httpClient.newCall(putBuilder.build()).executeAsync().use { response -> - if (!response.isSuccessful) { - throw IOException("CDN upload failed: HTTP ${response.code}") - } - } - - // commitfileupload - deliver the image to the target chat - val commitBodyBuilder = FormBody.Builder() - .add("sessionid", sessionId) - .add("l", "english") - .add("file_size", imageBytes.size.toString()) - .add("file_name", fileName) - .add("file_sha", fileSha) - .add("file_image_width", imageWidth.toString()) - .add("file_image_height", imageHeight.toString()) - .add("file_type", fileType) - .add("success", "1") - .add("ugcid", beginResult.result.ugcid) - .add("timestamp", beginResult.result.timestamp) - .add("hmac", beginResult.hmac) - .add("spoiler", if (spoiler) "1" else "0") - - destinationParams.forEach { (k, v) -> commitBodyBuilder.add(k, v) } - - val body = commitBodyBuilder.build() - val commitRequest = Request.Builder() - .url("https://steamcommunity.com/chat/commitfileupload") - .header("User-Agent", userAgent) - .header("Cookie", cookieHeader) - .post(body) - .build() - - httpClient.newCall(commitRequest).executeAsync().use { response -> - if (!response.isSuccessful) { - throw IOException("commitfileupload failed: HTTP ${response.code}") - } - } - - return beginResult.result.ugcid.toLong() + return ChatMediaUploader(client.configuration.httpClient).upload( + steamId = steamId.convertToUInt64(), + accessToken = accessToken, + media = media, + fileName = fileName, + spoiler = spoiler, + destination = destination, + ) } /** 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..704969b37 --- /dev/null +++ b/src/test/java/in/dragonbra/javasteam/steam/handlers/steamcloud/ChatMediaUploaderTest.kt @@ -0,0 +1,245 @@ +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() { + server.enqueue(beginResponse()) + server.enqueue(MockResponse.Builder().build()) + server.enqueue(MockResponse.Builder().body("{}").build()) + + val ugcId = upload(media = PNG, fileName = "cat.png", spoiler = true) + + assertEquals(UGC_ID, ugcId) + 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("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("640", beginFields["file_image_width"]) + assertEquals("480", 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("/ugcupload/abc", put.url.encodedPath) + assertEquals("yes", put.headers["x-upload-authorized"]) + 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.toString(), commitFields["ugcid"]) + assertEquals("1700000000", commitFields["timestamp"]) + assertEquals("deadbeef", commitFields["hmac"]) + assertEquals("1", commitFields["spoiler"]) + assertEquals("76561198000000001", commitFields["friend_steamid"]) + + // Everything from the first request is sent again + beginFields.forEach { (name, value) -> assertEquals(value, commitFields[name], name) } + } + + @Test + fun makesUpAFileNameFromTheType() { + server.enqueue(beginResponse()) + server.enqueue(MockResponse.Builder().build()) + server.enqueue(MockResponse.Builder().body("{}").build()) + + 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() { + server.enqueue(beginResponse()) + server.enqueue(MockResponse.Builder().build()) + server.enqueue(MockResponse.Builder().body("{}").build()) + + 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) + } + + @Test + fun failsWhenTheReplyHasNoUploadTarget() { + server.enqueue(MockResponse.Builder().body("""{"success":false}""").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().build()) + server.enqueue(MockResponse.Builder().code(400).build()) + + assertThrows(IOException::class.java) { upload() } + } + + private fun upload(media: ByteArray = PNG, fileName: String? = null, spoiler: Boolean = false): Long = runBlocking { + uploader.upload( + steamId = STEAM_ID, + accessToken = ACCESS_TOKEN, + media = media, + fileName = fileName, + spoiler = spoiler, + destination = mapOf("friend_steamid" to "76561198000000001"), + ) + } + + // Steam mixes quoted and bare values, and sends fields that aren't needed + private fun beginResponse(): MockResponse = MockResponse.Builder().body( + """ + { + "success": 1, + "result": { + "ugcid": "$UGC_ID", + "timestamp": 1700000000, + "use_https": false, + "url_host": "${server.hostName}:${server.port}", + "url_path": "/ugcupload/abc", + "request_headers": [ + { "name": "x-upload-authorized", "value": "yes" } + ] + }, + "hmac": "deadbeef" + } + """.trimIndent() + ).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 ACCESS_TOKEN = "header.payload.signature" + + const val UGC_ID = 2456789012345678901L + + // Just the headers, which is all that gets read + val PNG: ByteArray = ChatMediaInfoTest.png(640, 480) + + val GIF: ByteArray = ChatMediaInfoTest.gif(32, 16) + } +} From d1fc8c086012ff0e2f83c4287624cfb6b9dcd4e8 Mon Sep 17 00:00:00 2001 From: LossyDragon Date: Wed, 11 Nov 2026 16:44:00 -0600 Subject: [PATCH 3/3] Make sure media upload reflects closer to a response. Added ChatMediaUploadResult for result metadata --- .../_020_friends/SampleChatMedia.java | 70 ++----- .../handlers/steamcloud/ChatMediaInfo.kt | 3 + .../steamcloud/ChatMediaUploadResult.kt | 40 ++++ .../handlers/steamcloud/ChatMediaUploader.kt | 64 ++++++- .../steam/handlers/steamcloud/SteamCloud.kt | 22 +-- .../steamcloud/ChatMediaUploaderTest.kt | 173 +++++++++++++----- 6 files changed, 257 insertions(+), 115 deletions(-) create mode 100644 src/main/java/in/dragonbra/javasteam/steam/handlers/steamcloud/ChatMediaUploadResult.kt 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 index 1e6b333b9..d5f7b4d93 100644 --- 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 @@ -7,8 +7,8 @@ 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.steamcloud.callback.UGCDetailsCallback; 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; @@ -18,7 +18,6 @@ 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.types.UGCHandle; import in.dragonbra.javasteam.util.log.DefaultLogListener; import in.dragonbra.javasteam.util.log.LogManager; @@ -37,8 +36,8 @@ // 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 asks Steam for the details of the upload and prints -// the address the file is stored at. +// 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. @@ -213,32 +212,22 @@ private void onLoggedOn(LoggedOnCallback callback) { // at this point, we'd be able to perform actions on Steam - try { - UGCHandle ugcHandle = sendMedia(); - - if (ugcHandle != null) { - printDetails(ugcHandle); - } - } catch (InterruptedException e) { - Thread.currentThread().interrupt(); - } + sendMedia(); // for this sample we'll just log off // steamUser.logOff(); } /** - * Uploads the file to the chat with the friend. - * - * @return the handle of the uploaded file, or null if it could not be sent. + * Uploads the file to the chat with the friend, and prints where Steam stored it. */ - private UGCHandle sendMedia() throws InterruptedException { + private void sendMedia() { byte[] media; try { media = Files.readAllBytes(file); } catch (IOException e) { System.err.println("Unable to read " + file + ": " + e.getMessage()); - return null; + return; } System.out.println("Sending " + file.getFileName() + " (" + media.length + " bytes) to " + friend.convertToUInt64() + "..."); @@ -247,7 +236,7 @@ private UGCHandle sendMedia() throws InterruptedException { // 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. - long ugcId = steamCloud.uploadChatMediaToUser( + ChatMediaUploadResult result = steamCloud.uploadChatMediaToUser( accessToken, friend, media, @@ -255,40 +244,21 @@ private UGCHandle sendMedia() throws InterruptedException { spoiler ).get(); - // nothing else to do to get it delivered, Steam has posted the media to the chat - System.out.println("Sent! Steam stored it with UGC ID " + Long.toUnsignedString(ugcId)); - - return new UGCHandle(ugcId); + // 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, the access token being rejected for one. + // 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()); - return null; - } - } - - /** - * Asks Steam where the uploaded file ended up. - */ - private void printDetails(UGCHandle ugcHandle) throws InterruptedException { - try { - // the upload only hands back an ID. The details of what is stored behind it, the address - // it can be downloaded from among them, can be asked for over the connection to Steam. - UGCDetailsCallback details = steamCloud.requestUGCDetails(ugcHandle).get(); - - if (details.getResult() != EResult.OK) { - System.out.println("Unable to get the details of the upload: " + details.getResult()); - return; - } - - System.out.println(" URL: " + details.getUrl()); - System.out.println(" Name: " + details.getFileName()); - System.out.println(" Size: " + details.getFileSize() + " bytes"); - System.out.println(" SHA-1: " + details.getFileSHA()); - System.out.println(" Uploaded: " + details.getTimestamp()); - } catch (ExecutionException e) { - // the media was still sent, we just couldn't look it up - System.err.println("Unable to get the details of the upload: " + e.getCause().getMessage()); + } catch (InterruptedException e) { + Thread.currentThread().interrupt(); } } 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 index efc3b19af..c2e75ce82 100644 --- a/src/main/java/in/dragonbra/javasteam/steam/handlers/steamcloud/ChatMediaInfo.kt +++ b/src/main/java/in/dragonbra/javasteam/steam/handlers/steamcloud/ChatMediaInfo.kt @@ -1,5 +1,7 @@ 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. @@ -8,6 +10,7 @@ package `in`.dragonbra.javasteam.steam.handlers.steamcloud * @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) { /** 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 index 3445050ff..b711b485c 100644 --- a/src/main/java/in/dragonbra/javasteam/steam/handlers/steamcloud/ChatMediaUploader.kt +++ b/src/main/java/in/dragonbra/javasteam/steam/handlers/steamcloud/ChatMediaUploader.kt @@ -1,8 +1,11 @@ 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 @@ -30,6 +33,7 @@ import java.security.SecureRandom * @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, @@ -42,9 +46,9 @@ internal class ChatMediaUploader( * @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 The UGC ID Steam assigned to the media. + * @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 or Steam's reply can't be understood. + * @throws IOException if a request fails, Steam turns it down, or its reply can't be understood. */ suspend fun upload( steamId: Long, @@ -53,7 +57,7 @@ internal class ChatMediaUploader( fileName: String?, spoiler: Boolean, destination: Map, - ): Long { + ): 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" } @@ -87,7 +91,11 @@ internal class ChatMediaUploader( .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}") } @@ -102,10 +110,20 @@ internal class ChatMediaUploader( "spoiler" to if (spoiler) "1" else "0", ) + destination - post("chat/commitfileupload", cookies, commitFields) + 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 target.ugcId.toULongOrNull()?.toLong() - ?: throw IOException("beginfileupload returned an invalid ugcid: ${target.ugcId}") + 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 { @@ -121,6 +139,8 @@ internal class ChatMediaUploader( .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}") } @@ -137,10 +157,10 @@ internal class ChatMediaUploader( val hmac: String, ) - // Read field by field, Steam is loose about whether numbers and booleans are quoted private fun parseBeginResponse(json: String): UploadTarget { + val root = parseObject("beginfileupload", json) + try { - val root = Json.parseToJsonElement(json).jsonObject val result = root["result"]?.jsonObject ?: throw IOException("beginfileupload returned no upload target, is the access token valid?") @@ -158,15 +178,39 @@ internal class ChatMediaUploader( hmac = root.string("hmac"), ) } catch (e: IllegalArgumentException) { - // Not JSON, or not the shape expected. A login page comes back when the token is rejected. throw IOException("beginfileupload returned an unexpected response", e) } } - private fun JsonObject.string(key: String): String = (this[key] as? JsonPrimitive)?.content + /** + * 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 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 fe54b0f47..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 @@ -557,7 +557,7 @@ class SteamCloud : ClientMsgHandler() { * 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 The UGC ID Steam assigned to the media. + * @return Where Steam stored the media, with the URL it can be reached at. */ @JavaSteamAddition @JvmOverloads @@ -568,7 +568,7 @@ class SteamCloud : ClientMsgHandler() { fileName: String? = null, spoiler: Boolean = false, parentScope: CoroutineScope = client.defaultScope, - ): CompletableFuture = parentScope.future { + ): CompletableFuture = parentScope.future { uploadChatMediaToUser(accessToken, friendSteamId, media, fileName, spoiler) } @@ -584,9 +584,9 @@ class SteamCloud : ClientMsgHandler() { * 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 The UGC ID Steam assigned to the media. + * @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, for one when the access token is rejected. + * @throws IOException if a request fails or Steam turns it down, for one when the access token is rejected. */ @JavaSteamAddition suspend fun uploadChatMediaToUser( @@ -595,7 +595,7 @@ class SteamCloud : ClientMsgHandler() { media: ByteArray, fileName: String? = null, spoiler: Boolean = false, - ): Long = uploadChatMedia( + ): ChatMediaUploadResult = uploadChatMedia( accessToken = accessToken, media = media, fileName = fileName, @@ -616,7 +616,7 @@ class SteamCloud : ClientMsgHandler() { * 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 The UGC ID Steam assigned to the media. + * @return Where Steam stored the media, with the URL it can be reached at. */ @JavaSteamAddition @JvmOverloads @@ -628,7 +628,7 @@ class SteamCloud : ClientMsgHandler() { fileName: String? = null, spoiler: Boolean = false, parentScope: CoroutineScope = client.defaultScope, - ): CompletableFuture = parentScope.future { + ): CompletableFuture = parentScope.future { uploadChatMediaToChatRoom(accessToken, chatGroupId, chatId, media, fileName, spoiler) } @@ -645,9 +645,9 @@ class SteamCloud : ClientMsgHandler() { * 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 The UGC ID Steam assigned to the media. + * @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, for one when the access token is rejected. + * @throws IOException if a request fails or Steam turns it down, for one when the access token is rejected. */ @JavaSteamAddition suspend fun uploadChatMediaToChatRoom( @@ -657,7 +657,7 @@ class SteamCloud : ClientMsgHandler() { media: ByteArray, fileName: String? = null, spoiler: Boolean = false, - ): Long = uploadChatMedia( + ): ChatMediaUploadResult = uploadChatMedia( accessToken = accessToken, media = media, fileName = fileName, @@ -674,7 +674,7 @@ class SteamCloud : ClientMsgHandler() { fileName: String?, spoiler: Boolean, destination: Map, - ): Long { + ): ChatMediaUploadResult { val steamId = requireNotNull(client.steamID) { "No SteamID, the client is not logged on" } return ChatMediaUploader(client.configuration.httpClient).upload( 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 index 704969b37..1f1dffc40 100644 --- a/src/test/java/in/dragonbra/javasteam/steam/handlers/steamcloud/ChatMediaUploaderTest.kt +++ b/src/test/java/in/dragonbra/javasteam/steam/handlers/steamcloud/ChatMediaUploaderTest.kt @@ -39,13 +39,10 @@ class ChatMediaUploaderTest { @Test fun uploadsToAFriendInThreeRequests() { - server.enqueue(beginResponse()) - server.enqueue(MockResponse.Builder().build()) - server.enqueue(MockResponse.Builder().body("{}").build()) + enqueueUpload(fileName = "cat.png") - val ugcId = upload(media = PNG, fileName = "cat.png", spoiler = true) + upload(media = PNG, fileName = "cat.png", spoiler = true) - assertEquals(UGC_ID, ugcId) assertEquals(3, server.requestCount) // Ask where to upload to @@ -53,12 +50,13 @@ class ChatMediaUploaderTest { 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("640", beginFields["file_image_width"]) - assertEquals("480", beginFields["file_image_height"]) + 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() @@ -69,8 +67,15 @@ class ChatMediaUploaderTest { // Upload the file, with the headers Steam handed out and without our cookies val put = server.takeRequest() assertEquals("PUT", put.method) - assertEquals("/ugcupload/abc", put.url.encodedPath) - assertEquals("yes", put.headers["x-upload-authorized"]) + 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()) @@ -81,21 +86,47 @@ class ChatMediaUploaderTest { assertEquals("/chat/commitfileupload", commit.url.encodedPath) assertEquals(cookies, commit.cookies()) assertEquals("1", commitFields["success"]) - assertEquals(UGC_ID.toString(), commitFields["ugcid"]) - assertEquals("1700000000", commitFields["timestamp"]) - assertEquals("deadbeef", commitFields["hmac"]) + assertEquals(UGC_ID, commitFields["ugcid"]) + assertEquals(TIMESTAMP, commitFields["timestamp"]) + assertEquals(HMAC, commitFields["hmac"]) assertEquals("1", commitFields["spoiler"]) - assertEquals("76561198000000001", commitFields["friend_steamid"]) + 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() { - server.enqueue(beginResponse()) - server.enqueue(MockResponse.Builder().build()) - server.enqueue(MockResponse.Builder().body("{}").build()) + enqueueUpload() upload(media = GIF, fileName = null) @@ -110,9 +141,7 @@ class ChatMediaUploaderTest { @Test fun uploadsAVideoWithoutASize() { - server.enqueue(beginResponse()) - server.enqueue(MockResponse.Builder().build()) - server.enqueue(MockResponse.Builder().body("{}").build()) + enqueueUpload() upload(media = byteArrayOf(0x1A, 0x45, 0xDF.toByte(), 0xA3.toByte(), 0x01, 0x02, 0x03, 0x04)) @@ -158,9 +187,20 @@ class ChatMediaUploaderTest { 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":false}""").build()) + server.enqueue(MockResponse.Builder().body("""{"success":1}""").build()) assertThrows(IOException::class.java) { upload() } @@ -180,42 +220,78 @@ class ChatMediaUploaderTest { @Test fun failsWhenTheCommitFails() { server.enqueue(beginResponse()) - server.enqueue(MockResponse.Builder().build()) + server.enqueue(MockResponse.Builder().code(201).build()) server.enqueue(MockResponse.Builder().code(400).build()) assertThrows(IOException::class.java) { upload() } } - private fun upload(media: ByteArray = PNG, fileName: String? = null, spoiler: Boolean = false): Long = runBlocking { + // 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 "76561198000000001"), + destination = mapOf("friend_steamid" to FRIEND), ) } - // Steam mixes quoted and bare values, and sends fields that aren't needed - private fun beginResponse(): MockResponse = MockResponse.Builder().body( - """ - { - "success": 1, - "result": { - "ugcid": "$UGC_ID", - "timestamp": 1700000000, - "use_https": false, - "url_host": "${server.hostName}:${server.port}", - "url_path": "/ugcupload/abc", - "request_headers": [ - { "name": "x-upload-authorized", "value": "yes" } - ] - }, - "hmac": "deadbeef" - } - """.trimIndent() - ).build() + 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) @@ -233,12 +309,21 @@ class ChatMediaUploaderTest { private companion object { const val STEAM_ID = 76561198000000000L + const val FRIEND = "76561198000000001" + const val ACCESS_TOKEN = "header.payload.signature" - const val UGC_ID = 2456789012345678901L + // 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(640, 480) + val PNG: ByteArray = ChatMediaInfoTest.png(735, 561) val GIF: ByteArray = ChatMediaInfoTest.gif(32, 16) }