ref: e44b75a453055418c5a6593a561ad823f9815a8f
app/src/main/java/ml/adamsprogs/bimba/datasources/VmClient.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 |
package ml.adamsprogs.bimba.datasources import android.app.Service import android.content.Intent import android.os.Handler import android.os.HandlerThread import android.os.IBinder import android.os.Process.THREAD_PRIORITY_BACKGROUND import com.google.gson.Gson import ml.adamsprogs.bimba.NetworkStateReceiver import ml.adamsprogs.bimba.calendarFromIso import ml.adamsprogs.bimba.models.* import okhttp3.FormBody import okhttp3.OkHttpClient import ml.adamsprogs.bimba.models.gtfs.AgencyAndId import ml.adamsprogs.bimba.secondsAfterMidnight import java.io.IOException import java.util.* import kotlin.collections.HashMap import kotlin.collections.HashSet import kotlin.concurrent.thread class VmClient : Service() { companion object { const val ACTION_READY = "ml.adamsprogs.bimba.action.vm.ready" const val EXTRA_DEPARTURES = "ml.adamsprogs.bimba.extra.vm.departures" const val EXTRA_PLATE_ID = "ml.adamsprogs.bimba.extra.vm.plate" const val TICK_6_ZINA_TIM = 12500L const val TICK_6_ZINA_TIM_WITH_MARGIN = TICK_6_ZINA_TIM * 3 / 4 } private var handler: Handler? = null private val tick6ZinaTim: Runnable = object : Runnable { override fun run() { handler!!.postDelayed(this, TICK_6_ZINA_TIM) try { for (plateId in requests.keys) downloadVM() } catch (e: ConcurrentModificationException) { //fixme } } } private val requests = HashMap<AgencyAndId, Set<Request>>() private val vms = HashMap<AgencyAndId, Set<Plate>>() private val timetable = try { Timetable.getTimetable(this) } catch (e: NullPointerException) { null } override fun onCreate() { val thread = HandlerThread("ServiceStartArguments", THREAD_PRIORITY_BACKGROUND) thread.start() handler = Handler(thread.looper) handler!!.postDelayed(tick6ZinaTim, TICK_6_ZINA_TIM) } override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int { if (timetable == null) return START_NOT_STICKY val stopSegment = intent?.getParcelableExtra<StopSegment>("stop")!! if (stopSegment.plates == null) throw EmptyStopSegmentException() val action = intent.action val once = intent.getBooleanExtra("once", false) if (action == "request") { if (isAlreadyRequested(stopSegment)) { incrementRequest(stopSegment) sendResult(stopSegment) } else { if (!once) addRequest(stopSegment) thread { downloadVM(stopSegment) } } } else if (action == "remove") { decrementRequest(stopSegment) cleanRequests() } return START_STICKY } private fun cleanRequests() { val newMap = HashMap<AgencyAndId, Set<Request>>() requests.forEach { newMap[it.key] = it.value.minus(it.value.filter { it.times == 0 }) } newMap.forEach { requests[it.key] = it.value } } private fun addRequest(stopSegment: StopSegment) { if (requests[stopSegment.stop] == null) { requests[stopSegment.stop] = stopSegment.plates!! .map { Request(it, 1) } .toSet() } else { var req = requests[stopSegment.stop]!! stopSegment.plates!!.forEach { val plate = it if (req.any { it.plate == plate }) { req.filter { it.plate == plate }[0].times++ } else { req = req.plus(Request(it, 1)) } requests[stopSegment.stop] = req } } } private fun sendResult(stop: StopSegment) { vms[stop.stop]?.filter { val plate = it stop.plates!!.any { it == plate.id } }?.forEach { sendResult(it.id, it.departures?.get(today())) } } private fun today(): AgencyAndId { return timetable!!.getServiceForToday() } private fun incrementRequest(stopSegment: StopSegment) { stopSegment.plates!!.forEach { val plateId = it requests[it.stop]!!.filter { it.plate == plateId }.forEach { it.times++ } } } private fun decrementRequest(stopSegment: StopSegment) { stopSegment.plates!!.forEach { val plateId = it requests[it.stop]!!.filter { it.plate == plateId }.forEach { it.times-- } } } private fun isAlreadyRequested(stopSegment: StopSegment): Boolean { val platesIn = requests[stopSegment.stop]?.map { it.plate }?.toSet() val platesOut = stopSegment.plates if (platesIn == null || platesIn.isEmpty()) return false return (platesOut == platesIn || platesIn.containsAll(platesOut!!)) } override fun onBind(intent: Intent): IBinder? { return null } override fun onDestroy() { } private fun downloadVM() { vms.forEach { downloadVM(StopSegment(it.key, it.value.map { it.id }.toSet())) } } private fun downloadVM(stopSegment: StopSegment) { if (!NetworkStateReceiver.isNetworkAvailable(this)) { vms[stopSegment.stop] = HashSet(stopSegment.plates!!.map { Plate(it, null) }.toSet()) stopSegment.plates!!.forEach { sendResult(it, null) } return } val stopSymbol = timetable!!.getStopCode(stopSegment.stop) val client = OkHttpClient() val url = "http://www.peka.poznan.pl/vm/method.vm?ts=${Calendar.getInstance().timeInMillis}" val formBody = FormBody.Builder() .add("method", "getTimes") .add("p0", "{\"symbol\": \"$stopSymbol\"}") .build() val request = okhttp3.Request.Builder() .url(url) .post(formBody) .build() val responseBody: String? try { responseBody = client.newCall(request).execute().body()?.string() } catch (e: IOException) { stopSegment.plates!!.forEach { sendResult(it, null) } return } if (responseBody?.get(0) == '<') { stopSegment.plates!!.forEach { sendResult(it, null) } return } val javaRootMapObject = Gson().fromJson(responseBody, HashMap::class.java) val times = (javaRootMapObject["success"] as Map<*, *>)["times"] as List<*> stopSegment.plates!!.forEach { downloadVM(it, times) } } private fun downloadVM(plateId: Plate.ID, times: List<*>) { val date = Calendar.getInstance() val todayDay = "${date.get(Calendar.DATE)}".padStart(2, '0') val todayMode = timetable!!.calendarToMode(AgencyAndId(timetable.getServiceForToday().id)) val departures = HashSet<Departure>() times.forEach { val thisLine = AgencyAndId((it as Map<*, *>)["line"] as String) val thisHeadsign = it["direction"] as String val thisPlateId = Plate.ID(thisLine, plateId.stop, thisHeadsign) if (plateId == thisPlateId) { val departureDay = (it["departure"] as String).split("T")[0].split("-")[2] val departureTime = calendarFromIso(it["departure"] as String).secondsAfterMidnight() val departure = Departure(plateId.line, todayMode, departureTime, false, ArrayList(), it["direction"] as String, it["realTime"] as Boolean, departureDay != todayDay, it["onStopPoint"] as Boolean) departures.add(departure) } } val departuresForPlate = HashMap<AgencyAndId, HashSet<Departure>>() departuresForPlate[timetable.getServiceForToday()] = departures val vm = vms[plateId.stop] ?: HashSet() try { (vm as HashSet).remove(vm.filter { it.id == plateId }[0]) } catch (e: IndexOutOfBoundsException) { } (vm as HashSet).add(Plate(plateId, departuresForPlate)) vms[plateId.stop] = vm if (departures.isEmpty()) sendResult(plateId, null) else sendResult(plateId, departures) } private fun sendResult(plateId: Plate.ID, departures: HashSet<Departure>?) { val broadcastIntent = Intent() broadcastIntent.action = ACTION_READY broadcastIntent.addCategory(Intent.CATEGORY_DEFAULT) if (departures != null) broadcastIntent.putStringArrayListExtra(EXTRA_DEPARTURES, departures.map { it.toString() } as ArrayList) broadcastIntent.putExtra(EXTRA_PLATE_ID, plateId) sendBroadcast(broadcastIntent) } data class Request(val plate: Plate.ID, var times: Int) class EmptyStopSegmentException : Exception() } //note application stops the service on exit |