Bimba.git

ref: 343255d5c2e7108dd510ca9e7707d2d3d67e0bc6

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
package xyz.apiote.bimba.czwek.settings

import android.Manifest
import android.app.NotificationManager
import android.content.Context
import android.content.pm.PackageManager
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.ZonedDateTime
import java.util.UUID
import java.util.zip.ZipEntry
import java.util.zip.ZipInputStream

class DownloadCitiesWorker(appContext: Context, workerParams: WorkerParameters) :
	Worker(appContext, workerParams) {

	override fun doWork(): Result {
		val notificationBuilder = NotificationCompat.Builder(applicationContext, "cities_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("geocoding").path,
				null
			)
			val url = URL("https://download.geonames.org/export/dump/cities15000.zip")
			val connection = url.openConnection()
			var length = connection.contentLength.toLong()
			val connectionEtag = connection.getHeaderField("ETag")
			val savedEtag = PreferenceManager.getDefaultSharedPreferences(applicationContext)
				.getString("cities_etag", 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,
					"cities.zip"
				).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, "cities.zip")
			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 != "cities15000.txt") {
					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 ->
								db.execSQL(
									"insert into place_names2 values(?, ?) on conflict(name) do nothing",
									arrayOf(id, name)
								)
								db.execSQL(
									"insert into place_names2 values(?, ?) on conflict(name) do nothing",
									arrayOf(id, "$name, ${row[8]}")
								)
							}
						}
					}
				}
				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("cities_last_update", ZonedDateTime.now().toEpochSecond())
				putString("cities_etag", 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()
		}
	}
}