forked from famoser/Mensa
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathETHMensaProvider.kt
319 lines (268 loc) · 10.2 KB
/
ETHMensaProvider.kt
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
package ch.famoser.mensa.services.providers
import android.annotation.SuppressLint
import android.util.Log
import ch.famoser.mensa.models.Location
import ch.famoser.mensa.models.Mensa
import ch.famoser.mensa.models.Menu
import ch.famoser.mensa.services.IAssetService
import ch.famoser.mensa.services.ICacheService
import ch.famoser.mensa.services.SerializationService
import kotlinx.serialization.Serializable
import java.net.URI
import java.net.URL
import java.util.*
import kotlin.collections.ArrayList
import kotlin.collections.HashMap
class ETHMensaProvider(
private val cacheService: ICacheService,
private val assetService: IAssetService,
private val serializationService: SerializationService
) : AbstractMensaProvider(cacheService) {
companion object {
const val CACHE_PROVIDER_PREFIX = "eth"
const val MEAL_TIME_LUNCH = "lunch"
const val MEAL_TIME_DINNER = "dinner"
}
private val mensaMap: MutableMap<Mensa, EthMensa> = HashMap()
fun getMenus(time: String, date: Date, language: Language, ignoreCache: Boolean)
: List<Mensa> {
try {
val menuByMensaIds = getMenuByMensaId(date, ignoreCache, time, language)
for ((mensa, ethzMensa) in mensaMap) {
val menus = menuByMensaIds[ethzMensa.getMapId()]
if (menus != null) {
mensa.replaceMenus(menus)
}
}
} catch (ex: Exception) {
ex.printStackTrace()
}
return mensaMap.keys.toList()
}
private fun getMenuByMensaId(
date: Date,
ignoreCache: Boolean,
time: String,
language: Language
): Map<String, List<Menu>> {
val languageString = languageToString(language)
if (!ignoreCache) {
val menuByMensaIds = getMenuByMensaIdFromCache(date, time, languageString)
if (menuByMensaIds != null) {
return menuByMensaIds
}
}
val menuByMensaIds = getMensaMenusFromSearchApi(languageString, date, time)
for ((_, ethzMensa) in mensaMap) {
val menus = menuByMensaIds[ethzMensa.getMapId()]
if (menus == null && ethzMensa.timeSlug == time) {
menuByMensaIds[ethzMensa.getMapId()] =
getMensaMenuFromApi(languageString, date, time, ethzMensa)
}
if (menus !== null && menus.any() && menus.all { it.isSomeEmpty() }) {
val fallbackLanguage = fallbackLanguage(language)
val fallbackLanguageString = languageToString(fallbackLanguage)
val fallbackMenus = getMensaMenuFromApi(fallbackLanguageString, date, time, ethzMensa)
val newMenus = ArrayList<Menu>(menus);
var i = 0;
while (i < newMenus.size && i < fallbackMenus.size) {
newMenus[i] = newMenus[i].mergeWithFallback(fallbackMenus[i]);
i++;
}
menuByMensaIds[ethzMensa.getMapId()] = newMenus;
}
}
val cacheKey = getMensaIdCacheKey(date, time, languageString)
cacheService.saveMensaIds(cacheKey, menuByMensaIds.keys.toList())
for ((mensaId, menus) in menuByMensaIds) {
cacheMenus(CACHE_PROVIDER_PREFIX, mensaId, date, languageString, menus)
}
return menuByMensaIds
}
private fun getMenuByMensaIdFromCache(
date: Date,
source: String,
language: String
): Map<String, List<Menu>>? {
val cacheKey = getMensaIdCacheKey(date, source, language)
val impactedMensas = cacheService.readMensaIds(cacheKey) ?: return null
val menuByMensaId = HashMap<String, List<Menu>>()
for (mensaId in impactedMensas) {
val menus = tryGetMenusFromCache(CACHE_PROVIDER_PREFIX, mensaId, date, language)
if (menus != null) {
menuByMensaId[mensaId] = menus
}
}
return menuByMensaId
}
private fun getMensaIdCacheKey(date: Date, source: String, language: String): String {
val dateSlug = getDateTimeString(date)
return "$CACHE_PROVIDER_PREFIX.$source.$dateSlug.$language"
}
@SuppressLint("UseSparseArrays")
private fun getMensaMenusFromSearchApi(
language: String,
date: Date,
time: String
): MutableMap<String, List<Menu>> {
var apiMensas: List<ApiMensaSearch> = ArrayList();
val dateSlug = getDateTimeString(date)
val url =
URL("https://www.webservices.ethz.ch/gastro/v1/RVRI/Q1E1/meals/$language/$dateSlug/$time?language=$language")
try {
val json = url.readText()
apiMensas = serializationService.deserializeList(json)
} catch (e: java.lang.Exception) {
Log.e("ETHMensaProvider", "request for mensa search failed: $url", e);
}
val menuByMensaIds = HashMap<String, List<Menu>>()
for (apiMensa in apiMensas) {
val menus =
apiMensa.meals.map { parseApiMenu(it) }.filter { !isNoMenuNotice(it, language) }
menuByMensaIds[apiMensa.id.toString() + "_" + time] = menus
}
return menuByMensaIds
}
private fun isNoMenuNotice(menu: Menu, language: String): Boolean {
val invalidMenus = when (language) {
"en" -> {
arrayOf(
"We look forward to serving you this menu again soon!",
"is closed",
"Closed"
)
}
"de" -> {
arrayOf(
"Dieses Menu servieren wir Ihnen gerne bald wieder!",
"geschlossen",
"Geschlossen"
)
}
else -> {
arrayOf()
}
}
return invalidMenus.any { menu.description.contains(it) || menu.title == it }
}
@SuppressLint("UseSparseArrays")
private fun getMensaMenuFromApi(
language: String,
date: Date,
time: String,
mensa: EthMensa
): List<Menu> {
val dateSlug = getDateTimeString(date)
val url =
URL("https://www.webservices.ethz.ch/gastro/v1/RVRI/Q1E1/mensas/${mensa.idSlug}/$language/menus/daily/$dateSlug/$time?language=$language")
try {
val json = url.readText()
val apiMensa = serializationService.deserialize<ApiMensa>(json)
return apiMensa.menu.meals.map { parseApiMenu(it) }
} catch (e: java.lang.Exception) {
Log.e("ETHMensaProvider", "request for single mensa ${mensa.title} failed: $url", e);
return ArrayList();
}
}
private fun parseApiMenu(apiMeal: ApiMeal): Menu {
var label = apiMeal.label
var descriptionLines = apiMeal.description
if (label.isEmpty() && apiMeal.description.isNotEmpty()) {
label = apiMeal.description.first()
if (descriptionLines.size > 1) {
descriptionLines = descriptionLines.subList(1, descriptionLines.size)
} else {
descriptionLines = ArrayList()
}
}
val description = normalizeText(descriptionLines.joinToString(separator = "\n").trim())
val prices = apiMeal.prices
.run { arrayOf(student, staff, extern) }
.filterNot { it.isNullOrEmpty() || it == "NaN" }
.filterNotNull()
.toTypedArray()
val allergens = apiMeal.allergens
.fold(ArrayList<String>(), { acc, apiAllergen -> acc.add(apiAllergen.label); acc })
.joinToString(separator = ", ")
return Menu(
label,
description,
prices,
allergens
)
}
override fun getLocations(): List<Location> {
val json: String = assetService.readStringFile("eth/locations.json") ?: return ArrayList()
val ethLocations = serializationService.deserializeList<EthLocation>(json)
return ethLocations.map { ethLocation ->
Location(ethLocation.title, ethLocation.mensas.map {
val mensaId = UUID.fromString(it.id)
val imageName = it.infoUrlSlug.substring(it.infoUrlSlug.indexOf("/") + 1)
val mensa = Mensa(
mensaId,
it.title,
it.mealTime,
URI("https://ethz.ch/de/campus/erleben/gastronomie-und-einkaufen/gastronomie/restaurants-und-cafeterias/" + it.infoUrlSlug),
"eth/images/$imageName.jpg"
)
mensaMap[mensa] = it
mensa
})
}
}
@Serializable
data class ApiMensaSearch(
val id: Int,
val mensa: String,
val daytime: String,
val hours: ApiHours,
val meals: List<ApiMeal>
)
@Serializable
data class ApiMensa(
val id: Int,
val mensa: String,
val daytime: String,
val hours: ApiHours,
val menu: ApiMenu
)
@Serializable
data class ApiMenu(
val date: String,
val day: String,
val meals: List<ApiMeal>
)
@Serializable
data class ApiHours(val opening: List<ApiOpening>, val mealtime: List<ApiMealtime>)
@Serializable
data class ApiOpening(val from: String, val to: String, val type: String)
@Serializable
data class ApiMealtime(val from: String, val to: String, val type: String)
@Serializable
data class ApiMeal(
val id: Int,
val label: String,
val description: List<String>,
val prices: ApiPrices,
val allergens: List<ApiAllergen>
)
@Serializable
data class ApiPrices(val student: String?, val staff: String?, val extern: String?)
@Serializable
data class ApiAllergen(val allergen_id: Int, val label: String)
@Serializable
data class EthLocation(val title: String, val mensas: List<EthMensa>)
@Serializable
data class EthMensa(
val id: String,
val title: String,
val mealTime: String,
val idSlug: Int,
val timeSlug: String,
val infoUrlSlug: String
) {
fun getMapId(): String {
return idSlug.toString() + "_" + timeSlug
}
}
}