Welcome to mirror list, hosted at ThFree Co, Russian Federation.

API.kt « api « ocreader « schaal « email « java « main « src « app - github.com/schaal/ocreader.git - Unnamed repository; edit this file 'description' to name the repository.
summaryrefslogtreecommitdiff
blob: 2d9737fc05cb01ea5efddbd23a59750e2d7db59f (plain)
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
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
/*
 * Copyright © 2020. Daniel Schaal <daniel@schaal.email>
 *
 * This file is part of ocreader.
 *
 * ocreader is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * ocreader is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with Foobar.  If not, see <http://www.gnu.org/licenses/>.
 */

package email.schaal.ocreader.api

import android.content.Context
import android.util.Log
import androidx.preference.PreferenceManager
import com.github.zafarkhaja.semver.Version
import com.squareup.moshi.Moshi
import email.schaal.ocreader.Preferences
import email.schaal.ocreader.R
import email.schaal.ocreader.api.json.*
import email.schaal.ocreader.database.model.*
import email.schaal.ocreader.http.HttpManager
import email.schaal.ocreader.service.SyncType
import email.schaal.ocreader.util.buildBaseUrl
import io.realm.Realm
import io.realm.kotlin.where
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.FlowCollector
import kotlinx.coroutines.flow.collect
import kotlinx.coroutines.flow.flow
import kotlinx.coroutines.runBlocking
import okhttp3.HttpUrl
import okhttp3.HttpUrl.Companion.toHttpUrlOrNull
import retrofit2.Response
import retrofit2.Retrofit
import retrofit2.converter.moshi.MoshiConverterFactory

class API {
    companion object {
        private const val TAG = "API"

        const val BATCH_SIZE = 100L
        const val API_ROOT = "index.php/apps/news/api/"

        val MIN_VERSION: Version = Version.forIntegers(8, 8, 2)

        val moshi: Moshi = Moshi.Builder()
                .add(FeedJsonTypeAdapter())
                .add(ItemJsonTypeAdapter())
                .add(DateTypeAdapter())
                .add(UserJsonTypeAdapter())
                .add(VersionTypeAdapter())
                .build()
        val converterFactory: MoshiConverterFactory = MoshiConverterFactory.create(moshi)

        var instance: API? = null

        suspend fun login(context: Context, baseUrl: HttpUrl, username: String, apptoken: String): Status? {
            val httpManager = HttpManager(username, apptoken, baseUrl)

            val moshi = Moshi.Builder().build()

            val retrofit = Retrofit.Builder()
                    .baseUrl(baseUrl)
                    .client(httpManager.client)
                    .addConverterFactory(MoshiConverterFactory.create(moshi))
                    .build()

            val commonAPI = retrofit.create(CommonAPI::class.java)
            val response = commonAPI.apiLevels()
            if(response.isSuccessful) {
                val apiLevels = response.body()
                val apiLevel = apiLevels?.highestSupportedApi() ?: throw IllegalArgumentException(context.getString(R.string.error_not_compatible))
                val loginInstance = Level.getAPI(context, apiLevel, httpManager)
                val status = loginInstance.metaData()
                val version = status?.version
                if(version != null && MIN_VERSION.lessThanOrEqualTo(version)) {
                    PreferenceManager.getDefaultSharedPreferences(context).edit()
                            .putString(Preferences.USERNAME.key, username)
                            .putString(Preferences.APPTOKEN.key, apptoken)
                            .putString(Preferences.URL.key, baseUrl.toString())
                            .putString(Preferences.SYS_DETECTED_API_LEVEL.key, apiLevel.level)
                            .apply()
                    instance = loginInstance
                    return status
                }
            }
            instance = null
            return null
        }
    }

    enum class MarkAction(val key: String, val changedKey: String, val value: Boolean) {
        MARK_READ(Item.UNREAD, Item::unreadChanged.name, false),
        MARK_UNREAD(Item.UNREAD, Item::unreadChanged.name, true),
        MARK_STARRED(Item.STARRED, Item::starredChanged.name, true),
        MARK_UNSTARRED(Item.STARRED, Item::starredChanged.name, false);
    }

    private val api: APIv12Interface?
    private val ocsapi: OCSAPI?
    private val username: String?

    constructor(context: Context, httpManager: HttpManager) {
        api = setupApi(httpManager)
        username = Preferences.USERNAME.getString(PreferenceManager.getDefaultSharedPreferences(context))
        ocsapi = setupOCSApi(httpManager)
    }

    constructor(context: Context) {
        val sharedPreferences = PreferenceManager.getDefaultSharedPreferences(context)
        username = Preferences.USERNAME.getString(sharedPreferences)
        val apptoken = Preferences.APPTOKEN.getString(sharedPreferences)
        val url = Preferences.URL.getString(sharedPreferences)?.toHttpUrlOrNull()

        if(username == null || apptoken == null || url == null)
            throw IllegalStateException()

        val httpManager = HttpManager(username, apptoken, url)

        api = setupApi(httpManager)
        ocsapi = setupOCSApi(httpManager)
    }

    private fun setupOCSApi(httpManager: HttpManager): OCSAPI {
        val retrofit = Retrofit.Builder()
            .baseUrl(httpManager.credentials.rootUrl.buildBaseUrl("/"))
            .client(httpManager.client)
            .addConverterFactory(converterFactory)
            .build()

        return retrofit.create(OCSAPI::class.java)
    }

    private fun setupApi(httpManager: HttpManager): APIv12Interface {
        val retrofit = Retrofit.Builder()
                .baseUrl(httpManager.credentials.rootUrl.buildBaseUrl("$API_ROOT${Level.V12.level}/"))
                .client(httpManager.client)
                .addConverterFactory(converterFactory)
                .build()

        return retrofit.create(APIv12Interface::class.java)
    }

    private fun syncChanges(realm: Realm): Flow<Pair<MarkAction, List<Item>?>> = flow {
        for(markAction in MarkAction.values())
            emit(markAction to markItems(markAction, realm))
    }

    private suspend fun markItems(action: MarkAction, realm: Realm): List<Item>? {
        val results = realm.where<Item>()
                .equalTo(action.changedKey, true)
                .equalTo(action.key, action.value)
                .findAll()

        if(results.isEmpty())
            return null

        val response: Response<Void>? = when(action) {
            MarkAction.MARK_READ -> {
                api?.markItemsRead(ItemIds(results))
            }
            MarkAction.MARK_UNREAD -> {
                api?.markItemsUnread(ItemIds(results))
            }
            MarkAction.MARK_STARRED -> {
                api?.markItemsStarred(ItemMap(results))
            }
            MarkAction.MARK_UNSTARRED -> {
                api?.markItemsUnstarred(ItemMap(results))
            }
        }

        return if (response?.isSuccessful == true) results else throw IllegalStateException("Marking items failed")
    }

    private enum class QueryType(val type: Int) {
        FEED(0),
        FOLDER(1),
        STARRED(2),
        ALL(3)
    }

    private suspend fun batchedItemLoad(collector: FlowCollector<Insertable>, queryType: QueryType, getRead: Boolean = false) {
        var offset = 0L
        do {
            val resultCount = api?.items(BATCH_SIZE, offset, queryType.type, 0L, getRead = getRead, oldestFirst = true)?.items?.let {
                for (insertable in it) {
                    collector.emit(insertable)
                }
                offset = it.firstOrNull()?.id ?: 0L
                it.size.toLong()
            }
            Log.d(TAG, "offset: $offset, resultCount: $resultCount")
        } while(resultCount == BATCH_SIZE)
    }

    suspend fun sync(syncType: SyncType) {
        Log.d(TAG, "Sync started: ${syncType.action}")
        Realm.getDefaultInstance().use { realm ->
            val result = syncChanges(realm)
            when(syncType) {
                SyncType.SYNC_CHANGES_ONLY -> {
                    realm.executeTransaction {
                        resetItemChanged(result)
                    }
                }
                SyncType.FULL_SYNC -> {
                    val lastSync = realm.where<Item>().maximumDate(Item::lastModified.name)?.time?.let { it / 1000L } ?: 0L

                    val folders = api?.folders()?.folders
                    val feeds = api?.feeds()?.feeds

                    val insertFlow = flow {
                        username?.let {
                            ocsapi?.user(username)?.let { emit(it)}
                        }

                        if(lastSync == 0L) {
                            batchedItemLoad(this, QueryType.STARRED, true)
                            batchedItemLoad(this, QueryType.ALL, false)
                        } else {
                            api?.updatedItems(lastSync, QueryType.ALL.type, 0L)?.items?.let {
                                for (insertable in it) {
                                    emit(insertable)
                                }
                            }
                        }
                    }

                    realm.beginTransaction()
                        resetItemChanged(result)

                        if(folders != null) {
                            val dbFolders = realm.where<Folder>().findAll()
                            val foldersToDelete = dbFolders.minus(folders)

                            for(folder in folders)
                                folder.insert(realm)

                            for(folder in foldersToDelete)
                                folder.delete(realm)
                        }

                        val dbFeeds = realm.where<Feed>().findAll()

                        if(feeds != null) {
                            val feedsToDelete = dbFeeds.minus(feeds)

                            for(feed in feeds)
                                feed.insert(realm)

                            for(feed in feedsToDelete)
                                feed.delete(realm)
                        }

                        insertFlow.collect { it.insert(realm) }

                        for (feed in dbFeeds) {
                            feed.starredCount = realm.where<Item>()
                                    .equalTo(Item::feedId.name, feed.id)
                                    .equalTo(Item.STARRED, true).count().toInt()
                            feed.unreadCount = realm.where<Item>()
                                    .equalTo(Item::feedId.name, feed.id)
                                    .equalTo(Item.UNREAD, true).count().toInt()
                        }

                        Item.removeExcessItems(realm, 10000)
                    realm.commitTransaction()

                }
                SyncType.LOAD_MORE -> {

                }
            }
        }
        Log.d(TAG, "Sync finished: ${syncType.action}")
    }

    private fun resetItemChanged(result: Flow<Pair<MarkAction, List<Item>?>>) = runBlocking {
        result.collect { (action, results) ->
            if(results != null) {
                when(action) {
                    MarkAction.MARK_READ, MarkAction.MARK_UNREAD -> {
                        results.forEach { it.unreadChanged = false }
                    }
                    MarkAction.MARK_STARRED, MarkAction.MARK_UNSTARRED -> {
                        results.forEach { it.starredChanged = false }
                    }
                }
            }
        }
    }

    suspend fun createFeed(url: String, folderId: Long) {
        val feeds = api?.createFeed(mapOf("url" to url, "folderId" to folderId))?.feeds

        feeds?.get(0)?.let { feed: Feed ->
            Realm.getDefaultInstance().use { realm ->
                realm.executeTransaction {
                    feed.unreadCount = 0
                    feed.insert(it)
                }
            }
        }
    }

    suspend fun deleteFeed(feed: Feed) {
        val response = api?.deleteFeed(feed.id)
        if(response?.isSuccessful == true) {
            Realm.getDefaultInstance().use { realm ->
                realm.executeTransaction {
                    feed.delete(it)
                }
            }
        }
    }

    suspend fun moveFeed(feedId: Long, folderId: Long) {
        Realm.getDefaultInstance().use { realm ->
            val feed = Feed.get(realm, feedId) ?: return

            val response = api?.moveFeed(feed.id, mapOf("folderId" to folderId))
            if (response?.isSuccessful == true) {
                realm.executeTransaction {
                    feed.folderId = folderId
                    feed.folder = Folder.getOrCreate(it, folderId)
                }
            }
        }
    }

    suspend fun metaData(): Status? {
        return api?.status()
    }

}