-
-
Notifications
You must be signed in to change notification settings - Fork 800
Expand file tree
/
Copy pathPageFragmentLoadState.kt
More file actions
291 lines (266 loc) · 12.6 KB
/
PageFragmentLoadState.kt
File metadata and controls
291 lines (266 loc) · 12.6 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
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
package org.wikipedia.page
import android.widget.Toast
import androidx.lifecycle.lifecycleScope
import kotlinx.coroutines.CoroutineExceptionHandler
import kotlinx.coroutines.MainScope
import kotlinx.coroutines.async
import kotlinx.coroutines.launch
import org.wikipedia.R
import org.wikipedia.WikipediaApp
import org.wikipedia.analytics.eventplatform.ArticleLinkPreviewInteractionEvent
import org.wikipedia.auth.AccountUtil
import org.wikipedia.bridge.CommunicationBridge
import org.wikipedia.bridge.JavaScriptActionHandler
import org.wikipedia.categories.db.Category
import org.wikipedia.database.AppDatabase
import org.wikipedia.dataclient.ServiceFactory
import org.wikipedia.dataclient.mwapi.MwQueryResponse
import org.wikipedia.dataclient.okhttp.OfflineCacheInterceptor
import org.wikipedia.dataclient.page.PageSummary
import org.wikipedia.history.HistoryEntry
import org.wikipedia.notifications.AnonymousNotificationHelper
import org.wikipedia.page.leadimages.LeadImagesHandler
import org.wikipedia.page.tabs.Tab
import org.wikipedia.settings.Prefs
import org.wikipedia.staticdata.UserTalkAliasData
import org.wikipedia.util.DateUtil
import org.wikipedia.util.UriUtil
import org.wikipedia.util.log.L
import org.wikipedia.views.ObservableWebView
import retrofit2.Response
import java.io.IOException
import java.time.Instant
import java.time.LocalDate
import java.time.ZoneId
class PageFragmentLoadState(private var model: PageViewModel,
private var fragment: PageFragment,
private var webView: ObservableWebView,
private var bridge: CommunicationBridge,
private var leadImagesHandler: LeadImagesHandler,
private var currentTab: Tab) {
fun load(pushBackStack: Boolean) {
if (pushBackStack && model.title != null && model.curEntry != null) {
// update the topmost entry in the backstack, before we start overwriting things.
updateCurrentBackStackItem()
currentTab.pushBackStackItem(PageBackStackItem(model.title!!, model.curEntry!!))
}
pageLoad()
}
fun loadFromBackStack() {
if (currentTab.backStack.isEmpty()) {
return
}
val item = currentTab.backStack[currentTab.backStackPosition]
// display the page based on the backstack item, stage the scrollY position based on
// the backstack item.
fragment.loadPage(item.title, item.historyEntry, false, item.scrollY)
L.d("Loaded page " + item.title.displayText + " from backstack")
}
fun updateCurrentBackStackItem() {
if (currentTab.backStack.isEmpty()) {
return
}
val item = currentTab.backStack[currentTab.backStackPosition]
item.scrollY = webView.scrollY
model.title?.let {
item.title.description = it.description
item.title.thumbUrl = it.thumbUrl
}
}
fun setTab(tab: Tab): Boolean {
val isDifferent = tab != currentTab
currentTab = tab
return isDifferent
}
fun goBack(): Boolean {
if (currentTab.canGoBack()) {
currentTab.moveBack()
if (!backStackEmpty()) {
loadFromBackStack()
return true
}
}
return false
}
fun goForward(): Boolean {
if (currentTab.canGoForward()) {
currentTab.moveForward()
loadFromBackStack()
return true
}
return false
}
fun backStackEmpty(): Boolean {
return currentTab.backStack.isEmpty()
}
fun onConfigurationChanged() {
leadImagesHandler.loadLeadImage()
bridge.execute(JavaScriptActionHandler.setTopMargin(leadImagesHandler.topMargin))
}
private fun commonSectionFetchOnCatch(caught: Throwable) {
if (!fragment.isAdded) {
return
}
fragment.requireActivity().invalidateOptionsMenu()
fragment.onPageLoadError(caught)
}
private fun pageLoad() {
model.title?.let { title ->
fragment.lifecycleScope.launch(CoroutineExceptionHandler { _, throwable ->
L.e("Page details network error: ", throwable)
commonSectionFetchOnCatch(throwable)
}) {
model.readingListPage = AppDatabase.instance.readingListPageDao().findPageInAnyList(title)
fragment.updateQuickActionsAndMenuOptions()
fragment.requireActivity().invalidateOptionsMenu()
fragment.callback()?.onPageUpdateProgressBar(true)
model.page = null
val delayLoadHtml = title.prefixedText.contains(":")
if (!delayLoadHtml) {
bridge.resetHtml(title)
}
if (title.namespace() === Namespace.SPECIAL) {
// Short-circuit the entire process of fetching the Summary, since Special: pages
// are not supported in RestBase.
bridge.resetHtml(title)
leadImagesHandler.loadLeadImage()
fragment.requireActivity().invalidateOptionsMenu()
fragment.onPageMetadataLoaded()
return@launch
}
val pageSummaryRequest = async {
ServiceFactory.getRest(title.wikiSite).getSummaryResponse(title.prefixedText, cacheControl = model.cacheControl.toString(),
saveHeader = if (model.isInReadingList) OfflineCacheInterceptor.SAVE_HEADER_SAVE else null,
langHeader = title.wikiSite.languageCode, titleHeader = UriUtil.encodeURL(title.prefixedText))
}
val makeWatchRequest = WikipediaApp.instance.isOnline && AccountUtil.isLoggedIn
val watchedRequest = async {
try {
if (makeWatchRequest) {
ServiceFactory.get(title.wikiSite)
.getWatchedStatusWithCategories(title.prefixedText)
} else if (WikipediaApp.instance.isOnline && !AccountUtil.isLoggedIn) {
AnonymousNotificationHelper.maybeGetAnonUserInfo(title.wikiSite)
} else {
MwQueryResponse()
}
} catch (_: IOException) {
L.w("Ignoring network error while fetching watched status.")
MwQueryResponse()
}
}
val categoriesRequest = async {
try {
if (!makeWatchRequest && WikipediaApp.instance.isOnline) {
ServiceFactory.get(title.wikiSite).getCategoriesProps(title.text)
} else {
MwQueryResponse()
}
} catch (_: IOException) {
L.w("Ignoring network error while fetching categories.")
MwQueryResponse()
}
}
val pageSummaryResponse = pageSummaryRequest.await()
val watchedResponse = watchedRequest.await()
val categoriesResponse = categoriesRequest.await()
val isWatched = watchedResponse.query?.firstPage()?.watched == true
val hasWatchlistExpiry = watchedResponse.query?.firstPage()?.hasWatchlistExpiry() == true
if (pageSummaryResponse.body() == null) {
throw RuntimeException("Summary response was invalid.")
}
val redirectedFrom = if (pageSummaryResponse.raw().priorResponse?.isRedirect == true) model.title?.displayText else null
createPageModel(pageSummaryResponse, isWatched, hasWatchlistExpiry)
if (OfflineCacheInterceptor.SAVE_HEADER_SAVE == pageSummaryResponse.headers()[OfflineCacheInterceptor.SAVE_HEADER]) {
showPageOfflineMessage(pageSummaryResponse.headers().getInstant("date"))
}
val categoryList = (categoriesResponse.query ?: watchedResponse.query)?.firstPage()?.categories?.map { category ->
Category(title = category.title, lang = title.wikiSite.languageCode)
}.orEmpty()
if (categoryList.isNotEmpty()) {
AppDatabase.instance.categoryDao().upsertAll(categoryList)
}
if (delayLoadHtml) {
bridge.resetHtml(title)
}
fragment.onPageMetadataLoaded(redirectedFrom)
if (AnonymousNotificationHelper.shouldCheckAnonNotifications(watchedResponse)) {
checkAnonNotifications(title)
}
}
}
}
private fun checkAnonNotifications(title: PageTitle) {
fragment.lifecycleScope.launch(CoroutineExceptionHandler { _, throwable ->
L.e(throwable)
}) {
val response = ServiceFactory.get(title.wikiSite)
.getLastModified(UserTalkAliasData.valueFor(title.wikiSite.languageCode) + ":" + Prefs.lastAnonUserWithMessages)
if (AnonymousNotificationHelper.anonTalkPageHasRecentMessage(response, title)) {
fragment.showAnonNotification()
}
}
}
private fun showPageOfflineMessage(dateHeader: Instant?) {
if (!fragment.isAdded || dateHeader == null) {
return
}
val localDate = LocalDate.ofInstant(dateHeader, ZoneId.systemDefault())
val dateStr = DateUtil.getDateString(localDate)
Toast.makeText(fragment.requireContext().applicationContext,
fragment.getString(R.string.page_offline_notice_last_date, dateStr),
Toast.LENGTH_LONG).show()
}
private fun createPageModel(response: Response<PageSummary>,
isWatched: Boolean,
hasWatchlistExpiry: Boolean) {
if (!fragment.isAdded || response.body() == null) {
return
}
val pageSummary = response.body()
val page = pageSummary?.toPage(model.title)
model.page = page
model.isWatched = isWatched
model.hasWatchlistExpiry = hasWatchlistExpiry
model.title = page?.title
model.title?.let { title ->
if (!response.raw().request.url.fragment.isNullOrEmpty()) {
title.fragment = response.raw().request.url.fragment
}
if (title.description.isNullOrEmpty()) {
WikipediaApp.instance.appSessionEvent.noDescription()
}
if (!title.isMainPage) {
title.displayText = page?.displayTitle.orEmpty()
}
title.thumbUrl = pageSummary?.thumbnailUrl
leadImagesHandler.loadLeadImage()
fragment.requireActivity().invalidateOptionsMenu()
// Update our tab list to prevent ZH variants issue.
WikipediaApp.instance.tabList.getOrNull(WikipediaApp.instance.tabCount - 1)?.setBackStackPositionTitle(title)
// Update our history entry, in case the Title was changed (i.e. normalized)
model.curEntry?.let {
val entry = HistoryEntry(
title,
it.source,
timestamp = it.timestamp
).apply {
referrer = it.referrer
prevId = it.prevId
}
model.curEntry = entry
MainScope().launch {
// Insert and/or update this history entry in the DB
AppDatabase.instance.historyEntryDao().upsert(entry).run {
model.curEntry?.id = this
}
// Update metadata in the DB
AppDatabase.instance.pageImagesDao().upsertForMetadata(entry, title.thumbUrl, title.description, pageSummary?.coordinates?.latitude, pageSummary?.coordinates?.longitude)
}
// And finally, count this as a page view.
WikipediaApp.instance.appSessionEvent.pageViewed(entry)
ArticleLinkPreviewInteractionEvent(title.wikiSite.dbName(), pageSummary?.pageId ?: 0, entry.source).logNavigate()
}
}
}
}