Skip to content

uakihir0/kmastodon

Repository files navigation

日本語

kmastodon

Maven metadata URL

badge badge badge badge

This library is a Mastodon client library that supports Kotlin Multiplatform. It depends on khttpclient and internally uses Ktor Client. Therefore, this library is available on Kotlin Multiplatform and platforms supported by Ktor Client. The behavior on each platform depends on khttpclient.

Usage

Below is how to use it in Kotlin with Gradle on supported platforms. If you want to use it on Apple platforms, please refer to kmastodon-cocoapods. Also, for usage in JavaScript, please refer to kmastodon.js. Please refer to the test code for how to use each API.

repositories {
    mavenCentral()
+   maven { url = uri("https://repo.repsy.io/mvn/uakihir0/public") }
}

dependencies {
+   implementation("work.socialhub.kmastodon:core:0.0.1-SNAPSHOT")
+   implementation("work.socialhub.kmastodon:stream:0.0.1-SNAPSHOT")
}

Authentication

First, create an application and request application information from the server.

val mastodon = MastodonFactory.instance({{HOST}})

val response = mastodon.apps().registerApplication(
    AppsRegisterApplicationRequest().also {
        it.name = {{APP_NAME}}
        it.website = {{APP_WEBSITE}}
        it.redirectUris = {{REDIRECT_URI}}
        it.scopes = "read write follow push"
    }
)

println(response.data.clientId)
println(response.data.clientSecret)

Next, request the URL for users to authenticate as follows.

val response = mastodon.oauth().authorizationUrl(
    OAuthAuthorizationUrlRequest().also {
        it.clientId = {{CLIENT_ID}}
        it.redirectUri = {{REDIRECT_URI}}
        it.scopes = "read write follow push"
    }
)

println(response.data)

After the user authenticates and is redirected, obtain the code from the redirected URL query and get the access token as follows.

val response = mastodon.oauth().issueAccessTokenWithAuthorizationCode(
    OAuthIssueAccessTokenWithAuthorizationCodeRequest().also {
        it.clientId = {{CLIENT_ID}}
        it.clientSecret = {{CLIENT_SECRET}}
        it.redirectUri = {{REDIRECT_URI}}
        it.code = "CODE"
    }
)

println(response.data.accessToken)

Create Note

val mastodon = MastodonFactory.instance(
    {{HOST}}, {{ACCESS_TOKEN}}
)

mastodon.statuses().postStatus(
    StatusesPostStatusRequest().also {
        it.status = "Post from kmastodon! for test." + "\n" +
                "https://github.com/uakihir0/kmastodon"
    }
)

License

MIT License

Author

Akihiro Urushihara