Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions build.gradle.kts
Original file line number Diff line number Diff line change
Expand Up @@ -162,6 +162,7 @@ dependencies {
implementation(libs.bundles.okHttp)
implementation(libs.commons.lang3)
implementation(libs.kotlin.coroutines)
implementation(libs.kotlin.serialization.json)
implementation(libs.kotlin.stdib)
implementation(libs.protobuf.java)
compileOnly(libs.xz)
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,270 @@
package in.dragonbra.javasteamsamples._020_friends;

import in.dragonbra.javasteam.enums.EResult;
import in.dragonbra.javasteam.steam.authentication.AuthPollResult;
import in.dragonbra.javasteam.steam.authentication.AuthSessionDetails;
import in.dragonbra.javasteam.steam.authentication.AuthenticationException;
import in.dragonbra.javasteam.steam.authentication.CredentialsAuthSession;
import in.dragonbra.javasteam.steam.authentication.SteamAuthentication;
import in.dragonbra.javasteam.steam.authentication.UserConsoleAuthenticator;
import in.dragonbra.javasteam.steam.handlers.steamcloud.ChatMediaUploadResult;
import in.dragonbra.javasteam.steam.handlers.steamcloud.SteamCloud;
import in.dragonbra.javasteam.steam.handlers.steamuser.LogOnDetails;
import in.dragonbra.javasteam.steam.handlers.steamuser.SteamUser;
import in.dragonbra.javasteam.steam.handlers.steamuser.callback.LoggedOffCallback;
import in.dragonbra.javasteam.steam.handlers.steamuser.callback.LoggedOnCallback;
import in.dragonbra.javasteam.steam.steamclient.SteamClient;
import in.dragonbra.javasteam.steam.steamclient.callbackmgr.CallbackManager;
import in.dragonbra.javasteam.steam.steamclient.callbacks.ConnectedCallback;
import in.dragonbra.javasteam.steam.steamclient.callbacks.DisconnectedCallback;
import in.dragonbra.javasteam.types.SteamID;
import in.dragonbra.javasteam.util.log.DefaultLogListener;
import in.dragonbra.javasteam.util.log.LogManager;

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.concurrent.CancellationException;
import java.util.concurrent.ExecutionException;

//
// Sample 020.2: Chat media
//
// this sample logs on and sends an image or video to the chat with a friend.
//
// media doesn't go over the connection to Steam like a text message does. It is uploaded
// to the community website, and Steam then posts it to the chat for us. The website wants
// the access token of the logged-in user, so we log on with an auth session to get one.
//
// once it is sent, the sample prints where Steam stored the file, the address
// the chat message links to among it.
//
// usage: <username> <password> <friend steamid64> <path to a file> [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: <username> <password> <friend steamid64> <path to a file> [spoiler]");
return;
}

SteamID friend;
try {
friend = new SteamID(Long.parseUnsignedLong(args[2]));
} catch (NumberFormatException e) {
System.out.println("Sample 020: The friend has to be a 64-bit SteamID, like 76561197960287930");
return;
}

Path file = Path.of(args[3]);
if (!Files.isRegularFile(file)) {
System.out.println("Sample 020: No file found at " + file.toAbsolutePath());
return;
}

// an optional fifth argument hides the media in the chat until it is clicked
boolean spoiler = args.length > 4 && args[4].equalsIgnoreCase("spoiler");

LogManager.addListener(new DefaultLogListener());

new SampleChatMedia(args[0], args[1], friend, file, spoiler).run();
}

@Override
public void run() {
// create our steamclient instance
steamClient = new SteamClient();

// create the callback manager which will route callbacks to function calls
manager = new CallbackManager(steamClient);

// get the steamuser handler, which is used for logging on after successfully connecting
steamUser = steamClient.getHandler(SteamUser.class);

// get the steamcloud handler, which is used for uploading the media
steamCloud = steamClient.getHandler(SteamCloud.class);

// register a few callbacks we're interested in
// these are registered upon creation to a callback manager, which will then route the callbacks
// to the functions specified
manager.subscribe(ConnectedCallback.class, this::onConnected);
manager.subscribe(DisconnectedCallback.class, this::onDisconnected);

manager.subscribe(LoggedOnCallback.class, this::onLoggedOn);
manager.subscribe(LoggedOffCallback.class, this::onLoggedOff);

isRunning = true;

System.out.println("Connecting to steam...");

// initiate the connection
steamClient.connect();

// create our callback handling loop
while (isRunning) {
// in order for the callbacks to get routed, they need to be handled by the manager
manager.runWaitCallbacks(1000L);
}

}

private void onConnected(ConnectedCallback callback) {
System.out.println("Connected to Steam! Logging in " + user + "...");

AuthSessionDetails authSessionDetails = new AuthSessionDetails();
authSessionDetails.username = user;
authSessionDetails.password = pass;
authSessionDetails.persistentSession = false;
authSessionDetails.authenticator = new UserConsoleAuthenticator();

// get the authentication handler, which used for authenticating with Steam
SteamAuthentication auth = new SteamAuthentication(steamClient);

try {
CredentialsAuthSession authSession = auth.beginAuthSessionViaCredentials(authSessionDetails).get();

AuthPollResult pollResponse = authSession.pollingWaitForResult().get();

LogOnDetails logOnDetails = new LogOnDetails();
logOnDetails.setUsername(pollResponse.getAccountName());
logOnDetails.setAccessToken(pollResponse.getRefreshToken());

// Set LoginID to a non-zero value if you have another client connected using the same account,
// the same private ip, and same public ip.
logOnDetails.setLoginID(149);

steamUser.logOn(logOnDetails);

// the access token is what signs us in to the community website, keep it for the upload.
// it expires after a day, see sample 002 for how to renew it.
accessToken = pollResponse.getAccessToken();
} catch (Exception e) {
System.err.println(e.getMessage());

// List a couple of exceptions that could be important to handle.
if (e instanceof AuthenticationException) {
System.out.println("An Authentication error has occurred. " + e.getMessage());
}

if (e instanceof CancellationException) {
System.out.println("An Cancellation exception was raised. Usually means a timeout occurred. " + e.getMessage());
}

isRunning = false;
}
}

private void onDisconnected(DisconnectedCallback callback) {
System.out.println("Disconnected from Steam");

isRunning = false;
}

private void onLoggedOn(LoggedOnCallback callback) {
if (callback.getResult() != EResult.OK) {
System.out.println("Unable to login to steam: " + callback.getResult() + " / " + callback.getExtendedResult());

isRunning = false;

return;
}

System.out.println("Successfully logged on!");

// at this point, we'd be able to perform actions on Steam

sendMedia();

// for this sample we'll just log off
// steamUser.logOff();
}

/**
* Uploads the file to the chat with the friend, and prints where Steam stored it.
*/
private void sendMedia() {
byte[] media;
try {
media = Files.readAllBytes(file);
} catch (IOException e) {
System.err.println("Unable to read " + file + ": " + e.getMessage());
return;
}

System.out.println("Sending " + file.getFileName() + " (" + media.length + " bytes) to " + friend.convertToUInt64() + "...");

try {
// the type of the file, and the size of an image, are worked out from the file itself.
// the upload takes a few requests, so we get a future back and wait for it here.
// to send to a group chat instead, use uploadChatMediaToChatRoom with the IDs of the group and channel.
ChatMediaUploadResult result = steamCloud.uploadChatMediaToUser(
accessToken,
friend,
media,
file.getFileName().toString(),
spoiler
).get();

// nothing else to do to get it delivered, Steam has posted the media to the chat.
// the result tells where it is stored. The URL is the one the chat message links to.
// the UGC ID is unsigned, and can be used with steamCloud.requestUGCDetails to look the file up again later.
System.out.println("Sent!");
System.out.println(" UGC ID: " + Long.toUnsignedString(result.getUgcID()));
System.out.println(" URL: " + result.getUrl());
System.out.println(" Name: " + result.getFileName());
System.out.println(" Size: " + result.getFileSize() + " bytes");
System.out.println(" SHA-1: " + result.getFileSHA());
} catch (ExecutionException e) {
// an IllegalArgumentException means the file is too large or not a supported format,
// an IOException that a request failed or that Steam turned it down, the access token being rejected for one.
System.err.println("Unable to send the media: " + e.getCause().getMessage());
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
}

private void onLoggedOff(LoggedOffCallback callback) {
System.out.println("Logged off of Steam: " + callback.getResult());

isRunning = false;
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,116 @@
package `in`.dragonbra.javasteam.steam.handlers.steamcloud

import `in`.dragonbra.javasteam.util.JavaSteamAddition

/**
* The type and pixel size of an image or video, read from its header.
* Steam wants both when media is uploaded to a chat.
*
* @param mimeType The MIME type, like `image/png`.
* @param width The width in pixels, zero for a video.
* @param height The height in pixels, zero for a video.
*/
@JavaSteamAddition
internal data class ChatMediaInfo(val mimeType: String, val width: Int, val height: Int) {

/**
* The file extension that goes with [mimeType], without a dot.
*/
val extension: String
get() = mimeType.substringAfter('/')

companion object {
private val PNG_SIGNATURE = byteArrayOf(0x89.toByte(), 0x50, 0x4E, 0x47, 0x0D, 0x0A, 0x1A, 0x0A)

// The EBML header that WebM files start with
private val WEBM_SIGNATURE = byteArrayOf(0x1A, 0x45, 0xDF.toByte(), 0xA3.toByte())

// A pack header (program stream) or a sequence header (bare video stream)
private val MPEG_SIGNATURES = listOf(
byteArrayOf(0x00, 0x00, 0x01, 0xBA.toByte()),
byteArrayOf(0x00, 0x00, 0x01, 0xB3.toByte()),
)

/**
* Reads the type of a PNG, JPEG or GIF image, or a WebM, MPEG or OGV video.
* The size is read for images only, Steam takes videos with a size of zero.
*
* @throws IllegalArgumentException if the data is not one of those, or its header is cut short.
*/
fun detect(data: ByteArray): ChatMediaInfo = when {
data.startsWith(PNG_SIGNATURE) -> png(data)

data.startsWith("GIF87a") || data.startsWith("GIF89a") -> gif(data)

data.size >= 2 && data.u8(0) == 0xFF && data.u8(1) == 0xD8 -> jpeg(data)

data.startsWith(WEBM_SIGNATURE) -> ChatMediaInfo("video/webm", 0, 0)

MPEG_SIGNATURES.any { data.startsWith(it) } -> ChatMediaInfo("video/mpeg", 0, 0)

data.startsWith("OggS") -> ChatMediaInfo("video/ogv", 0, 0)

else -> throw IllegalArgumentException(
"Unsupported media format, expected a PNG, JPEG or GIF image, or a WebM, MPEG or OGV video"
)
}

// The IHDR chunk always comes first, with the size as two big endian ints
private fun png(data: ByteArray): ChatMediaInfo {
require(data.size >= 24) { "Malformed PNG, the header is cut short" }
return ChatMediaInfo("image/png", data.u32be(16), data.u32be(20))
}

// The logical screen size follows the signature as two little endian shorts
private fun gif(data: ByteArray): ChatMediaInfo {
require(data.size >= 10) { "Malformed GIF, the header is cut short" }
return ChatMediaInfo("image/gif", data.u16le(6), data.u16le(8))
}

// The size is in the start of frame segment, which can sit behind any number of other segments
private fun jpeg(data: ByteArray): ChatMediaInfo {
var offset = 2

while (offset + 4 <= data.size) {
if (data.u8(offset) != 0xFF) {
break
}

val marker = data.u8(offset + 1)

when {
// Padding before a marker
marker == 0xFF -> offset++

// Standalone markers, they have no length
marker == 0x01 || marker in 0xD0..0xD8 -> offset += 2

// Start of frame. C4, C8 and CC share the range but are other things.
marker in 0xC0..0xCF && marker != 0xC4 && marker != 0xC8 && marker != 0xCC -> {
if (offset + 9 > data.size) {
break
}
return ChatMediaInfo("image/jpeg", data.u16be(offset + 7), data.u16be(offset + 5))
}

else -> offset += 2 + data.u16be(offset + 2)
}
}

throw IllegalArgumentException("Malformed JPEG, no frame header found")
}

private fun ByteArray.startsWith(prefix: ByteArray): Boolean =
size >= prefix.size && prefix.indices.all { this[it] == prefix[it] }

private fun ByteArray.startsWith(prefix: String): Boolean = startsWith(prefix.toByteArray(Charsets.US_ASCII))

private fun ByteArray.u8(index: Int): Int = this[index].toInt() and 0xFF

private fun ByteArray.u16be(index: Int): Int = (u8(index) shl 8) or u8(index + 1)

private fun ByteArray.u16le(index: Int): Int = u8(index) or (u8(index + 1) shl 8)

private fun ByteArray.u32be(index: Int): Int = (u16be(index) shl 16) or u16be(index + 2)
}
}
Loading
Loading