-
-
Notifications
You must be signed in to change notification settings - Fork 800
Expand file tree
/
Copy pathHomeViewModel.kt
More file actions
212 lines (178 loc) · 7.95 KB
/
HomeViewModel.kt
File metadata and controls
212 lines (178 loc) · 7.95 KB
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
package org.wikipedia.feed
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import kotlinx.coroutines.CoroutineExceptionHandler
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.asStateFlow
import kotlinx.coroutines.flow.update
import kotlinx.coroutines.launch
import org.wikipedia.WikipediaApp
import org.wikipedia.dataclient.ServiceFactory
import org.wikipedia.dataclient.page.PageSummary
import org.wikipedia.feed.image.FeaturedImage
import org.wikipedia.feed.news.NewsItem
import org.wikipedia.feed.onthisday.OnThisDay
import org.wikipedia.feed.personalization.feedpreference.FeedPreferenceType
import org.wikipedia.feed.topread.TopRead
import org.wikipedia.settings.Prefs
import java.time.LocalDate
enum class HomeTab { COMMUNITY, FOR_YOU }
data class DayContent(
val age: Int,
val date: LocalDate,
val featuredArticle: PageSummary? = null,
val news: List<NewsItem> = emptyList(),
val topRead: TopRead? = null,
val featuredImage: FeaturedImage? = null,
val onThisDay: List<OnThisDay.Event> = emptyList()
)
sealed class ForYouModule {
abstract val pages: List<PageSummary>
data class BasedOnReadingHistory(override val pages: List<PageSummary>) : ForYouModule()
data class BasedOnLocation(override val pages: List<PageSummary>) : ForYouModule()
data class BasedOnInterests(val interest: String, override val pages: List<PageSummary>) : ForYouModule()
}
data class CommunityContentState(
val days: List<DayContent> = emptyList(),
val isInitialLoading: Boolean = false,
val isLoadingMore: Boolean = false,
val error: Throwable? = null,
val canLoadMore: Boolean = true
)
data class ForYouContentState(
val modules: List<ForYouModule> = emptyList(),
val isInitialLoading: Boolean = false,
val isLoadingMore: Boolean = false,
val error: Throwable? = null,
val canLoadMore: Boolean = true
)
class HomeViewModel : ViewModel() {
val wikiSite get() = WikipediaApp.instance.wikiSite
private val _selectedTab = MutableStateFlow(
if (Prefs.exploreFeedPreferenceSelection == FeedPreferenceType.PERSONALIZED) HomeTab.FOR_YOU else HomeTab.COMMUNITY
)
val selectedTab = _selectedTab.asStateFlow()
private val _communityState = MutableStateFlow(CommunityContentState())
val communityState = _communityState.asStateFlow()
private val _forYouState = MutableStateFlow(ForYouContentState())
val forYouState = _forYouState.asStateFlow()
// "age" in days from today. 0 = today, 1 = yesterday, etc.
private var nextCommunityAge = 0
// Batch counter for "For you" recommendations.
private var forYouBatchIndex = 0
private val communityHandler = CoroutineExceptionHandler { _, throwable ->
_communityState.value = _communityState.value.copy(
isInitialLoading = false,
isLoadingMore = false,
error = throwable
)
}
private val forYouHandler = CoroutineExceptionHandler { _, throwable ->
_forYouState.value = _forYouState.value.copy(
isInitialLoading = false,
isLoadingMore = false,
error = throwable
)
}
init {
if (_selectedTab.value == HomeTab.COMMUNITY) {
loadCommunityContent()
} else {
loadForYouContent()
}
}
fun refreshCommunityContent() {
nextCommunityAge = 0
_communityState.update { CommunityContentState() }
loadCommunityContent()
}
fun refreshForYouContent() {
forYouBatchIndex = 0
_forYouState.update { ForYouContentState() }
loadForYouContent()
}
fun selectTab(tab: HomeTab) {
_selectedTab.value = tab
if (tab == HomeTab.FOR_YOU &&
_forYouState.value.modules.isEmpty() &&
!_forYouState.value.isInitialLoading
) {
loadForYouContent()
}
}
/**
* Loads the next day's community content (today on first call, then progressively older).
* Safe to call as a retry — the age only advances after a successful fetch.
*/
fun loadCommunityContent() {
if (_communityState.value.isInitialLoading || _communityState.value.isLoadingMore) return
viewModelScope.launch(communityHandler) {
val isInitial = _communityState.value.days.isEmpty()
_communityState.value = _communityState.value.copy(
isInitialLoading = isInitial,
isLoadingMore = !isInitial,
error = null
)
val age = nextCommunityAge
val date = LocalDate.now().minusDays(nextCommunityAge.toLong())
val content = ServiceFactory.getRest(wikiSite)
.getFeedFeatured(date.year.toString(), "%02d".format(date.monthValue), "%02d".format(date.dayOfMonth), wikiSite.languageCode)
val dayContent = DayContent(
age = age,
date = date,
featuredArticle = content.tfa,
news = content.news.orEmpty(),
topRead = content.topRead,
featuredImage = content.potd,
onThisDay = content.onthisday.orEmpty()
)
// Advance age only after success, so retry on failure re-fetches the same day.
nextCommunityAge = age + 1
_communityState.value = _communityState.value.copy(
days = _communityState.value.days + dayContent,
isInitialLoading = false,
isLoadingMore = false,
error = null,
canLoadMore = true
)
}
}
/**
* Loads the next batch of personalized recommendations for the "For you" tab.
* Safe to call as a retry — the batch index only advances after a successful fetch.
*/
fun loadForYouContent() {
if (_forYouState.value.isInitialLoading || _forYouState.value.isLoadingMore) return
viewModelScope.launch(forYouHandler) {
val isInitial = _forYouState.value.modules.isEmpty()
_forYouState.value = _forYouState.value.copy(
isInitialLoading = isInitial,
isLoadingMore = !isInitial,
error = null
)
val newModules = fetchForYouModules(forYouBatchIndex)
// Advance batch index only after success.
forYouBatchIndex++
_forYouState.value = _forYouState.value.copy(
modules = _forYouState.value.modules + newModules,
isInitialLoading = false,
isLoadingMore = false,
error = null,
canLoadMore = newModules.isNotEmpty()
)
}
}
private suspend fun fetchForYouModules(batchIndex: Int): List<ForYouModule> {
val sampleImageUrls = listOf(
"https://upload.wikimedia.org/wikipedia/commons/thumb/2/25/SW_Hullathy_Gram_Panchayat_Villages_Nilgiris_Nov24_A7CR_05293.jpg/1280px-SW_Hullathy_Gram_Panchayat_Villages_Nilgiris_Nov24_A7CR_05293.jpg",
"https://upload.wikimedia.org/wikipedia/commons/thumb/1/10/Color_of_Friendship.jpg/1280px-Color_of_Friendship.jpg",
"https://upload.wikimedia.org/wikipedia/commons/thumb/d/dd/MAP_Expo_Empereur_Ojin_Poup%C3%A9e_03_01_2012.jpg/1280px-MAP_Expo_Empereur_Ojin_Poup%C3%A9e_03_01_2012.jpg",
"https://upload.wikimedia.org/wikipedia/commons/thumb/a/a7/Sachsenheim_-_Ochsenbach_-_Geigersberg_-_n%C3%B6rdlicher_Teil_von_SSO_im_M%C3%A4rz.jpg/1280px-Sachsenheim_-_Ochsenbach_-_Geigersberg_-_n%C3%B6rdlicher_Teil_von_SSO_im_M%C3%A4rz.jpg",
"https://upload.wikimedia.org/wikipedia/commons/thumb/0/02/Templo_de_Rams%C3%A9s_II%2C_Abu_Simbel%2C_Egipto%2C_2022-04-02%2C_DD_26-28_HDR.jpg/1280px-Templo_de_Rams%C3%A9s_II%2C_Abu_Simbel%2C_Egipto%2C_2022-04-02%2C_DD_26-28_HDR.jpg",
)
val modules = sampleImageUrls.map {
ForYouModule.BasedOnInterests("Art", listOf(PageSummary("", "", "", "", thumbnail = it, "")))
}
return modules
}
}