Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: use official Threads API #735

Merged
merged 1 commit into from
Oct 18, 2024
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
45 changes: 45 additions & 0 deletions src/main/kotlin/fr/shikkanime/controllers/admin/AdminController.kt
Original file line number Diff line number Diff line change
Expand Up @@ -7,8 +7,10 @@ import fr.shikkanime.entities.Anime
import fr.shikkanime.entities.EpisodeMapping
import fr.shikkanime.entities.EpisodeVariant
import fr.shikkanime.entities.Simulcast
import fr.shikkanime.entities.enums.ConfigPropertyKey
import fr.shikkanime.entities.enums.Link
import fr.shikkanime.services.*
import fr.shikkanime.services.caches.ConfigCacheService
import fr.shikkanime.services.caches.SimulcastCacheService
import fr.shikkanime.utils.MapCache
import fr.shikkanime.utils.routes.AdminSessionAuthenticated
Expand All @@ -19,6 +21,7 @@ import fr.shikkanime.utils.routes.method.Get
import fr.shikkanime.utils.routes.method.Post
import fr.shikkanime.utils.routes.param.BodyParam
import fr.shikkanime.utils.routes.param.QueryParam
import fr.shikkanime.wrappers.ThreadsWrapper
import io.ktor.http.*
import kotlinx.coroutines.delay
import kotlinx.coroutines.runBlocking
Expand All @@ -36,6 +39,9 @@ class AdminController {
@Inject
private lateinit var animeService: AnimeService

@Inject
private lateinit var configCacheService: ConfigCacheService

@Path
@Get
private fun home(@QueryParam("error") error: String?): Response {
Expand Down Expand Up @@ -156,6 +162,45 @@ class AdminController {
return Response.template(Link.TRACE_ACTIONS)
}

@Path("/threads")
@Get
@AdminSessionAuthenticated
private fun getThreads(
@QueryParam("success") success: Int?
): Response {
return Response.template(
Link.THREADS,
mapOf(
"askCodeUrl" to ThreadsWrapper.getCode(
requireNotNull(configCacheService.getValueAsString(ConfigPropertyKey.THREADS_APP_ID))
),
"success" to success
)
)
}

@Path("/threads-publish")
@Get
@AdminSessionAuthenticated
private fun threadsPublish(
@QueryParam("message") message: String,
@QueryParam("image_url") imageUrl: String?,
): Response {
val hasImage = !imageUrl.isNullOrBlank()

runBlocking {
ThreadsWrapper.post(
requireNotNull(configCacheService.getValueAsString(ConfigPropertyKey.THREADS_ACCESS_TOKEN)),
if (hasImage) ThreadsWrapper.PostType.IMAGE else ThreadsWrapper.PostType.TEXT,
message,
imageUrl.takeIf { hasImage },
"An example image".takeIf { hasImage }
)
}

return Response.redirect(Link.THREADS.href)
}

@Path("/config")
@Get
@AdminSessionAuthenticated
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -148,12 +148,21 @@ class EpisodeMappingController : HasPageableRoute() {

@Path("/{uuid}/media-image")
@Get
@AdminSessionAuthenticated
@OpenAPI(hidden = true)
private fun getMediaImage(@PathParam("uuid") uuid: UUID): Response {
@OpenAPI(
"Get episode variant image published on social networks",
[
OpenAPIResponse(200, "Image found", contentType = "image/jpeg"),
OpenAPIResponse(404, "Image not found")
]
)
private fun getMediaImage(
@PathParam("uuid", description = "UUID of the episode variant") uuid: UUID
): Response {
val episodeVariant = episodeVariantService.find(uuid) ?: return Response.notFound()

val image = ImageService.toEpisodeImage(
AbstractConverter.convert(
episodeVariantService.find(uuid),
episodeVariant,
EpisodeVariantDto::class.java
)
)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,7 @@ class MetricController {
private fun getMetrics(
@QueryParam("hours") hours: Int?,
): Response {
val oneHourAgo = ZonedDateTime.now().minusHours(hours?.toLong() ?: 1)
return Response.ok(AbstractConverter.convert(metricService.findAllAfter(oneHourAgo), MetricDto::class.java))
val xHourAgo = ZonedDateTime.now().minusHours(hours?.toLong() ?: 1)
return Response.ok(AbstractConverter.convert(metricService.findAllAfter(xHourAgo), MetricDto::class.java))
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,64 @@
package fr.shikkanime.controllers.api

import com.google.inject.Inject
import fr.shikkanime.entities.Config
import fr.shikkanime.entities.enums.ConfigPropertyKey
import fr.shikkanime.entities.enums.Link
import fr.shikkanime.services.ConfigService
import fr.shikkanime.services.caches.ConfigCacheService
import fr.shikkanime.utils.MapCache
import fr.shikkanime.utils.routes.AdminSessionAuthenticated
import fr.shikkanime.utils.routes.Controller
import fr.shikkanime.utils.routes.Path
import fr.shikkanime.utils.routes.Response
import fr.shikkanime.utils.routes.method.Get
import fr.shikkanime.utils.routes.openapi.OpenAPI
import fr.shikkanime.utils.routes.param.QueryParam
import fr.shikkanime.wrappers.ThreadsWrapper
import kotlinx.coroutines.runBlocking

@Controller("/api/threads")
class ThreadsCallbackController {
@Inject
private lateinit var configCacheService: ConfigCacheService

@Inject
private lateinit var configService: ConfigService

@Path
@Get
@AdminSessionAuthenticated
@OpenAPI(hidden = true)
private fun callback(
@QueryParam("code") code: String,
): Response {
val appId = requireNotNull(configCacheService.getValueAsString(ConfigPropertyKey.THREADS_APP_ID))
val appSecret = requireNotNull(configCacheService.getValueAsString(ConfigPropertyKey.THREADS_APP_SECRET))

return runBlocking {
try {
val accessToken = ThreadsWrapper.getAccessToken(
appId,
appSecret,
code,
)

val longLivedAccessToken = ThreadsWrapper.getLongLivedAccessToken(
appSecret,
accessToken,
)

configService.findByName(ConfigPropertyKey.THREADS_ACCESS_TOKEN.key)?.let {
it.propertyValue = longLivedAccessToken
configService.update(it)
MapCache.invalidate(Config::class.java)
}

Response.redirect("${Link.THREADS.href}?success=1")
} catch (e: Exception) {
e.printStackTrace()
Response.badRequest("Impossible to get token with code $code")
}
}
}
}
38 changes: 29 additions & 9 deletions src/main/kotlin/fr/shikkanime/entities/enums/ConfigPropertyKey.kt
Original file line number Diff line number Diff line change
Expand Up @@ -3,24 +3,44 @@ package fr.shikkanime.entities.enums
enum class ConfigPropertyKey(val key: String) {
SIMULCAST_RANGE("simulcast_range"),
DISCORD_TOKEN("discord_token"),
TWITTER_CONSUMER_KEY("twitter_consumer_key"),
TWITTER_CONSUMER_SECRET("twitter_consumer_secret"),
TWITTER_ACCESS_TOKEN("twitter_access_token"),
TWITTER_ACCESS_TOKEN_SECRET("twitter_access_token_secret"),
SEO_DESCRIPTION("seo_description"),
SOCIAL_NETWORK_EPISODES_SIZE_LIMIT("social_network_episodes_size_limit"),
GOOGLE_SITE_VERIFICATION_ID("google_site_verification_id"),
CHECK_CRUNCHYROLL_SIMULCASTS("check_crunchyroll_simulcasts"),
BSKY_IDENTIFIER("bsky_identifier"),
BSKY_PASSWORD("bsky_password"),

// Twitter API
TWITTER_CONSUMER_KEY("twitter_consumer_key"),
TWITTER_CONSUMER_SECRET("twitter_consumer_secret"),
TWITTER_ACCESS_TOKEN("twitter_access_token"),
TWITTER_ACCESS_TOKEN_SECRET("twitter_access_token_secret"),
TWITTER_FIRST_MESSAGE("twitter_first_message"),
TWITTER_SECOND_MESSAGE("twitter_second_message"),

// Threads old API
@Deprecated("Use Threads API")
THREADS_USERNAME("threads_username"),

@Deprecated("Use Threads API")
THREADS_PASSWORD("threads_password"),
THREADS_MESSAGE("threads_message"),
BSKY_MESSAGE("bsky_message"),
BSKY_SESSION_TIMEOUT("bsky_session_timeout"),

@Deprecated("Use Threads API")
THREADS_SESSION_TIMEOUT("threads_session_timeout"),

// Threads API
USE_NEW_THREADS_WRAPPER("use_new_threads_wrapper"),
THREADS_APP_ID("threads_app_id"),
THREADS_APP_SECRET("threads_app_secret"),
THREADS_ACCESS_TOKEN("threads_access_token"),
THREADS_FIRST_MESSAGE("threads_first_message"),
THREADS_SECOND_MESSAGE("threads_second_message"),

// Bsky API
BSKY_IDENTIFIER("bsky_identifier"),
BSKY_PASSWORD("bsky_password"),
BSKY_SESSION_TIMEOUT("bsky_session_timeout"),
BSKY_FIRST_MESSAGE("bsky_first_message"),
BSKY_SECOND_MESSAGE("bsky_second_message"),

SIMULCAST_RANGE_DELAY("simulcast_range_delay"),
CRUNCHYROLL_FETCH_API_SIZE("crunchyroll_fetch_api_size"),
ANIMATION_DITIGAL_NETWORK_SIMULCAST_DETECTION_REGEX("animation_digital_network_simulcast_detection_regex"),
Expand Down
1 change: 1 addition & 0 deletions src/main/kotlin/fr/shikkanime/entities/enums/Link.kt
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@ enum class Link(
ANIMES("/admin/animes", "/admin/animes/list.ftl", "bi bi-file-earmark-play", "Animes"),
EPISODES("/admin/episodes", "/admin/episodes/list.ftl", "bi bi-collection-play", "Episodes"),
TRACE_ACTIONS("/admin/trace-actions", "/admin/trace-actions.ftl", "bi bi-database-exclamation", "Trace actions"),
THREADS("/admin/threads", "/admin/threads.ftl", "bi bi-threads", "Threads"),
CONFIG("/admin/config", "/admin/configs.ftl", "bi bi-gear", "Configurations"),

// Site
Expand Down
Original file line number Diff line number Diff line change
@@ -1,10 +1,10 @@
package fr.shikkanime.socialnetworks

import com.google.inject.Inject
import fr.shikkanime.dtos.PlatformDto
import fr.shikkanime.dtos.variants.EpisodeVariantDto
import fr.shikkanime.entities.enums.EpisodeType
import fr.shikkanime.entities.enums.LangType
import fr.shikkanime.entities.enums.Platform
import fr.shikkanime.services.caches.ConfigCacheService
import fr.shikkanime.utils.Constant
import fr.shikkanime.utils.StringUtils
Expand All @@ -17,9 +17,7 @@ abstract class AbstractSocialNetwork {
abstract fun login()
abstract fun logout()

open fun platformAccount(platform: PlatformDto): String {
return platform.name
}
open fun platformAccount(platform: Platform) = platform.platformName

private fun information(episodeDto: EpisodeVariantDto): String {
return when (episodeDto.mapping.episodeType) {
Expand All @@ -41,7 +39,8 @@ abstract class AbstractSocialNetwork {
var configMessage = baseMessage
configMessage = configMessage.replace("{SHIKKANIME_URL}", getShikkanimeUrl(episodeDto))
configMessage = configMessage.replace("{URL}", episodeDto.url)
configMessage = configMessage.replace("{PLATFORM_ACCOUNT}", platformAccount(episodeDto.platform))
configMessage =
configMessage.replace("{PLATFORM_ACCOUNT}", platformAccount(Platform.valueOf(episodeDto.platform.id)))
configMessage = configMessage.replace("{PLATFORM_NAME}", episodeDto.platform.name)
configMessage = configMessage.replace("{ANIME_HASHTAG}", "#${StringUtils.getHashtag(episodeDto.mapping.anime.shortName)}")
configMessage = configMessage.replace("{ANIME_TITLE}", episodeDto.mapping.anime.shortName)
Expand Down
26 changes: 22 additions & 4 deletions src/main/kotlin/fr/shikkanime/socialnetworks/BskySocialNetwork.kt
Original file line number Diff line number Diff line change
Expand Up @@ -64,14 +64,18 @@ class BskySocialNetwork : AbstractSocialNetwork() {
override fun sendEpisodeRelease(episodeDto: EpisodeVariantDto, mediaImage: ByteArray?) {
checkSession()
if (!isInitialized) return
val message =
getEpisodeMessage(episodeDto, configCacheService.getValueAsString(ConfigPropertyKey.BSKY_MESSAGE) ?: "")

runBlocking {
val firstMessage =
getEpisodeMessage(
episodeDto,
configCacheService.getValueAsString(ConfigPropertyKey.BSKY_FIRST_MESSAGE) ?: ""
)

val firstRecord = runBlocking {
BskyWrapper.createRecord(
accessJwt!!,
did!!,
message,
firstMessage,
mediaImage?.let {
listOf(
BskyWrapper.Image(
Expand All @@ -85,5 +89,19 @@ class BskySocialNetwork : AbstractSocialNetwork() {
} ?: emptyList()
)
}

val secondMessage = configCacheService.getValueAsString(ConfigPropertyKey.BSKY_SECOND_MESSAGE)

if (!secondMessage.isNullOrBlank()) {
runBlocking {
BskyWrapper.createRecord(
accessJwt!!,
did!!,
getEpisodeMessage(episodeDto, secondMessage.replace("{EMBED}", "")).trim(),
replyTo = firstRecord,
embed = getShikkanimeUrl(episodeDto).takeIf { secondMessage.contains("{EMBED}") }
)
}
}
}
}
Loading
Loading