Bimba.git

ref: a52096478ab19aae3f657e40d0b973ae1276e090

app/src/main/java/ml/adamsprogs/bimba/datasources/TimetableDownloader.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
package ml.adamsprogs.bimba.datasources

import android.annotation.TargetApi
import android.app.IntentService
import android.app.Notification
import android.content.Context
import android.content.Intent
import android.support.v4.app.NotificationCompat
import java.net.HttpURLConnection
import java.net.URL
import java.io.*
import java.security.MessageDigest
import android.app.NotificationManager
import android.os.Build
import ir.mahdi.mzip.zip.ZipArchive
import ml.adamsprogs.bimba.NetworkStateReceiver
import ml.adamsprogs.bimba.NotificationChannels
import ml.adamsprogs.bimba.R
import ml.adamsprogs.bimba.models.Timetable
import java.util.*

class TimetableDownloader : IntentService("TimetableDownloader") {
    companion object {
        const val ACTION_DOWNLOADED = "ml.adamsprogs.bimba.timetableDownloaded"
        const val EXTRA_FORCE = "force"
        const val EXTRA_RESULT = "result"
        const val RESULT_NO_CONNECTIVITY = "no connectivity"
        const val RESULT_UP_TO_DATE = "up-to-date"
        const val RESULT_DOWNLOADED = "downloaded"
        const val RESULT_FINISHED = "finished"
    }

    private lateinit var notificationManager: NotificationManager
    private var size: Int = 0

    override fun onHandleIntent(intent: Intent?) { //fixme throws something

        if (intent != null) {
            notificationManager = getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
            val prefs = this.getSharedPreferences("ml.adamsprogs.bimba.prefs", Context.MODE_PRIVATE)!!
            if (!NetworkStateReceiver.isNetworkAvailable(this)) {
                sendResult(RESULT_NO_CONNECTIVITY)
                return
            }
            val url = URL("http://ztm.poznan.pl/pl/dla-deweloperow/getGTFSFile")
            val httpCon = url.openConnection() as HttpURLConnection
            if (httpCon.responseCode != HttpURLConnection.HTTP_OK) { //IOEXCEPTION or EOFEXCEPTION or ConnectException
                sendResult(RESULT_NO_CONNECTIVITY)
                return
            }
            val lastModified = httpCon.getHeaderField("Content-Disposition").split("=")[1].trim('\"').split("_")[0]
            size = httpCon.getHeaderField("Content-Length").toInt() / 1024

            val force = intent.getBooleanExtra(EXTRA_FORCE, false)
            val currentLastModified = prefs.getString("timetableLastModified", "19791012")
            if (lastModified <= currentLastModified && lastModified <= today() && !force) {
                sendResult(RESULT_UP_TO_DATE)
                return
            }

            notifyDownloading(0)

            val gtfs = File(this.filesDir, "timetable.zip")
            copyInputStreamToFile(httpCon.inputStream, gtfs)
            val prefsEditor = prefs.edit()
            prefsEditor.putString("timetableLastModified", lastModified)
            prefsEditor.apply()
            sendResult(RESULT_DOWNLOADED)

            //notifyConverting() //fixme

            val target = File(this.filesDir, "gtfs_files")
            target.deleteRecursively()
            target.mkdir()
            ZipArchive.unzip(gtfs.path, target.path, "")
            //todo divide stop_times by stop_id
            gtfs.delete()
            Timetable.getTimetable().refresh()

            cancelNotification()

            sendResult(RESULT_FINISHED)
        }
    }

    private fun today(): String {
        val cal = Calendar.getInstance()
        val d = cal[Calendar.DAY_OF_MONTH]
        val m = cal[Calendar.MONTH] + 1
        val y = cal[Calendar.YEAR]

        return "%d%02d%02d".format(y, m, d)
    }

    private fun sendResult(result: String) {
        val broadcastIntent = Intent()
        broadcastIntent.action = ACTION_DOWNLOADED
        broadcastIntent.addCategory(Intent.CATEGORY_DEFAULT)
        broadcastIntent.putExtra(EXTRA_RESULT, result)
        sendBroadcast(broadcastIntent)
    }

    private fun notifyDownloading(progress: Int) {
        if (Build.VERSION.SDK_INT < Build.VERSION_CODES.O)
            notifyCompat(progress)
        else
            notifyStandard(progress)
    }

    @Suppress("DEPRECATION")
    private fun notifyCompat(progress: Int) {
        val builder = NotificationCompat.Builder(this)
                .setSmallIcon(R.drawable.ic_download)
                .setContentTitle(getString(R.string.timetable_downloading))
                .setContentText("$progress KiB/$size KiB")
                .setCategory(NotificationCompat.CATEGORY_PROGRESS)
                .setOngoing(true)
                .setProgress(size, progress, false)
        notificationManager.notify(42, builder.build())
    }

    @TargetApi(Build.VERSION_CODES.O)
    private fun notifyStandard(progress: Int) {
        NotificationChannels.makeChannel(NotificationChannels.CHANNEL_UPDATES, "Updates", notificationManager)
        val builder = Notification.Builder(this, NotificationChannels.CHANNEL_UPDATES)
                .setSmallIcon(R.drawable.ic_download)
                .setContentTitle(getString(R.string.timetable_downloading))
                .setContentText("$progress KiB/$size KiB")
                .setCategory(Notification.CATEGORY_PROGRESS)
                .setOngoing(true)
                .setProgress(size, progress, false)
        notificationManager.notify(42, builder.build())
    }

    private fun notifyConverting() {
        if (Build.VERSION.SDK_INT < Build.VERSION_CODES.O)
            notifyCompatConverting()
        else
            notifyStandardConverting()

    }

    @Suppress("DEPRECATION")
    private fun notifyCompatConverting() {
        val builder = NotificationCompat.Builder(this)
                .setSmallIcon(R.drawable.ic_download)
                .setContentTitle(getString(R.string.timetable_converting))
                .setContentText("")
                .setCategory(NotificationCompat.CATEGORY_PROGRESS)
                .setOngoing(true)
                .setProgress(0, 0, true)
        notificationManager.notify(42, builder.build())
    }

    @TargetApi(Build.VERSION_CODES.O)
    private fun notifyStandardConverting() {
        NotificationChannels.makeChannel(NotificationChannels.CHANNEL_UPDATES, "Updates", notificationManager)
        val builder = Notification.Builder(this, NotificationChannels.CHANNEL_UPDATES)
                .setSmallIcon(R.drawable.ic_download)
                .setContentTitle(getString(R.string.timetable_converting))
                .setContentText("")
                .setCategory(Notification.CATEGORY_PROGRESS)
                .setOngoing(true)
                .setProgress(0, 0, true)
        notificationManager.notify(42, builder.build())
    }

    private fun cancelNotification() {
        notificationManager.cancel(42)
    }

    private fun copyInputStreamToFile(ins: InputStream, file: File) {
        val md = MessageDigest.getInstance("SHA-512")
        try {
            val out = FileOutputStream(file)
            val buf = ByteArray(5 * 1024)
            var lenSum = 0.0f
            var len = 42
            while (len > 0) {
                len = ins.read(buf)
                if (len <= 0)
                    break
                md.update(buf, 0, len)
                out.write(buf, 0, len)
                lenSum += len.toFloat() / 1024.0f
                notifyDownloading(lenSum.toInt())
            }
            out.close()
        } catch (e: Exception) {
            e.printStackTrace()
        } finally {
            ins.close()
        }
    }
}