Skip to content
This repository has been archived by the owner on Sep 6, 2022. It is now read-only.

Commit

Permalink
fix teams cache not clearing when refresed
Browse files Browse the repository at this point in the history
  • Loading branch information
omarshaarawi committed Dec 8, 2021
1 parent 0d566fc commit 1e65fc9
Show file tree
Hide file tree
Showing 5 changed files with 111 additions and 135 deletions.
31 changes: 14 additions & 17 deletions build.gradle
Original file line number Diff line number Diff line change
@@ -1,11 +1,12 @@
import org.jetbrains.kotlin.gradle.dsl.KotlinCompile

plugins {
id 'org.jetbrains.kotlin.jvm' version '1.5.31'
id 'org.jetbrains.kotlin.plugin.serialization' version '1.5.31'
id 'org.jetbrains.kotlin.jvm' version '1.6.0'
id 'idea'
id 'org.jetbrains.kotlin.plugin.serialization' version '1.6.0'
id 'maven-publish'

}
sourceSets.main.kotlin.srcDirs = ['src']

group 'com.omarshaarawi.espnff'
version System.getenv("VERSION")
Expand All @@ -17,29 +18,25 @@ repositories {


dependencies {
implementation 'org.jetbrains.kotlin:kotlin-stdlib:1.5.31'
implementation 'org.jetbrains.kotlin:kotlin-stdlib:1.6.0'
implementation "com.jakewharton.retrofit:retrofit2-kotlinx-serialization-converter:0.8.0"
implementation "com.squareup.retrofit2:retrofit:2.9.0"
implementation 'com.google.code.gson:gson:2.8.9'
implementation 'io.github.microutils:kotlin-logging-jvm:2.0.11'
implementation 'io.github.microutils:kotlin-logging-jvm:2.1.0'
implementation 'org.slf4j:slf4j-simple:1.7.32'
implementation "org.jetbrains.kotlinx:kotlinx-serialization-json:1.3.0"
}
implementation 'org.jetbrains.kotlinx:kotlinx-serialization-json:1.3.1'

testImplementation 'io.kotest:kotest-runner-junit5:5.0.1'
testImplementation 'io.kotest:kotest-assertions-core:5.0.1'
testImplementation 'io.kotest:kotest-property:5.0.1'

tasks.withType(KotlinCompile).configureEach { task ->
task.kotlinOptions {
jvmTarget = JavaVersion.VERSION_16
freeCompilerArgs += [
'-Xopt-in=kotlin.RequiresOptIn',
'-Xjsr305=strict',
]
}
}

compileTestKotlin {
compileKotlin {
kotlinOptions {
jvmTarget = JavaVersion.VERSION_16
freeCompilerArgs += [
'-Xopt-in=kotlinx.serialization.ExperimentalSerializationApi',
'-Xjsr305=strict -Xopt-in=kotlinx.serialization.ExperimentalSerializationApi'
]
}
}
Expand Down
14 changes: 5 additions & 9 deletions src/main/kotlin/com/espn/ff/base/BaseLeague.kt
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@ open class BaseLeague(leagueId: Int, year: Int, swid: String, espnS2: String) {

lateinit var settings: BaseSettings
var currentWeek by Delegates.notNull<Int>()
var firstScoringPeriod by Delegates.notNull<Int>()
private var firstScoringPeriod by Delegates.notNull<Int>()
var scoringPeriodId by Delegates.notNull<Int>()
var currentMatchupPeriod by Delegates.notNull<Int>()
private val logger: KLogger = KotlinLogging.logger {}
Expand All @@ -30,13 +30,12 @@ open class BaseLeague(leagueId: Int, year: Int, swid: String, espnS2: String) {
init {
this.leagueId = leagueId
this.year = year
this.teams = mutableListOf()
this.teams = emptyList<Team>().toMutableList()
this.draft = emptyList()
this.playerMap = mutableMapOf()
this.espnRequest = EspnRequests(year, leagueId, swid, espnS2, logger)
}


open fun fetchLeague(): JsonObject? {
val data = espnRequest.getLeague()
this.currentMatchupPeriod = data?.get("status")!!.jsonObject["currentMatchupPeriod"]!!.toString().toInt()
Expand All @@ -62,6 +61,7 @@ open class BaseLeague(leagueId: Int, year: Int, swid: String, espnS2: String) {
}

open fun fetchTeams(data: JsonObject) {
teams.clear()
val teamData = data["teams"]
val members = data["members"]
val schedule = data["schedule"]
Expand All @@ -81,8 +81,6 @@ open class BaseLeague(leagueId: Int, year: Int, swid: String, espnS2: String) {
newMember = member
break
}


}


Expand All @@ -108,12 +106,10 @@ open class BaseLeague(leagueId: Int, year: Int, swid: String, espnS2: String) {
val data = this.espnRequest.getProPlayers()

for (player in data.jsonArray) {
this.playerMap[player.jsonObject["id"].toString()] =
player.jsonObject["fullName"].toString()
this.playerMap[player.jsonObject["id"].toString()] = player.jsonObject["fullName"].toString()

if (player.jsonObject["fullName"].toString() !in this.playerMap) {
this.playerMap[player.jsonObject["fullName"].toString()] =
player.jsonObject["id"].toString()
this.playerMap[player.jsonObject["fullName"].toString()] = player.jsonObject["id"].toString()
}
}
}
Expand Down
32 changes: 10 additions & 22 deletions src/main/kotlin/com/espn/ff/model/League.kt
Original file line number Diff line number Diff line change
Expand Up @@ -79,7 +79,6 @@ class League(leagueId: Int, year: Int, swid: String, espnS2: String) : BaseLeagu
val data = super.fetchLeague()
this.nflWeek = data!!["status"]!!.jsonObject["latestScoringPeriod"]!!
this.fetchTeams(data)

}

fun loadRosterWeek(week: Int) {
Expand Down Expand Up @@ -204,6 +203,7 @@ class League(leagueId: Int, year: Int, swid: String, espnS2: String) : BaseLeagu
}
return null
}

fun recentActivity(size: Int = 25, msgType: String = ""): MutableList<Any> {
var msgTypes: List<Any> = listOf(178, 180, 179, 239, 181, 244)

Expand All @@ -219,21 +219,13 @@ class League(leagueId: Int, year: Int, swid: String, espnS2: String) : BaseLeagu
"value" to listOf(
"ACTIVITY_TRANSACTIONS"
)
),
"limit" to size,
"limitPerMessageSet" to mapOf(
), "limit" to size, "limitPerMessageSet" to mapOf(
"value" to 25
),
"offset" to 0,
"sortMessageDate" to mapOf(
"sortPriority" to 1,
"sortAsc" to false
),
"sortFor" to mapOf(
"sortPriority" to 2,
"sortAsc" to false
),
"filterIncludeMessageTypeIds" to mapOf(
), "offset" to 0, "sortMessageDate" to mapOf(
"sortPriority" to 1, "sortAsc" to false
), "sortFor" to mapOf(
"sortPriority" to 2, "sortAsc" to false
), "filterIncludeMessageTypeIds" to mapOf(
"value" to msgTypes
)
)
Expand All @@ -248,9 +240,7 @@ class League(leagueId: Int, year: Int, swid: String, espnS2: String) : BaseLeagu


val data = this.espnRequest.leagueGet(
extend = "/communication/",
views = views,
headers = headers
extend = "/communication/", views = views, headers = headers
).jsonObject["topics"]!!.jsonArray
for (topic in data) {
activity.add(Activity(topic, this::getTeamData, this::playerInfo))
Expand Down Expand Up @@ -455,10 +445,8 @@ class League(leagueId: Int, year: Int, swid: String, espnS2: String) : BaseLeagu
"players" to mapOf(
"filterIds" to mapOf(
"value" to listOf(tempPlayerId),
),
"filterStatsForTopScoringPeriodIds" to mapOf(
"value" to 16,
"additionalValue" to listOf("00${this.year}", "10${this.year}")
), "filterStatsForTopScoringPeriodIds" to mapOf(
"value" to 16, "additionalValue" to listOf("00${this.year}", "10${this.year}")
)

)
Expand Down
92 changes: 5 additions & 87 deletions src/main/kotlin/com/espn/ff/service/EspnClient.kt
Original file line number Diff line number Diff line change
@@ -1,14 +1,9 @@
package com.espn.ff.service

import com.espn.ff.util.EspnConstants
import com.google.gson.Gson
import com.jakewharton.retrofit2.converter.kotlinx.serialization.asConverterFactory
import kotlinx.serialization.ExperimentalSerializationApi
import kotlinx.serialization.json.Json
import kotlinx.serialization.json.JsonElement
import kotlinx.serialization.json.JsonObject
import kotlinx.serialization.json.jsonObject
import mu.KLogger
import okhttp3.MediaType
import okhttp3.OkHttpClient
import retrofit2.Retrofit
Expand All @@ -19,20 +14,15 @@ object EspnClient {
private val contentType = MediaType.get("application/json")

private val json = Json {
ignoreUnknownKeys = true; allowStructuredMapKeys = true; prettyPrint =
true
ignoreUnknownKeys = true; allowStructuredMapKeys = true; prettyPrint = true
}

@OptIn(ExperimentalSerializationApi::class)
fun createEspnService(cookies: String): EspnService {
val retrofit = Retrofit.Builder()
.addConverterFactory((json.asConverterFactory(contentType)))
.baseUrl(EspnConstants.FANTASY_BASE_ENDPOINT)
.client(OkHttpClient.Builder().addInterceptor { chain ->
chain.request().newBuilder().addHeader("Cookie", cookies).build()
.let { chain.proceed(it) }
}.build())
.build()
val retrofit = Retrofit.Builder().addConverterFactory((json.asConverterFactory(contentType)))
.baseUrl(EspnConstants.FANTASY_BASE_ENDPOINT).client(OkHttpClient.Builder().addInterceptor { chain ->
chain.request().newBuilder().addHeader("Cookie", cookies).build().let { chain.proceed(it) }
}.build()).build()
return retrofit.create(EspnService::class.java)
}

Expand All @@ -49,76 +39,4 @@ object EspnClient {
throw Exception()
}
}


}

class EspnRequests(year: Int, leagueId: Int, swid: String, espnS2: String, logger: KLogger) {
val cookies = "SWID=$swid; espn_s2=$espnS2"
val espnEndpoints by lazy { EspnClient.createEspnService(cookies) }

var leagueEndpoint = "ffl"
var endpoint: String = "ffl/seasons/${year}"
val gson = Gson()

init {
leagueEndpoint = if (year < 2018) {
"${this.leagueEndpoint}leagueHistory/$leagueId?seasonId=$year"
} else {
"${this.leagueEndpoint}/seasons/$year/segments/0/leagues/$leagueId"
}
}

fun leagueGet(
views: List<String> = emptyList(),
params: Map<String, String> = emptyMap(),
headers: Map<String, String> = emptyMap(),
extend: String = "",
): JsonObject {
val endpoint = this.leagueEndpoint + extend
val r = espnEndpoints.get(endpoint, views, params, headers).execute()
EspnClient.checkRequestStatus(r.code())

return r.body()!!.jsonObject

}

private fun get(
views: List<String> = emptyList(),
params: Map<String, String> = emptyMap(),
headers: Map<String, String> = emptyMap(),
extend: String = "",
): JsonElement {
val endpoint = this.endpoint + extend
val r = espnEndpoints.get(endpoint, views, params, headers).execute()
EspnClient.checkRequestStatus(r.code())
return r.body()!!
}

fun getLeague(): JsonObject? {
val views = listOf(
"mTeam", "mSchedule", "mRoster", "mMatchup", "mSettings"
)
return leagueGet(views)
}

fun getProSchedules(): JsonElement {
val views = listOf("proTeamSchedules_wl")
return get(views)
}

fun getProPlayers(): JsonElement {
val views = listOf("players_wl")
val filters = mapOf(
"filterActive" to mapOf("value" to true)
)
val headers = mapOf("x-fantasy-filter" to gson.toJson(filters))

return get(views = views, headers = headers, extend = "/players")
}

fun getLeagueDraft(): JsonObject? {
val views = listOf("mDraftDetail")
return leagueGet(views)
}
}
77 changes: 77 additions & 0 deletions src/main/kotlin/com/espn/ff/service/EspnRequests.kt
Original file line number Diff line number Diff line change
@@ -0,0 +1,77 @@
package com.espn.ff.service

import com.google.gson.Gson
import kotlinx.serialization.json.JsonElement
import kotlinx.serialization.json.JsonObject
import kotlinx.serialization.json.jsonObject
import mu.KLogger

class EspnRequests(year: Int, leagueId: Int, swid: String, espnS2: String, logger: KLogger) {
private val cookies = "SWID=$swid; espn_s2=$espnS2"
private val espnEndpoints by lazy { EspnClient.createEspnService(cookies) }

var leagueEndpoint = "ffl"
var endpoint: String = "ffl/seasons/${year}"
private val gson = Gson()

init {
leagueEndpoint = if (year < 2018) {
"${this.leagueEndpoint}leagueHistory/$leagueId?seasonId=$year"
} else {
"${this.leagueEndpoint}/seasons/$year/segments/0/leagues/$leagueId"
}
}

fun leagueGet(
views: List<String> = emptyList(),
params: Map<String, String> = emptyMap(),
headers: Map<String, String> = emptyMap(),
extend: String = "",
): JsonObject {
val endpoint = this.leagueEndpoint + extend
val r = espnEndpoints.get(endpoint, views, params, headers).execute()
EspnClient.checkRequestStatus(r.code())

return r.body()!!.jsonObject

}

private fun get(
views: List<String> = emptyList(),
params: Map<String, String> = emptyMap(),
headers: Map<String, String> = emptyMap(),
extend: String = "",
): JsonElement {
val endpoint = this.endpoint + extend
val r = espnEndpoints.get(endpoint, views, params, headers).execute()
EspnClient.checkRequestStatus(r.code())
return r.body()!!
}

fun getLeague(): JsonObject? {
val views = listOf(
"mTeam", "mSchedule", "mRoster", "mMatchup", "mSettings"
)
return leagueGet(views)
}

fun getProSchedules(): JsonElement {
val views = listOf("proTeamSchedules_wl")
return get(views)
}

fun getProPlayers(): JsonElement {
val views = listOf("players_wl")
val filters = mapOf(
"filterActive" to mapOf("value" to true)
)
val headers = mapOf("x-fantasy-filter" to gson.toJson(filters))

return get(views = views, headers = headers, extend = "/players")
}

fun getLeagueDraft(): JsonObject? {
val views = listOf("mDraftDetail")
return leagueGet(views)
}
}

0 comments on commit 1e65fc9

Please sign in to comment.