-
-
Notifications
You must be signed in to change notification settings - Fork 800
Expand file tree
/
Copy pathEditSectionViewModel.kt
More file actions
151 lines (132 loc) · 6.31 KB
/
EditSectionViewModel.kt
File metadata and controls
151 lines (132 loc) · 6.31 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
package org.wikipedia.edit
import androidx.lifecycle.SavedStateHandle
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import kotlinx.coroutines.CoroutineExceptionHandler
import kotlinx.coroutines.Job
import kotlinx.coroutines.delay
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.asStateFlow
import kotlinx.coroutines.launch
import org.wikipedia.Constants
import org.wikipedia.auth.AccountUtil
import org.wikipedia.csrf.CsrfTokenClient
import org.wikipedia.dataclient.ServiceFactory
import org.wikipedia.dataclient.mwapi.MwServiceError
import org.wikipedia.dataclient.okhttp.OkHttpConnectionFactory
import org.wikipedia.page.PageTitle
import org.wikipedia.util.Resource
import org.wikipedia.util.StringUtil
import org.wikipedia.util.log.L
class EditSectionViewModel(savedStateHandle: SavedStateHandle) : ViewModel() {
var pageTitle = savedStateHandle.get<PageTitle>(Constants.ARG_TITLE)!!
var invokeSource = savedStateHandle.get<Constants.InvokeSource>(Constants.INTENT_EXTRA_INVOKE_SOURCE)!!
var sectionID = savedStateHandle[EditSectionActivity.EXTRA_SECTION_ID] ?: -1
var sectionAnchor = savedStateHandle.get<String>(EditSectionActivity.EXTRA_SECTION_ANCHOR)
var textToHighlight = savedStateHandle.get<String>(EditSectionActivity.EXTRA_HIGHLIGHT_TEXT)
var sectionWikitext: String? = null
var sectionWikitextOriginal: String? = null
var tempAccountsEnabled = true
var editingAllowed = false
val editNotices = mutableListOf<String>()
// Current revision of the article, to be passed back to the server to detect possible edit conflicts.
private var currentRevision: Long = 0
private var clientJob: Job? = null
private val _fetchSectionTextState = MutableStateFlow(Resource<MwServiceError?>())
val fetchSectionTextState = _fetchSectionTextState.asStateFlow()
private val _postEditState = MutableStateFlow(Resource<Edit>())
val postEditState = _postEditState.asStateFlow()
private val _waitForRevisionState = MutableStateFlow(Resource<Long>())
val waitForRevisionState = _waitForRevisionState.asStateFlow()
init {
fetchSectionText()
}
fun fetchSectionText() {
viewModelScope.launch(CoroutineExceptionHandler { _, throwable ->
_fetchSectionTextState.value = Resource.Error(throwable)
}) {
_fetchSectionTextState.value = Resource.Loading()
val infoResponse = ServiceFactory.get(pageTitle.wikiSite).getWikiTextForSectionWithInfo(pageTitle.prefixedText, if (sectionID >= 0) sectionID else null)
tempAccountsEnabled = infoResponse.query?.autoCreateTempUser?.enabled == true
infoResponse.query?.firstPage()?.let { firstPage ->
val rev = firstPage.revisions.first()
pageTitle = PageTitle(firstPage.title, pageTitle.wikiSite).apply {
this.displayText = pageTitle.displayText
}
sectionWikitext = rev.contentMain
sectionWikitextOriginal = sectionWikitext
currentRevision = rev.revId
editNotices.clear()
// Populate edit notices, but filter out anonymous edit warnings, since
// we show that type of warning ourselves when previewing.
editNotices.addAll(firstPage.getEditNotices()
.filterKeys { key -> (key.startsWith("editnotice") && !key.endsWith("-notext")) }
.values.filter { str -> StringUtil.fromHtml(str).trim().isNotEmpty() })
val editError = firstPage.getErrorForAction("edit")
var error: MwServiceError? = null
if (editError.isEmpty()) {
editingAllowed = true
} else {
error = editError[0]
}
_fetchSectionTextState.value = Resource.Success(error)
}
}
}
fun postEdit(isMinorEdit: Boolean?,
watchThisPage: String,
summaryText: String,
editSectionText: String,
editTags: String,
captchaId: String?,
captchaWord: String?) {
clientJob?.cancel()
clientJob = viewModelScope.launch(CoroutineExceptionHandler { _, throwable ->
L.e(throwable)
_postEditState.value = Resource.Error(throwable)
}) {
_postEditState.value = Resource.Loading()
val csrfToken = CsrfTokenClient.getToken(pageTitle.wikiSite)
val result = ServiceFactory.get(pageTitle.wikiSite).postEditSubmit(
title = pageTitle.prefixedText,
section = if (sectionID >= 0) sectionID.toString() else null,
newSectionTitle = null,
summary = summaryText,
user = AccountUtil.assertUser,
text = editSectionText,
appendText = null,
baseRevId = currentRevision,
token = csrfToken,
captchaId = captchaId,
captchaWord = captchaWord,
minor = isMinorEdit,
watchlist = watchThisPage,
tags = editTags
)
_postEditState.value = Resource.Success(result)
}
}
fun waitForRevisionUpdate(newRevision: Long) {
viewModelScope.launch(CoroutineExceptionHandler { _, throwable ->
L.e(throwable)
_waitForRevisionState.value = Resource.Success(newRevision)
}) {
_waitForRevisionState.value = Resource.Success(retryUntilNewRevision(pageTitle, newRevision))
}
}
companion object {
suspend fun retryUntilNewRevision(pageTitle: PageTitle, newRevision: Long, maxRetries: Int = 10): Long {
// Implement a retry mechanism to wait for the revision to be available.
var retry = 0
var revision = -1L
while (revision < newRevision && retry < maxRetries) {
delay(2000)
val pageSummaryResponse = ServiceFactory.getRest(pageTitle.wikiSite)
.getPageSummary(pageTitle.prefixedText, cacheControl = OkHttpConnectionFactory.CACHE_CONTROL_FORCE_NETWORK.toString())
revision = pageSummaryResponse.revision
retry++
}
return revision
}
}
}