aboutsummaryrefslogtreecommitdiff
path: root/android/app/src/main/java/jp/thb/tracker/SelfTrackService.kt
blob: d6f37954256060e200870da2d5140aca35ef70a3 (plain) (blame)
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
package jp.thb.tracker

import android.app.Notification
import android.app.NotificationChannel
import android.app.NotificationManager
import android.app.PendingIntent
import android.app.Service
import android.content.Context
import android.content.Intent
import android.location.Location
import android.location.LocationListener
import android.location.LocationManager
import android.os.Build
import android.os.Bundle
import android.os.Handler
import android.os.IBinder
import android.os.Looper
import android.os.PowerManager
import androidx.core.app.NotificationCompat
import jp.thb.tracker.data.SelfTrack
import org.json.JSONArray
import org.json.JSONObject
import java.io.BufferedReader
import java.io.InputStreamReader
import java.net.HttpURLConnection
import java.net.URL
import java.text.SimpleDateFormat
import java.util.Date
import java.util.Locale
import java.util.TimeZone
import java.util.concurrent.atomic.AtomicBoolean
import kotlin.concurrent.thread

/**
 * Reports the phone's own position to the THB server every N hours (1-hour steps).
 *
 * A cell/Wi-Fi fix is preferred.  If the network provider gives nothing within
 * 30 s, one GPS fix is requested (up to 90 s), and finally the newest last-known
 * position is used.  Every attempt is stored in SharedPreferences so the
 * "端末" tab can show the result.
 */
class SelfTrackService : Service() {

    companion object {
        const val ACTION_TICK = "jp.thb.tracker.SELF_TICK"
        const val ACTION_ONCE = "jp.thb.tracker.SELF_ONCE"
        const val ACTION_STOP = "jp.thb.tracker.SELF_STOP"
        private const val CHANNEL = "thb_selftrack"
        private const val NOTIF_ID = 1001
    }

    private val handler = Handler(Looper.getMainLooper())
    private var busy = false
    private var foreground = false

    private val tick = object : Runnable {
        override fun run() {
            if (!SelfTrack.enabled(this@SelfTrackService)) {
                stopSelf()
                return
            }
            runWork(once = false)
            handler.postDelayed(this, SelfTrack.hours(this@SelfTrackService) * 3_600_000L)
        }
    }

    override fun onBind(intent: Intent?): IBinder? = null

    override fun onCreate() {
        super.onCreate()
        jp.thb.tracker.net.Tls.install(this)
    }

    override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {
        when (intent?.action) {
            ACTION_STOP -> {
                getSharedPreferences("thb_selftrack", MODE_PRIVATE).edit()
                    .putBoolean("enabled", false).apply()
                handler.removeCallbacks(tick)
                stopForegroundCompat()
                stopSelf()
                return START_NOT_STICKY
            }

            ACTION_ONCE -> {
                ensureForeground()
                runWork(once = true)
                return START_STICKY
            }

            else -> {
                ensureForeground()
                handler.removeCallbacks(tick)
                if (!SelfTrack.enabled(this)) {
                    stopForegroundCompat()
                    stopSelf()
                    return START_NOT_STICKY
                }
                runWork(once = false)
                handler.postDelayed(tick, SelfTrack.hours(this) * 3_600_000L)
                return START_STICKY
            }
        }
    }

    override fun onDestroy() {
        handler.removeCallbacks(tick)
        super.onDestroy()
    }

    // ---------------------------------------------------------------- work

    private fun runWork(once: Boolean) {
        if (busy) return
        busy = true
        updateNotification("位置を取得しています…")

        val power = getSystemService(Context.POWER_SERVICE) as? PowerManager
        val wake = power?.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "thb:selftrack")?.also {
            runCatching { it.acquire(4 * 60_000L) }
        }

        locate { loc ->
            if (loc == null) {
                SelfTrack.noteError(this, "位置を取得できませんでした(この端末は GPS のみ。屋外でお試しください)")
                finish(wake, once, "位置を取得できませんでした", ok = false)
                return@locate
            }
            thread {
                val err = post(loc)
                handler.post {
                    if (err == null) {
                        val acc = if (loc.hasAccuracy()) " 精度 ${loc.accuracy.toInt()}m" else ""
                        SelfTrack.noteOk(this, "送信しました$acc")
                        finish(wake, once, "送信しました$acc", ok = true)
                    } else {
                        SelfTrack.noteError(this, err)
                        finish(wake, once, "送信失敗: $err", ok = false)
                    }
                }
            }
        }
    }

    private fun finish(wake: PowerManager.WakeLock?, once: Boolean, message: String, ok: Boolean) {
        if (wake?.isHeld == true) runCatching { wake.release() }
        busy = false
        updateNotification(message)
        if (once && !SelfTrack.enabled(this)) {
            handler.postDelayed({
                stopForegroundCompat()
                stopSelf()
            }, 3_000)
        }
    }

    // ------------------------------------------------------------ location

    private fun locate(onDone: (Location?) -> Unit) {
        val lm = getSystemService(Context.LOCATION_SERVICE) as? LocationManager
        if (lm == null) {
            onDone(null)
            return
        }
        // This handset's real network provider is Qualcomm IZat, exposed as the
        // remote "fused" provider (persist.loc.nlp_name=com.qualcomm.location).
        // getProvider("fused") returns null for apps here, so just try the names
        // and fall back when the request is rejected.
        val order = buildList {
            for (p in listOf(
                LocationManager.NETWORK_PROVIDER, "fused", "sbm_lib",
                LocationManager.PASSIVE_PROVIDER, LocationManager.GPS_PROVIDER,
            )) if (p !in this) add(p)
            for (p in runCatching { lm.getProviders(true) }.getOrDefault(emptyList())) {
                if (p !in this) add(p)
            }
        }

        val best = order.mapNotNull { p ->
            runCatching { lm.getLastKnownLocation(p) }.getOrNull()
        }.maxByOrNull { it.time }

        // A recent fix is good enough and costs no radio time.
        if (best != null && System.currentTimeMillis() - best.time < 10 * 60_000L) {
            onDone(best)
            return
        }

        fun tryNext(index: Int) {
            if (index >= order.size) {
                onDone(best)
                return
            }
            val provider = order[index]
            val timeout = when (provider) {
                LocationManager.GPS_PROVIDER -> 90_000L
                "fused" -> 30_000L      // Qualcomm IZat (network) - often unavailable here
                "sbm_lib" -> 20_000L    // SoftBank provider: accepts the request, no fix
                LocationManager.PASSIVE_PROVIDER -> 5_000L
                else -> 10_000L
            }
            requestOnce(lm, provider, timeout) { loc ->
                if (loc != null) onDone(loc) else tryNext(index + 1)
            }
        }
        tryNext(0)
    }

    private fun requestOnce(
        lm: LocationManager,
        provider: String,
        timeoutMs: Long,
        onDone: (Location?) -> Unit,
    ) {
        // No isProviderEnabled() pre-check: "fused" is a remote provider here and
        // reports disabled, but requestSingleUpdate() still works.
        val done = AtomicBoolean(false)
        var listener: LocationListener? = null
        val timeout = Runnable {
            if (done.compareAndSet(false, true)) {
                listener?.let { l -> runCatching { lm.removeUpdates(l) } }
                onDone(null)
            }
        }
        val l = object : LocationListener {
            override fun onLocationChanged(location: Location) {
                if (done.compareAndSet(false, true)) {
                    runCatching { lm.removeUpdates(this) }
                    handler.removeCallbacks(timeout)
                    onDone(location)
                }
            }

            override fun onStatusChanged(provider: String?, status: Int, extras: Bundle?) {}
            override fun onProviderEnabled(provider: String) {}
            override fun onProviderDisabled(provider: String) {}
        }
        listener = l
        try {
            lm.requestSingleUpdate(provider, l, Looper.getMainLooper())
            handler.postDelayed(timeout, timeoutMs)
        } catch (e: Exception) {
            if (done.compareAndSet(false, true)) onDone(null)
        }
    }

    // ------------------------------------------------------------- network

    private fun post(loc: Location): String? {
        val prefs = getSharedPreferences("thb", MODE_PRIVATE)
        val base = prefs.getString("baseUrl", "").orEmpty().trim().trimEnd('/')
        val token = prefs.getString("token", "").orEmpty().trim()
        if (base.isBlank()) return "サーバー URL が未設定です(設定 → サーバー設定)"

        val point = JSONObject()
            .put("time", isoTime(loc.time))
            .put("lat", loc.latitude)
            .put("lon", loc.longitude)
            .put("accuracy_m", if (loc.hasAccuracy()) loc.accuracy.toDouble() else JSONObject.NULL)
        val body = JSONObject().put("name", "この端末").put("points", JSONArray().put(point))

        var conn: HttpURLConnection? = null
        return try {
            conn = (URL("$base/api/self/points").openConnection() as HttpURLConnection).apply {
                requestMethod = "POST"
                connectTimeout = 10_000
                readTimeout = 20_000
                doOutput = true
                setRequestProperty("Content-Type", "application/json; charset=utf-8")
                if (token.isNotBlank()) setRequestProperty("X-Auth", token)
            }
            conn.outputStream.use { it.write(body.toString().toByteArray(Charsets.UTF_8)) }
            val code = conn.responseCode
            val text = (if (code in 200..299) conn.inputStream else conn.errorStream)?.use { input ->
                BufferedReader(InputStreamReader(input, Charsets.UTF_8)).readText()
            }.orEmpty()
            if (code !in 200..299) "HTTP $code ${text.take(120)}" else null
        } catch (e: Exception) {
            e.message ?: e.javaClass.simpleName
        } finally {
            runCatching { conn?.disconnect() }
        }
    }

    private fun isoTime(millis: Long): String {
        val f = SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'", Locale.US)
        f.timeZone = TimeZone.getTimeZone("UTC")
        return f.format(Date(millis))
    }

    // -------------------------------------------------------- notification

    private fun ensureForeground(text: String = "待機中") {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            val nm = getSystemService(NotificationManager::class.java)
            if (nm != null && nm.getNotificationChannel(CHANNEL) == null) {
                nm.createNotificationChannel(
                    NotificationChannel(CHANNEL, "この端末の追跡", NotificationManager.IMPORTANCE_LOW)
                )
            }
        }
        try {
            startForeground(NOTIF_ID, buildNotification(text))
            foreground = true
        } catch (e: Exception) {
            // Android 14 can refuse a location foreground service started from
            // the background; the periodic work simply will not run there.
            foreground = false
        }
    }

    private fun updateNotification(text: String) {
        if (!foreground) return
        runCatching {
            val nm = getSystemService(NotificationManager::class.java)
            nm?.notify(NOTIF_ID, buildNotification(text))
        }
    }

    private fun buildNotification(text: String): Notification {
        val flags = PendingIntent.FLAG_UPDATE_CURRENT or
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) PendingIntent.FLAG_IMMUTABLE else 0
        val open = PendingIntent.getActivity(
            this, 0, Intent(this, MainActivity::class.java), flags
        )
        return NotificationCompat.Builder(this, CHANNEL)
            .setSmallIcon(android.R.drawable.ic_menu_mylocation)
            .setContentTitle("この端末を追跡中")
            .setContentText(text)
            .setOngoing(true)
            .setOnlyAlertOnce(true)
            .setContentIntent(open)
            .build()
    }

    @Suppress("DEPRECATION")
    private fun stopForegroundCompat() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
            stopForeground(STOP_FOREGROUND_REMOVE)
        } else {
            stopForeground(true)
        }
        foreground = false
    }
}