Skip to content

Commit

Permalink
send mail on send to social networks errors
Browse files Browse the repository at this point in the history
  • Loading branch information
Ziedelth committed Dec 17, 2024
1 parent 7fa6d80 commit bb75ddf
Show file tree
Hide file tree
Showing 3 changed files with 56 additions and 41 deletions.
30 changes: 11 additions & 19 deletions src/main/kotlin/fr/shikkanime/jobs/FetchEpisodesJob.kt
Original file line number Diff line number Diff line change
Expand Up @@ -8,13 +8,16 @@ import fr.shikkanime.entities.EpisodeVariant
import fr.shikkanime.entities.Simulcast
import fr.shikkanime.entities.enums.*
import fr.shikkanime.platforms.AbstractPlatform
import fr.shikkanime.services.EmailService
import fr.shikkanime.services.EpisodeVariantService
import fr.shikkanime.services.MediaImage
import fr.shikkanime.services.caches.ConfigCacheService
import fr.shikkanime.services.caches.EpisodeVariantCacheService
import fr.shikkanime.utils.*
import jakarta.inject.Inject
import java.io.ByteArrayOutputStream
import java.io.PrintWriter
import java.io.StringWriter
import java.time.ZonedDateTime
import java.util.logging.Level
import javax.imageio.ImageIO
Expand All @@ -38,6 +41,9 @@ class FetchEpisodesJob : AbstractJob {
@Inject
private lateinit var configCacheService: ConfigCacheService

@Inject
private lateinit var emailService: EmailService

fun addHashCaches(
it: AbstractPlatform<*, *, *>,
variants: List<EpisodeVariant>
Expand Down Expand Up @@ -148,21 +154,12 @@ class FetchEpisodesJob : AbstractJob {

if (typeIdentifiers.add(typeIdentifier)) {
val episodeDto = AbstractConverter.convert(episode, EpisodeVariantDto::class.java)
sendEpisodeNotification(episodeDto)
sendToSocialNetworks(episodeDto)
}
}
}
}

private fun sendEpisodeNotification(episodeDto: EpisodeVariantDto) {
try {
FirebaseNotification.send(episodeDto)
} catch (e: Exception) {
logger.log(Level.SEVERE, "Error while sending notification for episode ${episodeDto.identifier}", e)
}
}

private fun sendToSocialNetworks(dto: EpisodeVariantDto) {
val mediaImage = try {
val byteArrayOutputStream = ByteArrayOutputStream()
Expand All @@ -177,16 +174,11 @@ class FetchEpisodesJob : AbstractJob {
try {
socialNetwork.sendEpisodeRelease(dto, mediaImage)
} catch (e: Exception) {
logger.log(
Level.SEVERE,
"Error while sending episode release for ${
socialNetwork.javaClass.simpleName.replace(
"SocialNetwork",
""
)
}",
e
)
val title = "Error while sending episode release for ${socialNetwork.javaClass.simpleName.replace("SocialNetwork", "")}"
logger.log(Level.SEVERE, title, e)
val stringWriter = StringWriter()
e.printStackTrace(PrintWriter(stringWriter))
emailService.sendAdminEmail(title, stringWriter.toString().replace("\n", "<br>"))
}
}
}
Expand Down
Original file line number Diff line number Diff line change
@@ -1,35 +1,58 @@
package fr.shikkanime.utils
package fr.shikkanime.socialnetworks

import com.google.auth.oauth2.GoogleCredentials
import com.google.firebase.FirebaseApp
import com.google.firebase.FirebaseOptions
import com.google.firebase.messaging.*
import com.google.inject.Inject
import fr.shikkanime.dtos.variants.EpisodeVariantDto
import fr.shikkanime.services.MemberService
import fr.shikkanime.utils.Constant
import fr.shikkanime.utils.LoggerFactory
import fr.shikkanime.utils.StringUtils
import java.io.File
import java.io.FileInputStream
import java.util.logging.Level

object FirebaseNotification {
class FirebaseSocialNetwork : AbstractSocialNetwork() {
private val logger = LoggerFactory.getLogger(FirebaseSocialNetwork::class.java)
private var isInitialized = false

private fun init() {
if (isInitialized) return
val file = File(Constant.dataFolder, "firebase.json")
if (!file.exists()) return
@Inject
private lateinit var memberService: MemberService

FirebaseApp.initializeApp(
FirebaseOptions.builder()
.setCredentials(GoogleCredentials.fromStream(FileInputStream(file)))
.build()
)
override fun utmSource() = "firebase"

isInitialized = true
override fun login() {
if (isInitialized)
return

try {
val file = File(Constant.dataFolder, "firebase.json")
if (!file.exists())
return

FirebaseApp.initializeApp(
FirebaseOptions.builder()
.setCredentials(GoogleCredentials.fromStream(FileInputStream(file)))
.build()
)

isInitialized = true
} catch (e: Exception) {
logger.log(Level.SEVERE, "Error while initializing FirebaseSocialNetwork", e)
}
}

fun send(episodeDto: EpisodeVariantDto) {
init()
override fun logout() {
if (!isInitialized) return
val memberService = Constant.injector.getInstance(MemberService::class.java)
isInitialized = false
}

override fun sendEpisodeRelease(episodeDto: EpisodeVariantDto, mediaImage: ByteArray?) {
login()
if (!isInitialized) return

val image = "${Constant.apiUrl}/v1/attachments?uuid=${episodeDto.mapping.uuid}&type=image"

val notification = Notification.builder()
Expand Down
14 changes: 7 additions & 7 deletions src/main/kotlin/fr/shikkanime/wrappers/ThreadsWrapper.kt
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@ object ThreadsWrapper {
private const val API_URL = "https://graph.threads.net"
private val httpRequest = HttpRequest()

fun getRedirectUri() = "${Constant.baseUrl}/api/threads".replace("http://", "https://")
private fun getRedirectUri() = "${Constant.baseUrl}/api/threads".replace("http://", "https://")

fun getCode(appId: String) = "$AUTHORIZATION_URL/oauth/authorize?" +
"client_id=$appId&" +
Expand Down Expand Up @@ -77,22 +77,22 @@ object ThreadsWrapper {
"reply_to_id" to replyToId,
).filterValues { it != null }.map { (key, value) -> "$key=$value" }.joinToString("&")

val response = httpRequest.post(
val createResponse = httpRequest.post(
"$API_URL/me/threads?$parameters",
headers = mapOf(HttpHeaders.ContentType to ContentType.Application.Json.toString()),
)

require(response.status == HttpStatusCode.OK) { "Failed to post" }
val creationId = ObjectParser.fromJson(response.bodyAsText())["id"].asString
require(createResponse.status == HttpStatusCode.OK) { "Failed to post" }
val creationId = ObjectParser.fromJson(createResponse.bodyAsText())["id"].asString

val response2 = httpRequest.post(
val publishResponse = httpRequest.post(
"$API_URL/me/threads_publish?" +
"access_token=$accessToken&" +
"creation_id=$creationId",
headers = mapOf(HttpHeaders.ContentType to ContentType.Application.Json.toString()),
)

require(response2.status == HttpStatusCode.OK) { "Failed to publish" }
return ObjectParser.fromJson(response2.bodyAsText())["id"].asLong
require(publishResponse.status == HttpStatusCode.OK) { "Failed to publish" }
return ObjectParser.fromJson(publishResponse.bodyAsText())["id"].asLong
}
}

0 comments on commit bb75ddf

Please sign in to comment.