Skip to content

Commit

Permalink
feat: send email for FetchOldEpisodesJob.kt
Browse files Browse the repository at this point in the history
  • Loading branch information
Ziedelth committed Sep 30, 2024
1 parent 2e59306 commit de8aab0
Show file tree
Hide file tree
Showing 5 changed files with 60 additions and 14 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,7 @@ enum class ConfigPropertyKey(val key: String) {
LAST_FETCH_OLD_EPISODES("last_fetch_old_episodes"),
FETCH_OLD_EPISODES_RANGE("fetch_old_episodes_range"),
FETCH_OLD_EPISODES_LIMIT("fetch_old_episodes_limit"),
FETCH_OLD_EPISODES_EMAIL("fetch_old_episodes_email"),
EMAIL_HOST("email_host"),
EMAIL_PORT("email_port"),
EMAIL_USERNAME("email_username"),
Expand Down
48 changes: 35 additions & 13 deletions src/main/kotlin/fr/shikkanime/jobs/FetchOldEpisodesJob.kt
Original file line number Diff line number Diff line change
Expand Up @@ -9,10 +9,7 @@ import fr.shikkanime.exceptions.EpisodeNoSubtitlesOrVoiceException
import fr.shikkanime.platforms.AbstractPlatform.Episode
import fr.shikkanime.platforms.AnimationDigitalNetworkPlatform
import fr.shikkanime.platforms.CrunchyrollPlatform
import fr.shikkanime.services.AnimeService
import fr.shikkanime.services.ConfigService
import fr.shikkanime.services.EpisodeVariantService
import fr.shikkanime.services.TraceActionService
import fr.shikkanime.services.*
import fr.shikkanime.services.caches.ConfigCacheService
import fr.shikkanime.utils.*
import fr.shikkanime.wrappers.CrunchyrollWrapper
Expand Down Expand Up @@ -45,6 +42,14 @@ class FetchOldEpisodesJob : AbstractJob {
@Inject
private lateinit var traceActionService: TraceActionService

@Inject
private lateinit var emailService: EmailService

private fun log(stringBuilder: StringBuilder, level: Level, message: String) {
logger.log(level, message)
stringBuilder.append("[${level.localizedName}] $message<br/>")
}

override fun run() {
val range = configCacheService.getValueAsIntNullable(ConfigPropertyKey.FETCH_OLD_EPISODES_RANGE) ?: run {
logger.warning("Config ${ConfigPropertyKey.FETCH_OLD_EPISODES_RANGE.key} not found")
Expand All @@ -67,7 +72,9 @@ class FetchOldEpisodesJob : AbstractJob {

val episodes = mutableListOf<Episode>()
val start = System.currentTimeMillis()
logger.info("Fetching old episodes... (From ${dates.first()} to ${dates.last()})")
val emailLogs = StringBuilder()

log(emailLogs, Level.INFO, "Fetching old episodes... (From ${dates.first()} to ${dates.last()})")

episodes.addAll(
animationDigitalNetworkPlatform.configuration?.availableCountries?.flatMap {
Expand All @@ -93,32 +100,35 @@ class FetchOldEpisodesJob : AbstractJob {
if (limit != -1) {
episodes.groupBy { it.anime + it.releaseDateTime.toLocalDate().toString() }.forEach { (_, animeDayEpisodes) ->
if (animeDayEpisodes.size > limit) {
logger.warning("More than $limit episodes for ${animeDayEpisodes.first().anime} on ${animeDayEpisodes.first().releaseDateTime.toLocalDate()}, removing...")
log(emailLogs, Level.WARNING, "More than $limit episodes for ${animeDayEpisodes.first().anime} on ${animeDayEpisodes.first().releaseDateTime.toLocalDate()}, removing...")
episodes.removeAll(animeDayEpisodes)
return@forEach
}
}
}

logger.info("Found ${episodes.size} episodes, saving...")
log(emailLogs, Level.INFO, "Found ${episodes.size} episodes, saving...")
var realSaved = 0
val realSavedAnimes = mutableSetOf<String>()

episodes.sortedBy { it.releaseDateTime }.forEach { episode ->
val findByIdentifier = episodeVariantService.findByIdentifier(episode.getIdentifier())

if (findByIdentifier == null) {
realSavedAnimes.add(episode.anime)
realSavedAnimes.add(StringUtils.getShortName(episode.anime))
realSaved++
episodeVariantService.save(episode, false)
}
}

logger.info("Saved $realSaved episodes")
realSavedAnimes.forEach { logger.info("Updating $it...") }
log(emailLogs, Level.INFO, "Saved $realSaved episodes")

realSavedAnimes.forEach {
log(emailLogs, Level.INFO, "Updating $it...")
}

if (realSaved > 0) {
logger.info("Recalculating simulcasts...")
log(emailLogs, Level.INFO, "Recalculating simulcasts...")
animeService.recalculateSimulcasts()

MapCache.invalidate(
Expand All @@ -129,11 +139,23 @@ class FetchOldEpisodesJob : AbstractJob {
)
}

logger.info("Updating config to the next fetch date...")
log(emailLogs, Level.INFO, "Updating config to the next fetch date...")

config.propertyValue = from.toString()
configService.update(config)
traceActionService.createTraceAction(config, TraceAction.Action.UPDATE)
logger.info("Take ${(System.currentTimeMillis() - start) / 1000}s to check ${dates.size} dates")

log(emailLogs, Level.INFO, "Take ${(System.currentTimeMillis() - start) / 1000}s to check ${dates.size} dates")

try {
emailService.sendEmail(
requireNotNull(configCacheService.getValueAsString(ConfigPropertyKey.FETCH_OLD_EPISODES_EMAIL)),
"FetchOldEpisodesJob - ${dates.first()} to ${dates.last()}",
emailLogs.toString(),
)
} catch (e: Exception) {
logger.warning("Impossible to send email: ${e.message}")
}
}

private fun fetchAnimationDigitalNetwork(
Expand Down
2 changes: 1 addition & 1 deletion src/main/kotlin/fr/shikkanime/services/EmailService.kt
Original file line number Diff line number Diff line change
Expand Up @@ -57,7 +57,7 @@ class EmailService {
)
}

fun sendEmail(email: String, title: String, content: String, async : Boolean = true) {
fun sendEmail(email: String, title: String, content: String, async : Boolean = false) {
val emailHost = requireNotNull(configCacheService.getValueAsString(ConfigPropertyKey.EMAIL_HOST)) { "Email host config not found" }
val emailPort = configCacheService.getValueAsInt(ConfigPropertyKey.EMAIL_PORT)
require(emailPort != -1) { "Email port config not found" }
Expand Down
22 changes: 22 additions & 0 deletions src/main/resources/db/changelog/2024/09/07-changelog.xml
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
<?xml version="1.0" encoding="UTF-8"?>
<databaseChangeLog xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://www.liquibase.org/xml/ns/dbchangelog"
xsi:schemaLocation="http://www.liquibase.org/xml/ns/dbchangelog
https://www.liquibase.org/xml/ns/dbchangelog/dbchangelog-latest.xsd">
<property global="false" name="id" value="1727690914835"/>
<property global="false" name="author" value="Ziedelth"/>

<changeSet id="${id}-1" author="${author}" dbms="postgresql">
<preConditions onFail="MARK_RAN">
<sqlCheck expectedResult="0">SELECT COUNT(*)
FROM config
WHERE property_key = 'fetch_old_episodes_email'</sqlCheck>
</preConditions>

<insert tableName="config">
<column name="uuid" valueComputed="gen_random_uuid()"/>
<column name="property_key" value="fetch_old_episodes_email"/>
<column name="property_value" value=""/>
</insert>
</changeSet>
</databaseChangeLog>
1 change: 1 addition & 0 deletions src/main/resources/db/changelog/db.changelog-master.xml
Original file line number Diff line number Diff line change
Expand Up @@ -65,4 +65,5 @@
<include file="/db/changelog/2024/09/04-changelog.xml"/>
<include file="/db/changelog/2024/09/05-changelog.xml"/>
<include file="/db/changelog/2024/09/06-changelog.xml"/>
<include file="/db/changelog/2024/09/07-changelog.xml"/>
</databaseChangeLog>

0 comments on commit de8aab0

Please sign in to comment.