Bimba.git

ref: v3.7.0

app/src/main/java/xyz/apiote/bimba/czwek/settings/DownloadCitiesWorker.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
// SPDX-FileCopyrightText: Adam Evyčędo
//
// SPDX-License-Identifier: AGPL-3.0-or-later

package xyz.apiote.bimba.czwek.settings

import android.Manifest
import android.content.Context
import android.content.pm.PackageManager
import android.database.sqlite.SQLiteConstraintException
import android.database.sqlite.SQLiteDatabase
import android.util.Log
import androidx.core.app.ActivityCompat
import androidx.core.app.NotificationCompat
import androidx.core.app.NotificationManagerCompat
import androidx.core.content.edit
import androidx.core.database.sqlite.transaction
import androidx.preference.PreferenceManager
import androidx.work.Worker
import androidx.work.WorkerParameters
import com.github.doyaaaaaken.kotlincsv.dsl.csvReader
import org.apache.commons.io.input.BoundedInputStream
import xyz.apiote.bimba.czwek.R
import java.io.BufferedInputStream
import java.io.BufferedOutputStream
import java.io.File
import java.net.URL
import java.time.Instant
import java.time.ZonedDateTime
import java.time.temporal.ChronoUnit
import java.util.UUID
import java.util.zip.ZipEntry
import java.util.zip.ZipInputStream

// FIXME doesn't work on older versions of Android
class DownloadCitiesWorker(appContext: Context, workerParams: WorkerParameters) :
	Worker(appContext, workerParams) {

	companion object {
		const val AUTOUPDATE_KEY = "autoupdate_cities_list"
		const val LAST_UPDATE_KEY = "cities_last_update"
		const val NOTIFICATION_CHANNEL = "cities_channel"
		const val DATABASE_NAME = "geocoding"
		const val ETAG_HEADER_NAME = "ETag"
		const val ETAG_KEY = "cities_etag"
		const val RESULT_ZIP_FILE = "cities.zip"
		const val CITIES_URL = "https://download.geonames.org/export/dump/cities15000.zip"
		const val CITIES_FILE = "cities15000.txt"
		fun shouldUpdate(context: Context): Boolean {
			val (updatesEnabled, weekPassed) = PreferenceManager.getDefaultSharedPreferences(context)
				.let {
					arrayOf(
						it.getBoolean(AUTOUPDATE_KEY, false),
						Instant.ofEpochSecond(it.getLong(LAST_UPDATE_KEY, 0)).plus(7, ChronoUnit.DAYS)
							.isBefore(Instant.now())
					)
				}
			return updatesEnabled && weekPassed
		}
	}

	override fun doWork(): Result {
		val notificationBuilder = NotificationCompat.Builder(applicationContext, NOTIFICATION_CHANNEL)
			.setSmallIcon(R.drawable.geocoding)
			.setContentTitle(applicationContext.getString(R.string.updating_geocoding_data))
			.setContentText(applicationContext.getString(R.string.downloading_cities_list))
			.setPriority(NotificationCompat.PRIORITY_LOW)
			.setProgress(100, 0, true)
		try {
			if (ActivityCompat.checkSelfPermission(
					applicationContext,
					Manifest.permission.POST_NOTIFICATIONS
				) == PackageManager.PERMISSION_GRANTED
			) {
				NotificationManagerCompat.from(applicationContext).notify(0, notificationBuilder.build())
			}

			val db = SQLiteDatabase.openOrCreateDatabase(
				applicationContext.getDatabasePath(DATABASE_NAME).path,
				null
			)
			val url = URL(CITIES_URL)
			val connection = url.openConnection()
			var length = connection.contentLength.toLong()
			val connectionEtag = connection.getHeaderField(ETAG_HEADER_NAME)
			val savedEtag = PreferenceManager.getDefaultSharedPreferences(applicationContext)
				.getString(ETAG_KEY, null)
			if (savedEtag != null && savedEtag == connectionEtag) {
				if (ActivityCompat.checkSelfPermission(
						applicationContext,
						Manifest.permission.POST_NOTIFICATIONS
					) == PackageManager.PERMISSION_GRANTED
				) {
					NotificationManagerCompat.from(applicationContext).cancel(0)
				}
				return Result.success()
			}

			db.execSQL("drop table if exists place_names2")
			db.execSQL("drop table if exists places2")
			db.execSQL("create table places2(id text primary key, lat real, lon real)")
			db.execSQL("create table place_names2(id text references places(id), name text primary key)")

			var countingStream =
				BoundedInputStream.Builder()
					.setInputStream(BufferedInputStream(connection.getInputStream())).get()
			val zipFileStream = BufferedOutputStream(
				File(
					applicationContext.noBackupFilesDir.path,
					RESULT_ZIP_FILE
				).outputStream()
			)

			val buffer = ByteArray(DEFAULT_BUFFER_SIZE)
			var bytes = countingStream.read(buffer)
			while (bytes >= 0) {
				zipFileStream.write(buffer, 0, bytes)
				Log.i(
					"geocoding",
					"zip_download: downloaded ${countingStream.count}/$length: ${countingStream.count.toFloat() / length * 100}%"
				)
				if (ActivityCompat.checkSelfPermission(
						applicationContext,
						Manifest.permission.POST_NOTIFICATIONS
					) == PackageManager.PERMISSION_GRANTED
				) {
					notificationBuilder
						.setProgress(100, (countingStream.count.toFloat() / length * 100).toInt(), false)
					NotificationManagerCompat.from(applicationContext).notify(0, notificationBuilder.build())
				}
				bytes = countingStream.read(buffer)
			}
			countingStream.close()
			zipFileStream.close()

			notificationBuilder
				.setProgress(100, 0, true)
				.setContentText(applicationContext.getString(R.string.saving_cities_list))
			if (ActivityCompat.checkSelfPermission(
					applicationContext,
					Manifest.permission.POST_NOTIFICATIONS
				) == PackageManager.PERMISSION_GRANTED
			) {
				NotificationManagerCompat.from(applicationContext).notify(0, notificationBuilder.build())
			}
			val zipFile = File(applicationContext.noBackupFilesDir.path, RESULT_ZIP_FILE)
			length = zipFile.length()
			countingStream =
				BoundedInputStream.Builder().setInputStream(BufferedInputStream(zipFile.inputStream()))
					.get()
			val stream = ZipInputStream(countingStream)
			var entry: ZipEntry? = stream.nextEntry
			while (entry != null) {
				if (entry.name != CITIES_FILE) {
					entry = stream.nextEntry
					continue
				}
				var count = 0
				db.transaction {
					csvReader { delimiter = '\t' }.open(stream) {
						readAllAsSequence().forEach { row ->
							val names = if (row[3] == "") {
								"${row[1]},${row[2]}"
							} else {
								row[3]
							}
							if (count % 1000 == 0) {
								Log.i(
									"geocoding",
									"${countingStream.count}/$length=${countingStream.count.toFloat() / length * 100}% $names"
								)
								if (ActivityCompat.checkSelfPermission(
										applicationContext,
										Manifest.permission.POST_NOTIFICATIONS
									) == PackageManager.PERMISSION_GRANTED
								) {
									notificationBuilder
										.setProgress(
											100,
											(countingStream.count.toFloat() / length * 100).toInt(),
											false
										)
									NotificationManagerCompat.from(applicationContext)
										.notify(0, notificationBuilder.build())
								}
							}
							count++

							val id = UUID.randomUUID()
							db.execSQL("insert into places2 values(?, ?, ?)", arrayOf(id, row[4], row[5]))
							names.split(",").toSet().forEach { name ->
								try {
									db.execSQL(
										"insert into place_names2 values(?, ?)",
										arrayOf(id, name)
									)
								} catch (e: SQLiteConstraintException) {
									// XXX `on conflict` doesn't work on older versions of Android
									if (e.message?.contains("UNIQUE constraint failed: place_names2.name") != true) {
										throw e
									}
								}
								try {
									db.execSQL(
										"insert into place_names2 values(?, ?)",
										arrayOf(id, "$name, ${row[8]}")
									)
								} catch (e: SQLiteConstraintException) {
									// XXX `on conflict` doesn't work on older versions of Android
									if (e.message?.contains("UNIQUE constraint failed: place_names2.name") != true) {
										throw e
									}
								}
							}
						}
					}
				}
				Log.i("geocoding", "COMPLETE")
				break
			}
			stream.close()
			zipFile.delete()

			db.execSQL("drop index if exists place_names__name")
			db.execSQL("drop table if exists place_names")
			db.execSQL("drop table if exists places")
			db.execSQL("alter table places2 rename to places")
			db.execSQL("alter table place_names2 rename to place_names")
			db.execSQL("create unique index place_names__name on place_names(name)")

			PreferenceManager.getDefaultSharedPreferences(applicationContext).edit {
				putLong(LAST_UPDATE_KEY, ZonedDateTime.now().toEpochSecond())
				putString(ETAG_KEY, connectionEtag)
			}

			db.close()
			if (ActivityCompat.checkSelfPermission(
					applicationContext,
					Manifest.permission.POST_NOTIFICATIONS
				) == PackageManager.PERMISSION_GRANTED
			) {
				notificationBuilder
					.setContentText("")
					.setContentTitle(applicationContext.getString(R.string.finished_updating_geocoding_data))
					.setProgress(100, 100, false)
				NotificationManagerCompat.from(applicationContext).notify(0, notificationBuilder.build())
			}
			return Result.success()
		} catch (e: Exception) {
			e.printStackTrace()
			if (ActivityCompat.checkSelfPermission(
					applicationContext,
					Manifest.permission.POST_NOTIFICATIONS
				) == PackageManager.PERMISSION_GRANTED
			) {
				notificationBuilder
					.setContentText("")
					.setContentTitle(applicationContext.getString(R.string.updating_geocoding_data_failed))
					.setProgress(100, 100, false)
				NotificationManagerCompat.from(applicationContext).notify(0, notificationBuilder.build())
			}
			return Result.failure()
		}
	}
}