JavaSteam

repository·master·Indexed 40 days ago

https://github.com/longi94/javasteam

A Java port of SteamKit2 designed to interface with Steam services, targeting Java 17. It provides capabilities for Steam session authentication via AuthSessionDetails, downloading depot manifests and chunks through the Client class, and handling struct-backed Steam and Game Coordinator messages using the Msg and ClientGCMsg classes.

Tokens
7.7K
Snippets
16
Records
28
Agent score
50%

What's inside JavaSteam

  1. Install JavaSteam via Gradle or Maven

    master

    JavaSteam is a Java port of SteamKit2 that targets Java 17. To use it in your project, add the Maven Central repository and the in.dragonbra:javasteam dependency.

    1. Add the repository

    Gradle:

    repositories {
        mavenCentral()
    }

    Maven:

    <repository>
        <id>central</id>
        <url>https://repo.maven.apache.org/maven2</url>
    </repository>

    2. Add the dependency

    Gradle:

    implementation 'in.dragonbra:javasteam:x.y.z'

    Maven:

    <dependency>
        <groupId>in.dragonbra</groupId>
        <artifactId>javasteam</artifactId>
        <version>x.y.z</version>
    </dependency>
    implementation 'in.dragonbra:javasteam:x.y.z'
  2. Configure required cryptography dependencies

    master

    JavaSteam requires a cryptography dependency to function. You must choose the one appropriate for your platform:

    Troubleshooting InvalidKeyException If you encounter java.security.InvalidKeyException: Illegal key size or default parameters during message encryption, you may need to install the Unlimited Strength Jurisdiction Policy Files into your ${java.home}/jre/lib/security/ directory.

  3. Build JavaSteam from source

    master

    If you are developing or building the project from the repository, use the following Gradle commands:

    Full build:

    ./gradlew build -x signMavenJavaPublication

    Generate required classes (Protobufs and Steam language):

    ./gradlew generateProto generateSteamLanguage generateProjectVersion
    ./gradlew build -x signMavenJavaPublication
  4. Use the Client class to download Steam content

    master

    The Client class is the primary interface for downloading game content from Steam content delivery networks (CDNs). It requires an associated, connected, and logged-in SteamClient instance.

    Key capabilities include:

    • Downloading depot manifests (downloadManifest).
    • Downloading depot chunks (downloadDepotChunk).
    • Supporting proxy servers and CDN authentication tokens.
    • Decrypting filenames and processing chunks if a depotKey is provided.

    Note: The Client implements Closeable. You should call .close() to cancel pending coroutines and shut down the underlying HTTP client's connection pool and executor service.

    // Example initialization (requires an existing SteamClient)
    val cdnClient = Client(steamClient)
    
    try {
        // Perform downloads...
    } finally {
        cdnClient.close()
    }
  5. Configure optional JavaSteam dependencies

    master

    Depending on your use case, you may need to add the following optional dependencies:

    Protobufs

    If you intend to work with protobuf builders directly (for actions not supported by a handler), add protobuf-java. It is recommended to match the version used by JavaSteam to avoid errors or warnings.

    Content Downloading

    To support content downloading, add these dependencies:

    You can find the specific versions supported by the current JavaSteam release in the libs.versions.toml file.

  6. Use ChatEnterCallback to handle chat room entry events

    master

    The ChatEnterCallback is triggered when a user attempts to join a chat room. It provides metadata about the chat room, the user's relationship to it, and the current membership list.

    Note that chatRoomName and chatMembers are only reliably populated if the enterResponse is EChatRoomEnterResponse.Success. If the entry attempt fails, the payload may only contain the chat room name.

    Available Properties

    • chatID: The SteamID of the chat room.
    • friendID: The SteamID of the friend involved.
    • chatRoomType: The type of the chat room (EChatRoomType).
    • ownerID: The SteamID of the chat room owner.
    • clanID: The SteamID of the clan that owns the chat room.
    • chatFlags: Byte representing chat flags.
    • enterResponse: The result of the entry attempt (EChatRoomEnterResponse).
    • numChatMembers: The number of users currently in the chat room.
    • chatRoomName: The name of the chat room.
    • chatMembers: A list of ChatMemberInfo instances for the members in the room.
    // Example of accessing ChatEnterCallback properties
    fun handleChatEnter(callback: ChatEnterCallback) {
        println("Joined chat: ${callback.chatRoomName} (ID: ${callback.chatID})")
        
        if (callback.enterResponse == EChatRoomEnterResponse.Success) {
            println("Members in chat: ${callback.chatMembers.size}")
            callback.chatMembers.forEach { member ->
                // Access member info
            }
        } else {
            println("Failed to enter chat. Response: ${callback.enterResponse}")
        }
    }
  7. Access ServerRecord properties

    master

    Once a ServerRecord is created, you can access the connection details through the following properties:

    • host: Returns the hostname or IP address as a String.
    • port: Returns the port number as an Int.
    • endpoint: Returns the underlying InetSocketAddress used for the connection.
    • protocolTypes: Returns an EnumSet of the ProtocolTypes supported by this server.
  8. Java compatibility: downloadManifestFuture and downloadDepotChunkFuture

    master

    For Java consumers, the Client provides CompletableFuture versions of the primary download methods to handle asynchronous execution via a managed coroutine scope.

    • downloadManifestFuture(...): Returns CompletableFuture<DepotManifest>.
    • downloadDepotChunkFuture(...): Returns CompletableFuture<Int>.

    Note on downloadDepotChunkFuture buffer sizing:

    • If depotKey is provided: The destination buffer must be longer than chunk.compressedLength (to accommodate decompression).
    • If depotKey is NOT provided: The destination buffer must be exactly the same size as chunk.compressedLength.
    // Java usage example
    CompletableFuture<DepotManifest> future = client.downloadManifestFuture(
        12345, 67890L, 0L, server, depotKey, null, null
    );
    
    future.thenAccept(manifest -> {
        // Handle manifest
    }).exceptionally(ex -> {
        // Handle error
        return null;
    });
  9. Create a Server instance

    master

    The Server class represents a single Steam3 'Steampipe' content server. You can instantiate a Server using two static factory methods provided in its companion object:

    1. fromInetSocketAddress(endPoint: InetSocketAddress): Creates a server from a network socket address. It automatically determines if the protocol is HTTPS or HTTP based on whether the port is 443.
    2. fromHostAndPort(hostname: String, port: Int): Creates a server from a hostname string and an integer port. It also automatically sets the protocol to HTTPS if the port is 443.

    Note that host and vHost are both initialized to the provided hostname/address.

    // Using hostname and port
    val server = Server.fromHostAndPort("cdn.steampowered.com", 443)
    
    // Using InetSocketAddress
    val address = InetSocketAddress("127.0.0.1", 80)
    val serverFromAddress = Server.fromInetSocketAddress(address)
  10. Build CDN request URLs with buildCommand

    master

    The Client.buildCommand companion method constructs a valid HttpUrl for CDN requests, supporting proxy transformations.

    Parameters:

    • server: The target Server.
    • command: The request path (e.g., depot/123/manifest/456).
    • query (optional): A query string (e.g., ?token=abc).
    • proxyServer (optional): A Server instance. If proxyServer.useAsProxy is true and proxyServer.proxyRequestPathTemplate is provided, the URL is constructed using the template (replacing %host% and %path%).

    Returns: A configured HttpUrl object.

  11. Create a ServerRecord for Steam CM servers

    master

    The ServerRecord class represents the connection information required to connect to a Steam Connection Manager (CM) server. You can instantiate it using several factory methods in the companion object depending on whether you are dealing with raw host/port pairs, socket endpoints, or WebSocket addresses.

    Factory Methods

    • createServer(host: String, port: Int, protocolTypes: ProtocolTypes): Creates a record for a specific host and port with a single protocol type.
    • createServer(host: String, port: Int, protocolTypes: EnumSet<ProtocolTypes>): Creates a record for a specific host and port with multiple protocol types.
    • createSocketServer(endpoint: InetSocketAddress): Creates a record from an InetSocketAddress and automatically assigns both ProtocolTypes.TCP and ProtocolTypes.UDP.
    • tryCreateSocketServer(address: String): Attempts to parse a string address (e.g., "127.0.0.1:8080") into a socket server record. Returns null if the address is invalid.
    • createWebSocketServer(address: String): Creates a record for a WebSocket server. If the address is in the format hostname:port, it uses that port; otherwise, it defaults to port 443. This record is assigned ProtocolTypes.WEB_SOCKET.
    // Create via host and port
    val record = ServerRecord.createServer("localhost", 27015, ProtocolTypes.UDP)
    
    // Create via string address (returns null if invalid)
    val socketRecord = ServerRecord.tryCreateSocketServer("127.0.0.1:27015")
    
    // Create via WebSocket address (defaults to port 443 if no port provided)
    val wsRecord = ServerRecord.createWebSocketServer("example.com:8443")