cordova-plugin-pushizo 0.1.0 → 0.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,493 +1,856 @@
1
- package com.pushizo.cordova
2
-
3
- import android.Manifest
4
- import android.app.Activity
5
- import android.app.AlertDialog
6
- import android.content.Context
7
- import android.content.pm.PackageManager
8
- import android.os.Build
9
- import com.pushizo.sdk.Pushizo
10
- import com.pushizo.sdk.HsApiException
11
- import com.pushizo.sdk.HsCallback
12
- import com.pushizo.sdk.HsChatEventAdapter
13
- import com.pushizo.sdk.HsChatOpenListener
14
- import com.pushizo.sdk.HsClickEvent
15
- import com.pushizo.sdk.HsForegroundEvent
16
- import com.pushizo.sdk.HsInAppClickEvent
17
- import com.pushizo.sdk.HsInAppLifecycleEvent
18
- import com.pushizo.sdk.HsInAppLifecycleListener
19
- import com.pushizo.sdk.HsInboxItem
20
- import com.pushizo.sdk.HsInboxPage
21
- import com.pushizo.sdk.HsLog
22
- import com.pushizo.sdk.HsMessageCategory
23
- import com.pushizo.sdk.HsNotification
24
- import com.pushizo.sdk.HsPreference
25
- import com.pushizo.sdk.HsPreferenceInput
26
- import com.pushizo.sdk.HsPreferencesResult
27
- import com.pushizo.sdk.HsPushSubscriptionState
28
- import org.json.JSONArray
29
- import org.json.JSONObject
30
- import java.util.concurrent.atomic.AtomicBoolean
31
- import java.util.concurrent.atomic.AtomicLong
32
-
33
- /**
34
- * Köprüden bağımsız Android çekirdeği: JS metot adlarını Pushizo Android SDK çağrılarına çevirir,
35
- * SDK olaylarını `emit(tür, veri)` ile köprüye iletir. Cordova eklentisi bu sınıfı sarar.
36
- */
37
- internal class PushizoBridgeCore(
38
- private val context: Context,
39
- private val emit: (type: String, payload: JSONObject) -> Unit,
40
- ) {
41
- /** Metot sonucu; `success(null)` boş yanıt demektir. */
42
- interface Reply {
43
- fun success(data: JSONObject?)
44
- fun error(code: String, message: String?)
45
- }
46
-
47
- /** JS tarafında ön plan dinleyicisi varsa gösterim JS kararına bırakılır. */
48
- @Volatile var foregroundHandlerEnabled = false
49
-
50
- private val listenersRegistered = AtomicBoolean(false)
51
- private val foregroundSeq = AtomicLong(0)
52
-
53
- /** Karar bekleyen ön plan bildirimleri; en eski kayıtlar düşürülür (sınırlı bellek). */
54
- private val pendingForeground = object : LinkedHashMap<String, HsForegroundEvent>() {
55
- override fun removeEldestEntry(eldest: MutableMap.MutableEntry<String, HsForegroundEvent>?): Boolean = size > MAX_PENDING_FOREGROUND
56
- }
57
-
58
- private val clickListener: (HsClickEvent) -> Unit = { e ->
59
- emit("click", JSONObject().put("notification", e.notification.toJson()).put("result", JSONObject().put("actionId", e.actionId.orNull()).put("url", e.url.orNull())))
60
- }
61
-
62
- private val foregroundListener: (HsForegroundEvent) -> Unit = { e ->
63
- val id = "fg-${foregroundSeq.incrementAndGet()}"
64
- val pending = foregroundHandlerEnabled
65
- if (pending) {
66
- // Yerel gösterim ertelenir; JS `display()` çağırırsa veya hiçbir dinleyici engellemezse gösterilir.
67
- e.preventDefault()
68
- synchronized(pendingForeground) { pendingForeground[id] = e }
69
- }
70
- emit("foregroundWillDisplay", JSONObject().put("notificationId", id).put("pending", pending).put("notification", e.notification.toJson()))
71
- }
72
-
73
- private val subscriptionObserver: (HsPushSubscriptionState) -> Unit = { s -> emit("pushSubscriptionChange", s.toJson()) }
74
-
75
- /**
76
- * Yerel SDK izin gözlemcisi: izin isteği sonucu ve uygulama ön plana döndüğünde (izin sistem ayarlarından
77
- * değişmiş olabilir) etkin izin değiştiyse çağrılır.
78
- */
79
- private val permissionObserver: (Boolean) -> Unit = { granted -> emit("permissionChange", JSONObject().put("permission", granted)) }
80
-
81
- private val inAppClickListener: (HsInAppClickEvent) -> Unit = { e ->
82
- emit("inAppClick", JSONObject().put("message", JSONObject().put("id", e.messageId)).put("result", JSONObject().put("actionId", e.actionId).put("url", e.url.orNull())))
83
- }
84
-
85
- /** Canlı sohbet olayları → JS `chatEvent` (`{ type: message|typing|read|unread|conversation|connection|error, ... }`). */
86
- private val chatListener = HsChatEventAdapter { type, payload -> emit("chatEvent", JSONObject(payload).put("type", type)) }
87
-
88
- /** Sohbet bildirimine tıklama → JS `chatOpen` (cephe dinleyici yoksa bekletir). */
89
- private val chatOpenListener = HsChatOpenListener { info -> emit("chatOpen", JSONObject(info.toMap())) }
90
-
91
- private val inAppLifecycleListener = object : HsInAppLifecycleListener {
92
- private fun send(event: String, e: HsInAppLifecycleEvent) =
93
- emit("inAppLifecycle", JSONObject().put("event", event).put("message", JSONObject().put("id", e.message.id)))
94
- override fun onWillDisplay(event: HsInAppLifecycleEvent) = send("willDisplay", event)
95
- override fun onDidDisplay(event: HsInAppLifecycleEvent) = send("didDisplay", event)
96
- override fun onWillDismiss(event: HsInAppLifecycleEvent) = send("willDismiss", event)
97
- override fun onDidDismiss(event: HsInAppLifecycleEvent) = send("didDismiss", event)
98
- }
99
-
100
- /** SDK zaten başlatıldıysa (kayıtlı ayarlarla süreç başında) dinleyicileri bağlar. */
101
- fun attachIfInitialized() {
102
- if (Pushizo.isInitialized) registerListeners()
103
- }
104
-
105
- /** SDK dinleyicileri bir kez eklenir; soğuk başlatma tıklaması ilk tıklama dinleyicisine teslim edilir. */
106
- private fun registerListeners() {
107
- if (!listenersRegistered.compareAndSet(false, true)) return
108
- Pushizo.Notifications.addClickListener(clickListener)
109
- Pushizo.Notifications.addForegroundLifecycleListener(foregroundListener)
110
- Pushizo.User.pushSubscription.addObserver(subscriptionObserver)
111
- Pushizo.Notifications.addPermissionObserver(permissionObserver)
112
- Pushizo.InAppMessages.addClickListener(inAppClickListener)
113
- Pushizo.InAppMessages.addLifecycleListener(inAppLifecycleListener)
114
- Pushizo.Chat.addListener(chatListener)
115
- Pushizo.Chat.addOpenListener(chatOpenListener)
116
- }
117
-
118
- fun detach() {
119
- if (!listenersRegistered.compareAndSet(true, false)) return
120
- Pushizo.Notifications.removeClickListener(clickListener)
121
- Pushizo.Notifications.removeForegroundLifecycleListener(foregroundListener)
122
- Pushizo.User.pushSubscription.removeObserver(subscriptionObserver)
123
- Pushizo.Notifications.removePermissionObserver(permissionObserver)
124
- Pushizo.InAppMessages.removeClickListener(inAppClickListener)
125
- Pushizo.InAppMessages.removeLifecycleListener(inAppLifecycleListener)
126
- Pushizo.Chat.removeListener(chatListener)
127
- Pushizo.Chat.removeOpenListener(chatOpenListener)
128
- // Bekleyen ön plan bildirimleri kaybolmasın diye gösterilir.
129
- val pending = synchronized(pendingForeground) { pendingForeground.values.toList().also { pendingForeground.clear() } }
130
- pending.forEach { it.display() }
131
- }
132
-
133
- /** İzin isteği sonuçlandı: SDK aboneliği günceller; izin değiştiyse yerel izin gözlemcisi olayı gönderir. */
134
- fun onPermissionResult() {
135
- Pushizo.Notifications.onPermissionResult()
136
- }
137
-
138
- fun permissionJson(): JSONObject = JSONObject().put("permission", Pushizo.Notifications.permission)
139
-
140
- // --- Konum izni (v2 Faz 17b) ---
141
-
142
- /**
143
- * Konum izni akışı: Android SDK'nın `Location.requestPermission` sonucu geri çağrıyla bildirilmediğinden köprü aynı
144
- * adımları kendi izin mekanizmasıyla yürütür. İzin zaten varsa true; uygulama manifest'inde konum izni yoksa veya
145
- * Activity yoksa false. Değilse açıklama diyaloğu gösterilir (başlık/düğmeler SDK string kaynakları, mesaj
146
- * `rationale` ya da SDK varsayılanı); "Şimdi değil"/iptal false döner, "Devam" ise [requestSystem] ile köprünün izin
147
- * API'si üzerinden sistem izni istenir — sonuç geldiğinde köprü [onLocationPermissionResult] yanıtını döndürür.
148
- */
149
- fun requestLocationPermission(activity: Activity?, args: JSONObject, reply: Reply, requestSystem: (Array<String>) -> Unit) {
150
- if (!Pushizo.isInitialized) {
151
- reply.error("NOT_READY", NOT_INITIALIZED)
152
- return
153
- }
154
- if (Pushizo.Location.permissionGranted) {
155
- reply.success(onLocationPermissionResult())
156
- return
157
- }
158
- val permissions = declaredLocationPermissions()
159
- if (permissions.isEmpty()) {
160
- HsLog.w("konum izni istenemedi: uygulama manifest'inde ACCESS_COARSE_LOCATION/ACCESS_FINE_LOCATION yok")
161
- reply.success(locationPermissionJson())
162
- return
163
- }
164
- if (activity == null || activity.isFinishing || activity.isDestroyed) {
165
- HsLog.w("konum izni istenemedi: etkin Activity yok")
166
- reply.success(locationPermissionJson())
167
- return
168
- }
169
- val rationale = args.optStringOrNull("rationale")?.takeIf { it.isNotBlank() }
170
- activity.runOnUiThread {
171
- if (activity.isFinishing || activity.isDestroyed) {
172
- reply.success(locationPermissionJson())
173
- return@runOnUiThread
174
- }
175
- AlertDialog.Builder(activity)
176
- .setTitle(com.pushizo.sdk.R.string.hs_location_rationale_title)
177
- .setMessage(rationale ?: activity.getString(com.pushizo.sdk.R.string.hs_location_rationale_message))
178
- .setPositiveButton(com.pushizo.sdk.R.string.hs_location_rationale_continue) { _, _ -> requestSystem(permissions) }
179
- .setNegativeButton(com.pushizo.sdk.R.string.hs_location_rationale_not_now) { _, _ -> reply.success(locationPermissionJson()) }
180
- .setOnCancelListener { reply.success(locationPermissionJson()) }
181
- .show()
182
- }
183
- }
184
-
185
- /** Sistem izin sonucu: SDK bilgilendirilir (izin verildiyse ve paylaşım açıksa konum gönderilir), güncel izin döner. */
186
- fun onLocationPermissionResult(): JSONObject {
187
- Pushizo.Location.onPermissionResult()
188
- return locationPermissionJson()
189
- }
190
-
191
- fun locationPermissionJson(): JSONObject = JSONObject().put("permission", Pushizo.Location.permissionGranted)
192
-
193
- /** Uygulama manifest'inde tanımlı konum izinleri (eklenti izinleri otomatik eklemez; README "Konum"). */
194
- private fun declaredLocationPermissions(): Array<String> {
195
- val requested = try {
196
- val pm = context.packageManager
197
- val info = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
198
- pm.getPackageInfo(context.packageName, PackageManager.PackageInfoFlags.of(PackageManager.GET_PERMISSIONS.toLong()))
199
- } else {
200
- @Suppress("DEPRECATION")
201
- pm.getPackageInfo(context.packageName, PackageManager.GET_PERMISSIONS)
202
- }
203
- info.requestedPermissions?.toSet().orEmpty()
204
- } catch (e: PackageManager.NameNotFoundException) {
205
- emptySet()
206
- }
207
- return LOCATION_PERMISSIONS.filter { it in requested }.toTypedArray()
208
- }
209
-
210
- /**
211
- * Metodu çalıştırır. Bilinmeyen metotta false döner. `requestPermission` ve `requestLocationPermission` Activity
212
- * gerektirdiğinden köprü sınıfında ele alınır.
213
- */
214
- fun handle(method: String, args: JSONObject, reply: Reply): Boolean {
215
- try {
216
- when (method) {
217
- "initialize" -> {
218
- val config = PushizoConfigStore.Config(
219
- appId = args.requireString("appId"),
220
- apiUrl = args.optStringOrNull("apiUrl") ?: Pushizo.Options().apiUrl,
221
- requiresPrivacyConsent = args.optBoolean("requiresPrivacyConsent", false),
222
- logLevel = args.optStringOrNull("logLevel") ?: "warn",
223
- )
224
- // Süreç yeniden başladığında (bildirim tıklaması, FCM servisi) SDK erkenden başlatılabilsin diye saklanır.
225
- PushizoConfigStore.save(context, config)
226
- Pushizo.initialize(context, config.appId, config.toOptions())
227
- registerListeners()
228
- reply.success(null)
229
- }
230
- "setConsentGiven" -> { Pushizo.setConsentGiven(args.optBoolean("given", false)); reply.success(null) }
231
- "login" -> {
232
- Pushizo.login(args.requireString("externalId"), args.optStringOrNull("identityHash"), args.optStringOrNull("jwt"))
233
- reply.success(null)
234
- }
235
- "updateUserJwt" -> { Pushizo.updateUserJwt(args.requireString("jwt")); reply.success(null) }
236
- "logout" -> { Pushizo.logout(); reply.success(null) }
237
-
238
- "addTags" -> { Pushizo.User.addTags(args.stringMap("tags")); reply.success(null) }
239
- "removeTags" -> { Pushizo.User.removeTags(args.stringList("keys")); reply.success(null) }
240
- "getTags" -> reply.success(JSONObject().put("tags", JSONObject(Pushizo.User.getTags())))
241
- "addAliases" -> { Pushizo.User.addAliases(args.stringMap("aliases")); reply.success(null) }
242
- "removeAlias" -> { Pushizo.User.removeAlias(args.requireString("label")); reply.success(null) }
243
- "setLanguage" -> { Pushizo.User.setLanguage(args.requireString("code")); reply.success(null) }
244
- // Geçersiz adres → IllegalArgumentException → INVALID_ARGUMENT
245
- "addEmail" -> { Pushizo.User.addEmail(args.requireString("email")); reply.success(null) }
246
- "removeEmail" -> { Pushizo.User.removeEmail(args.requireString("email")); reply.success(null) }
247
- "addSms" -> { Pushizo.User.addSms(args.requireString("phoneNumber")); reply.success(null) }
248
- "removeSms" -> { Pushizo.User.removeSms(args.requireString("phoneNumber")); reply.success(null) }
249
- "getUser" -> reply.success(JSONObject().put("id", Pushizo.User.id.orNull()).put("externalId", Pushizo.User.externalId.orNull()))
250
- "getContacts" -> reply.success(
251
- JSONObject().put("emails", JSONArray(Pushizo.User.emails)).put("smsNumbers", JSONArray(Pushizo.User.smsNumbers)),
252
- )
253
- // Tercihler (ADR-0019 §4): sahiplik kanıtı yerel SDK'da eklenir; doğrulama hatası INVALID_ARGUMENT, abonelik yoksa NOT_READY.
254
- "getPreferences" -> Pushizo.User.getPreferences(callback(reply) { it.toJson() })
255
- "setPreferences" -> Pushizo.User.setPreferences(args.preferenceInputs("preferences"), callback(reply) { it.toJson() })
256
-
257
- "getPushSubscription" -> reply.success(Pushizo.User.pushSubscription.state.toJson())
258
- "optIn" -> { Pushizo.User.pushSubscription.optIn(); reply.success(null) }
259
- "optOut" -> { Pushizo.User.pushSubscription.optOut(); reply.success(null) }
260
-
261
- "getPermission" -> reply.success(permissionJson())
262
- "clearAll" -> { Pushizo.Notifications.clearAll(); reply.success(null) }
263
- "removeNotification" -> {
264
- // Android tepsi kimliği tamsayıdır; metin kimlik (iOS biçimi) yalnızca sayıysa kabul edilir.
265
- val id = when {
266
- args.has("id") -> args.getInt("id")
267
- else -> args.optStringOrNull("identifier")?.trim()?.toIntOrNull()
268
- ?: throw IllegalArgumentException("id gerekli (Android bildirim kimliği tamsayıdır)")
269
- }
270
- Pushizo.Notifications.removeNotification(id)
271
- reply.success(null)
272
- }
273
- "removeGroupedNotifications" -> { Pushizo.Notifications.removeGroupedNotifications(args.requireString("group")); reply.success(null) }
274
- "setForegroundHandlerEnabled" -> { foregroundHandlerEnabled = args.optBoolean("enabled", false); reply.success(null) }
275
- "displayNotification" -> {
276
- val id = args.requireString("notificationId")
277
- val event = synchronized(pendingForeground) { pendingForeground.remove(id) }
278
- if (event == null) {
279
- reply.error("NOT_FOUND", "Bildirim bulunamadı veya zaten gösterildi.")
280
- } else {
281
- event.display()
282
- reply.success(null)
283
- }
284
- }
285
-
286
- "sendEvent" -> {
287
- val value = if (args.has("value") && !args.isNull("value")) args.getDouble("value") else null
288
- Pushizo.Session.sendEvent(args.requireString("name"), args.optJSONObject("properties")?.toMap() ?: emptyMap(), value)
289
- reply.success(null)
290
- }
291
- "setLogLevel" -> { Pushizo.Debug.setLogLevel(logLevel(args.optStringOrNull("level"))); reply.success(null) }
292
-
293
- "addTriggers" -> { Pushizo.InAppMessages.addTriggers(args.stringMap("triggers")); reply.success(null) }
294
- "removeTriggers" -> { Pushizo.InAppMessages.removeTriggers(args.stringList("keys")); reply.success(null) }
295
- "clearTriggers" -> { Pushizo.InAppMessages.clearTriggers(); reply.success(null) }
296
- "getTriggers" -> reply.success(JSONObject().put("triggers", JSONObject(Pushizo.InAppMessages.getTriggers())))
297
- "setScreen" -> { Pushizo.InAppMessages.setScreen(args.optStringOrNull("name")); reply.success(null) }
298
- "setInAppPaused" -> { Pushizo.InAppMessages.paused = args.optBoolean("paused", false); reply.success(null) }
299
- "getInAppPaused" -> reply.success(JSONObject().put("paused", Pushizo.InAppMessages.paused))
300
-
301
- "inboxList" -> Pushizo.Inbox.list(args.optInt("limit", 50), args.optStringOrNull("cursor"), callback(reply) { it.toJson() })
302
- "inboxMarkRead" -> Pushizo.Inbox.markRead(args.requireString("id"), callback(reply) { it.toJson() })
303
- "inboxMarkAllRead" -> Pushizo.Inbox.markAllRead(callback(reply) { JSONObject().put("unreadCount", it) })
304
- "inboxArchive" -> Pushizo.Inbox.archive(args.requireString("id"), callback(reply) { null })
305
- "inboxUnreadCount" -> Pushizo.Inbox.unreadCount(callback(reply) { JSONObject().put("unreadCount", it) })
306
-
307
- // Konum (v2 Faz 17b): izin isteği Activity gerektirdiğinden köprü sınıfında ele alınır.
308
- "setLocationShared" -> {
309
- check(Pushizo.isInitialized) { NOT_INITIALIZED }
310
- Pushizo.Location.setShared(args.optBoolean("shared", false))
311
- reply.success(null)
312
- }
313
- "isLocationShared" -> reply.success(JSONObject().put("shared", Pushizo.Location.isShared))
314
-
315
- // Live Activities yalnızca iOS'ta vardır (ADR-0024); Android'de sessizce başarılı dönülmez.
316
- "setupDefaultLiveActivity" -> reply.error(LIVE_ACTIVITY_UNSUPPORTED_CODE, LIVE_ACTIVITY_UNSUPPORTED_MESSAGE)
317
- "startDefaultLiveActivity" -> reply.error(LIVE_ACTIVITY_UNSUPPORTED_CODE, LIVE_ACTIVITY_UNSUPPORTED_MESSAGE)
318
- // Canlı sohbet (ADR-0040): kimlik, kuyruk, akış ve push native SDK'dadır.
319
- "chatStart" -> Pushizo.Chat.start(args.optStringOrNull("name"), args.optStringOrNull("email"), args.optStringOrNull("language"), callback(reply) { JSONObject(it.toMap()) })
320
- "chatGetConfig" -> Pushizo.Chat.getConfig(args.optStringOrNull("language"), callback(reply) { JSONObject(it.toMap()) })
321
- "chatGetConversation" -> Pushizo.Chat.getConversation(callback(reply) { JSONObject(it.toMap()) })
322
- "chatGetMessages" -> Pushizo.Chat.getMessages(
323
- args.optLongOrNull("afterSeq"), args.optLongOrNull("beforeSeq"), args.optInt("limit", 50), callback(reply) { JSONObject(it.toMap()) },
324
- )
325
- "chatSendMessage" -> Pushizo.Chat.sendMessage(args.requireString("text"), args.optStringOrNull("optionId"), callback(reply) { it.toJson() })
326
- "chatSendAttachment" -> {
327
- val fileName = args.requireString("fileName")
328
- val mimeType = args.requireString("mimeType")
329
- val text = args.optStringOrNull("text")
330
- val base64 = args.optStringOrNull("base64")
331
- if (base64 != null) {
332
- val bytes = android.util.Base64.decode(base64, android.util.Base64.DEFAULT)
333
- Pushizo.Chat.sendAttachment(bytes, fileName, mimeType, text, callback(reply) { it.toJson() })
334
- } else {
335
- Pushizo.Chat.sendAttachment(android.net.Uri.parse(args.requireString("uri")), fileName, mimeType, text, callback(reply) { it.toJson() })
336
- }
337
- }
338
- "chatMarkRead" -> Pushizo.Chat.markRead(args.optLong("seq", 0L), callback(reply) { JSONObject().put("unreadCount", it) })
339
- "chatRefreshUnreadCount" -> Pushizo.Chat.refreshUnreadCount(callback(reply) { JSONObject().put("unreadCount", it) })
340
- "chatGetUnreadCount" -> reply.success(JSONObject().put("unreadCount", Pushizo.Chat.unreadCount))
341
- "chatLeaveOfflineMessage" -> Pushizo.Chat.leaveOfflineMessage(
342
- args.requireString("email"), args.requireString("text"), args.optStringOrNull("name"), callback(reply) { it.toJson() },
343
- )
344
- "chatSetTyping" -> { Pushizo.Chat.setTyping(args.optBoolean("typing", false)); reply.success(null) }
345
- "chatStartListening" -> { Pushizo.Chat.startListening(); reply.success(null) }
346
- "chatStopListening" -> { Pushizo.Chat.stopListening(); reply.success(null) }
347
- "chatAttachmentUrl" -> reply.success(
348
- JSONObject().put("url", Pushizo.Chat.attachmentUrl(args.requireString("attachmentId"), args.optBoolean("download", false))),
349
- )
350
- "chatGetVisitorId" -> reply.success(JSONObject().put("visitorId", Pushizo.Chat.visitorId.orNull()))
351
- else -> return false
352
- }
353
- } catch (e: IllegalArgumentException) {
354
- reply.error("INVALID_ARGUMENT", e.message)
355
- } catch (e: IllegalStateException) {
356
- reply.error("NOT_READY", e.message)
357
- } catch (e: Exception) {
358
- reply.error("HS_ERROR", e.message)
359
- }
360
- return true
361
- }
362
-
363
- /** SDK geri çağrısını köprü yanıtına çevirir; API hatasında sunucu kodu korunur. */
364
- private fun <T> callback(reply: Reply, map: (T) -> JSONObject?) = HsCallback<T> { result ->
365
- result.fold(
366
- onSuccess = { reply.success(map(it)) },
367
- onFailure = { e ->
368
- val code = when (e) {
369
- is HsApiException -> e.code
370
- is IllegalStateException -> "NOT_READY"
371
- is IllegalArgumentException -> "INVALID_ARGUMENT"
372
- else -> "HS_ERROR"
373
- }
374
- reply.error(code, e.message)
375
- },
376
- )
377
- }
378
-
379
- companion object {
380
- private const val MAX_PENDING_FOREGROUND = 32
381
- private const val NOT_INITIALIZED = "Önce Pushizo.initialize çağrılmalı"
382
- private val LOCATION_PERMISSIONS = arrayOf(Manifest.permission.ACCESS_COARSE_LOCATION, Manifest.permission.ACCESS_FINE_LOCATION)
383
- private const val LIVE_ACTIVITY_UNSUPPORTED_CODE = "PLATFORM_NOT_SUPPORTED"
384
- private const val LIVE_ACTIVITY_UNSUPPORTED_MESSAGE = "Live Activities yalnızca iOS'ta desteklenir"
385
-
386
- fun logLevel(name: String?): HsLog.Level = when (name) {
387
- "none" -> HsLog.Level.NONE
388
- "error" -> HsLog.Level.ERROR
389
- "info" -> HsLog.Level.INFO
390
- "debug" -> HsLog.Level.DEBUG
391
- else -> HsLog.Level.WARN
392
- }
393
-
394
- fun HsNotification.toJson(): JSONObject = JSONObject()
395
- .put("title", title.orNull())
396
- .put("body", body.orNull())
397
- .put("url", url.orNull())
398
- .put("imageUrl", imageUrl.orNull())
399
- .put("deliveryId", deliveryId.orNull())
400
- .put("messageId", messageId.orNull())
401
- .put("data", JSONObject(data))
402
- .put("androidNotificationId", androidNotificationId)
403
-
404
- fun HsPushSubscriptionState.toJson(): JSONObject = JSONObject()
405
- .put("id", id.orNull())
406
- .put("token", token.orNull())
407
- .put("optedIn", optedIn)
408
- .put("permission", permission)
409
-
410
- fun HsInboxItem.toJson(): JSONObject = JSONObject()
411
- .put("id", id)
412
- .put("messageId", messageId.orNull())
413
- .put("title", title.orNull())
414
- .put("body", body.orNull())
415
- .put("url", url.orNull())
416
- .put("imageUrl", imageUrl.orNull())
417
- .put("data", JSONObject(data))
418
- .put("read", read)
419
- .put("readAt", readAt.orNull())
420
- .put("archivedAt", archivedAt.orNull())
421
- .put("expiresAt", expiresAt.orNull())
422
- .put("createdAt", createdAt.orNull())
423
-
424
- fun HsInboxPage.toJson(): JSONObject = JSONObject()
425
- .put("items", JSONArray(items.map { it.toJson() }))
426
- .put("unreadCount", unreadCount)
427
- .put("nextCursor", nextCursor.orNull())
428
- .put("hasMore", hasMore)
429
-
430
- fun HsPreference.toJson(): JSONObject = JSONObject()
431
- .put("category", category)
432
- .put("channel", channel.orNull())
433
- .put("optedIn", optedIn)
434
- .put("explicit", explicit)
435
- .put("source", source.orNull())
436
- .put("updatedAt", updatedAt.orNull())
437
-
438
- fun HsMessageCategory.toJson(): JSONObject = JSONObject()
439
- .put("key", key)
440
- .put("name", JSONObject(name))
441
- .put("description", JSONObject(description))
442
- .put("channels", channels?.let { JSONArray(it) }.orNull())
443
- .put("defaultOptedIn", defaultOptedIn)
444
-
445
- fun HsPreferencesResult.toJson(): JSONObject = JSONObject()
446
- .put("preferences", JSONArray(preferences.map { it.toJson() }))
447
- .put("categories", JSONArray(categories.map { it.toJson() }))
448
-
449
- /** JS `{ category, channel, optedIn }[]` → SDK girdisi; kural denetimi (1-100, kanal) SDK'dadır. */
450
- fun JSONObject.preferenceInputs(key: String): List<HsPreferenceInput> {
451
- val arr = optJSONArray(key) ?: throw IllegalArgumentException("$key gerekli")
452
- return (0 until arr.length()).map { i ->
453
- val item = arr.optJSONObject(i) ?: throw IllegalArgumentException("$key[$i] nesne olmalı")
454
- HsPreferenceInput(item.requireString("category"), item.optStringOrNull("channel"), item.optBoolean("optedIn", false))
455
- }
456
- }
457
-
458
- private fun Any?.orNull(): Any = this ?: JSONObject.NULL
459
-
460
- fun JSONObject.optStringOrNull(key: String): String? = if (has(key) && !isNull(key)) optString(key) else null
461
-
462
- fun JSONObject.optLongOrNull(key: String): Long? = if (has(key) && !isNull(key)) optLong(key) else null
463
-
464
- fun JSONObject.requireString(key: String): String =
465
- optStringOrNull(key)?.takeIf { it.isNotBlank() } ?: throw IllegalArgumentException("$key gerekli")
466
-
467
- fun JSONObject.stringMap(key: String): Map<String, String> {
468
- val obj = optJSONObject(key) ?: return emptyMap()
469
- val out = LinkedHashMap<String, String>()
470
- obj.keys().forEach { k -> if (!obj.isNull(k)) out[k] = obj.get(k).toString() }
471
- return out
472
- }
473
-
474
- fun JSONObject.stringList(key: String): List<String> {
475
- val arr = optJSONArray(key) ?: return emptyList()
476
- return (0 until arr.length()).mapNotNull { i -> if (arr.isNull(i)) null else arr.get(i).toString() }
477
- }
478
-
479
- /** JSON nesnesini SDK'nın beklediği Map/List yapısına çevirir (iç içe değerler korunur). */
480
- fun JSONObject.toMap(): Map<String, Any?> {
481
- val out = LinkedHashMap<String, Any?>()
482
- keys().forEach { k -> out[k] = unwrap(get(k)) }
483
- return out
484
- }
485
-
486
- private fun unwrap(value: Any?): Any? = when (value) {
487
- JSONObject.NULL, null -> null
488
- is JSONObject -> value.toMap()
489
- is JSONArray -> (0 until value.length()).map { unwrap(value.get(it)) }
490
- else -> value
491
- }
492
- }
493
- }
1
+ package com.pushizo.cordova
2
+
3
+ import android.Manifest
4
+ import android.app.Activity
5
+ import android.app.AlertDialog
6
+ import android.app.Application
7
+ import android.content.Context
8
+ import android.content.pm.PackageManager
9
+ import android.os.Build
10
+ import android.os.Bundle
11
+ import com.pushizo.sdk.Pushizo
12
+ import com.pushizo.sdk.HsApiException
13
+ import com.pushizo.sdk.HsCallback
14
+ import com.pushizo.sdk.HsChatActivity
15
+ import com.pushizo.sdk.HsChatEventAdapter
16
+ import com.pushizo.sdk.HsChatOpenListener
17
+ import com.pushizo.sdk.HsClickEvent
18
+ import com.pushizo.sdk.HsConsent
19
+ import com.pushizo.sdk.HsForegroundEvent
20
+ import com.pushizo.sdk.HsInAppAction
21
+ import com.pushizo.sdk.HsInAppBlock
22
+ import com.pushizo.sdk.HsInAppCarouselCard
23
+ import com.pushizo.sdk.HsInAppClickEvent
24
+ import com.pushizo.sdk.HsInAppDisplay
25
+ import com.pushizo.sdk.HsInAppLifecycleEvent
26
+ import com.pushizo.sdk.HsInAppLifecycleListener
27
+ import com.pushizo.sdk.HsInAppMessage
28
+ import com.pushizo.sdk.HsInAppTrigger
29
+ import com.pushizo.sdk.HsContentCard
30
+ import com.pushizo.sdk.HsContentCardFeed
31
+ import com.pushizo.sdk.HsDeliverySetting
32
+ import com.pushizo.sdk.HsDeliveryStatus
33
+ import com.pushizo.sdk.HsFeatureFlagObserver
34
+ import com.pushizo.sdk.HsInboxItem
35
+ import com.pushizo.sdk.HsInboxObserver
36
+ import com.pushizo.sdk.HsInboxPage
37
+ import com.pushizo.sdk.HsLog
38
+ import com.pushizo.sdk.HsMessageCategory
39
+ import com.pushizo.sdk.HsNotification
40
+ import com.pushizo.sdk.HsPreference
41
+ import com.pushizo.sdk.HsPreferenceInput
42
+ import com.pushizo.sdk.HsPreferencesResult
43
+ import com.pushizo.sdk.HsPushSubscriptionState
44
+ import com.pushizo.sdk.HsUserProfile
45
+ import org.json.JSONArray
46
+ import org.json.JSONObject
47
+ import java.util.Collections
48
+ import java.util.WeakHashMap
49
+ import java.util.concurrent.atomic.AtomicBoolean
50
+ import java.util.concurrent.atomic.AtomicLong
51
+
52
+ /**
53
+ * Köprüden bağımsız Android çekirdeği: JS metot adlarını Pushizo Android SDK çağrılarına çevirir,
54
+ * SDK olaylarını `emit(tür, veri)` ile köprüye iletir. Cordova eklentisi bu sınıfı sarar.
55
+ */
56
+ internal class PushizoBridgeCore(
57
+ private val context: Context,
58
+ private val emit: (type: String, payload: JSONObject) -> Unit,
59
+ ) {
60
+ /** Metot sonucu; `success(null)` boş yanıt demektir. */
61
+ interface Reply {
62
+ fun success(data: JSONObject?)
63
+ fun error(code: String, message: String?)
64
+ }
65
+
66
+ /** JS tarafında ön plan dinleyicisi varsa gösterim JS kararına bırakılır. */
67
+ @Volatile var foregroundHandlerEnabled = false
68
+
69
+ /** Köprünün etkin Activity'si (teslimat ayar ekranı ve açıklama diyaloğu için); köprü sınıfı atar, yoksa null döner. */
70
+ @Volatile var activityProvider: (() -> Activity?)? = null
71
+
72
+ private val listenersRegistered = AtomicBoolean(false)
73
+ private val foregroundSeq = AtomicLong(0)
74
+
75
+ /** Karar bekleyen ön plan bildirimleri; en eski kayıtlar düşürülür (sınırlı bellek). */
76
+ private val pendingForeground = object : LinkedHashMap<String, HsForegroundEvent>() {
77
+ override fun removeEldestEntry(eldest: MutableMap.MutableEntry<String, HsForegroundEvent>?): Boolean = size > MAX_PENDING_FOREGROUND
78
+ }
79
+
80
+ /** Son `placementsList` yanıtlarındaki mesajlar (kimliğe göre); raporlar bu nesnelerle yapılır, en eski kayıtlar düşürülür. */
81
+ private val placementMessages = object : LinkedHashMap<String, HsInAppMessage>() {
82
+ override fun removeEldestEntry(eldest: MutableMap.MutableEntry<String, HsInAppMessage>?): Boolean = size > MAX_PLACEMENT_CACHE
83
+ }
84
+
85
+ private val clickListener: (HsClickEvent) -> Unit = { e ->
86
+ emit("click", JSONObject().put("notification", e.notification.toJson()).put("result", JSONObject().put("actionId", e.actionId.orNull()).put("url", e.url.orNull())))
87
+ }
88
+
89
+ private val foregroundListener: (HsForegroundEvent) -> Unit = { e ->
90
+ val id = "fg-${foregroundSeq.incrementAndGet()}"
91
+ val pending = foregroundHandlerEnabled
92
+ if (pending) {
93
+ // Yerel gösterim ertelenir; JS `display()` çağırırsa veya hiçbir dinleyici engellemezse gösterilir.
94
+ e.preventDefault()
95
+ synchronized(pendingForeground) { pendingForeground[id] = e }
96
+ }
97
+ emit("foregroundWillDisplay", JSONObject().put("notificationId", id).put("pending", pending).put("notification", e.notification.toJson()))
98
+ }
99
+
100
+ private val subscriptionObserver: (HsPushSubscriptionState) -> Unit = { s -> emit("pushSubscriptionChange", s.toJson()) }
101
+
102
+ /**
103
+ * Yerel SDK izin gözlemcisi: izin isteği sonucu ve uygulama ön plana döndüğünde (izin sistem ayarlarından
104
+ * değişmiş olabilir) etkin izin değiştiyse çağrılır.
105
+ */
106
+ private val permissionObserver: (Boolean) -> Unit = { granted -> emit("permissionChange", JSONObject().put("permission", granted)) }
107
+
108
+ private val inAppClickListener: (HsInAppClickEvent) -> Unit = { e ->
109
+ emit("inAppClick", JSONObject().put("message", JSONObject().put("id", e.messageId)).put("result", JSONObject().put("actionId", e.actionId).put("url", e.url.orNull())))
110
+ }
111
+
112
+ /** Canlı sohbet olayları → JS `chatEvent` (`{ type: message|typing|read|unread|conversation|connection|error, ... }`). */
113
+ private val chatListener = HsChatEventAdapter { type, payload -> emit("chatEvent", JSONObject(payload).put("type", type)) }
114
+
115
+ /** Sohbet bildirimine tıklama → JS `chatOpen` (cephe dinleyici yoksa bekletir). */
116
+ private val chatOpenListener = HsChatOpenListener { info -> emit("chatOpen", JSONObject(info.toMap())) }
117
+
118
+ /** Özellik bayrakları sunucudan yenilendi → JS `featureFlagsChange` (yerel SDK ana iş parçacığında çağırır). */
119
+ private val featureFlagObserver = HsFeatureFlagObserver { emit("featureFlagsChange", JSONObject()) }
120
+
121
+ /** Bildirim kutusu değişti → JS `inboxChange` (`{ type, itemId, unreadCount }`; `itemId` tek öğe olayları dışında null). */
122
+ private val inboxObserver = HsInboxObserver { event -> emit("inboxChange", JSONObject(event.toMap())) }
123
+
124
+ /**
125
+ * Açık hazır sohbet ekranları. Yerel SDK ekranın açık olup olmadığını dışa açmadığından (`Chat.hide()` yalnızca
126
+ * kapatır) köprü `HsChatActivity` yaşam döngüsünü izler; kayıtlar zayıf tutulur.
127
+ */
128
+ private val chatScreens: MutableSet<Activity> = Collections.newSetFromMap(WeakHashMap())
129
+
130
+ private val chatScreenTracker = object : Application.ActivityLifecycleCallbacks {
131
+ override fun onActivityCreated(activity: Activity, savedInstanceState: Bundle?) {
132
+ if (activity is HsChatActivity) synchronized(chatScreens) { chatScreens.add(activity) }
133
+ }
134
+ override fun onActivityDestroyed(activity: Activity) {
135
+ if (activity is HsChatActivity) synchronized(chatScreens) { chatScreens.remove(activity) }
136
+ }
137
+ override fun onActivityStarted(activity: Activity) = Unit
138
+ override fun onActivityResumed(activity: Activity) = Unit
139
+ override fun onActivityPaused(activity: Activity) = Unit
140
+ override fun onActivityStopped(activity: Activity) = Unit
141
+ override fun onActivitySaveInstanceState(activity: Activity, outState: Bundle) = Unit
142
+ }
143
+
144
+ init {
145
+ (context.applicationContext as? Application)?.registerActivityLifecycleCallbacks(chatScreenTracker)
146
+ }
147
+
148
+ /** `Chat.show()` ile açılan sohbet ekranı açık mı (kapanmakta olan ekran sayılmaz). */
149
+ private fun isChatPresented(): Boolean = synchronized(chatScreens) { chatScreens.any { !it.isFinishing && !it.isDestroyed } }
150
+
151
+ private val inAppLifecycleListener = object : HsInAppLifecycleListener {
152
+ private fun send(event: String, e: HsInAppLifecycleEvent) =
153
+ emit("inAppLifecycle", JSONObject().put("event", event).put("message", JSONObject().put("id", e.message.id)))
154
+ override fun onWillDisplay(event: HsInAppLifecycleEvent) = send("willDisplay", event)
155
+ override fun onDidDisplay(event: HsInAppLifecycleEvent) = send("didDisplay", event)
156
+ override fun onWillDismiss(event: HsInAppLifecycleEvent) = send("willDismiss", event)
157
+ override fun onDidDismiss(event: HsInAppLifecycleEvent) = send("didDismiss", event)
158
+ }
159
+
160
+ /** SDK zaten başlatıldıysa (kayıtlı ayarlarla süreç başında) dinleyicileri bağlar. */
161
+ fun attachIfInitialized() {
162
+ if (Pushizo.isInitialized) registerListeners()
163
+ }
164
+
165
+ /** SDK dinleyicileri bir kez eklenir; soğuk başlatma tıklaması ilk tıklama dinleyicisine teslim edilir. */
166
+ private fun registerListeners() {
167
+ if (!listenersRegistered.compareAndSet(false, true)) return
168
+ Pushizo.Notifications.addClickListener(clickListener)
169
+ Pushizo.Notifications.addForegroundLifecycleListener(foregroundListener)
170
+ Pushizo.User.pushSubscription.addObserver(subscriptionObserver)
171
+ Pushizo.Notifications.addPermissionObserver(permissionObserver)
172
+ Pushizo.InAppMessages.addClickListener(inAppClickListener)
173
+ Pushizo.InAppMessages.addLifecycleListener(inAppLifecycleListener)
174
+ Pushizo.Chat.addListener(chatListener)
175
+ Pushizo.Chat.addOpenListener(chatOpenListener)
176
+ Pushizo.FeatureFlags.addObserver(featureFlagObserver)
177
+ Pushizo.Inbox.addObserver(inboxObserver)
178
+ }
179
+
180
+ fun detach() {
181
+ (context.applicationContext as? Application)?.unregisterActivityLifecycleCallbacks(chatScreenTracker)
182
+ if (!listenersRegistered.compareAndSet(true, false)) return
183
+ Pushizo.Notifications.removeClickListener(clickListener)
184
+ Pushizo.Notifications.removeForegroundLifecycleListener(foregroundListener)
185
+ Pushizo.User.pushSubscription.removeObserver(subscriptionObserver)
186
+ Pushizo.Notifications.removePermissionObserver(permissionObserver)
187
+ Pushizo.InAppMessages.removeClickListener(inAppClickListener)
188
+ Pushizo.InAppMessages.removeLifecycleListener(inAppLifecycleListener)
189
+ Pushizo.Chat.removeListener(chatListener)
190
+ Pushizo.Chat.removeOpenListener(chatOpenListener)
191
+ Pushizo.FeatureFlags.removeObserver(featureFlagObserver)
192
+ Pushizo.Inbox.removeObserver(inboxObserver)
193
+ // Bekleyen ön plan bildirimleri kaybolmasın diye gösterilir.
194
+ val pending = synchronized(pendingForeground) { pendingForeground.values.toList().also { pendingForeground.clear() } }
195
+ pending.forEach { it.display() }
196
+ }
197
+
198
+ /** İzin isteği sonuçlandı: SDK aboneliği günceller; izin değiştiyse yerel izin gözlemcisi olayı gönderir. */
199
+ fun onPermissionResult() {
200
+ Pushizo.Notifications.onPermissionResult()
201
+ }
202
+
203
+ fun permissionJson(): JSONObject = JSONObject().put("permission", Pushizo.Notifications.permission)
204
+
205
+ // --- Konum izni (v2 Faz 17b) ---
206
+
207
+ /**
208
+ * Konum izni akışı: Android SDK'nın `Location.requestPermission` sonucu geri çağrıyla bildirilmediğinden köprü aynı
209
+ * adımları kendi izin mekanizmasıyla yürütür. İzin zaten varsa true; uygulama manifest'inde konum izni yoksa veya
210
+ * Activity yoksa false. Değilse açıklama diyaloğu gösterilir (başlık/düğmeler SDK string kaynakları, mesaj
211
+ * `rationale` ya da SDK varsayılanı); "Şimdi değil"/iptal false döner, "Devam" ise [requestSystem] ile köprünün izin
212
+ * API'si üzerinden sistem izni istenir — sonuç geldiğinde köprü [onLocationPermissionResult] yanıtını döndürür.
213
+ */
214
+ fun requestLocationPermission(activity: Activity?, args: JSONObject, reply: Reply, requestSystem: (Array<String>) -> Unit) {
215
+ if (!Pushizo.isInitialized) {
216
+ reply.error("NOT_READY", NOT_INITIALIZED)
217
+ return
218
+ }
219
+ if (Pushizo.Location.permissionGranted) {
220
+ reply.success(onLocationPermissionResult())
221
+ return
222
+ }
223
+ val permissions = declaredLocationPermissions()
224
+ if (permissions.isEmpty()) {
225
+ HsLog.w("konum izni istenemedi: uygulama manifest'inde ACCESS_COARSE_LOCATION/ACCESS_FINE_LOCATION yok")
226
+ reply.success(locationPermissionJson())
227
+ return
228
+ }
229
+ if (activity == null || activity.isFinishing || activity.isDestroyed) {
230
+ HsLog.w("konum izni istenemedi: etkin Activity yok")
231
+ reply.success(locationPermissionJson())
232
+ return
233
+ }
234
+ val rationale = args.optStringOrNull("rationale")?.takeIf { it.isNotBlank() }
235
+ activity.runOnUiThread {
236
+ if (activity.isFinishing || activity.isDestroyed) {
237
+ reply.success(locationPermissionJson())
238
+ return@runOnUiThread
239
+ }
240
+ AlertDialog.Builder(activity)
241
+ .setTitle(com.pushizo.sdk.R.string.hs_location_rationale_title)
242
+ .setMessage(rationale ?: activity.getString(com.pushizo.sdk.R.string.hs_location_rationale_message))
243
+ .setPositiveButton(com.pushizo.sdk.R.string.hs_location_rationale_continue) { _, _ -> requestSystem(permissions) }
244
+ .setNegativeButton(com.pushizo.sdk.R.string.hs_location_rationale_not_now) { _, _ -> reply.success(locationPermissionJson()) }
245
+ .setOnCancelListener { reply.success(locationPermissionJson()) }
246
+ .show()
247
+ }
248
+ }
249
+
250
+ /** Sistem izin sonucu: SDK bilgilendirilir (izin verildiyse ve paylaşım açıksa konum gönderilir), güncel izin döner. */
251
+ fun onLocationPermissionResult(): JSONObject {
252
+ Pushizo.Location.onPermissionResult()
253
+ return locationPermissionJson()
254
+ }
255
+
256
+ fun locationPermissionJson(): JSONObject = JSONObject().put("permission", Pushizo.Location.permissionGranted)
257
+
258
+ /**
259
+ * Arka plan konum izni akışı (bölge izleme, ADR-0065): Android SDK'nın `Location.requestBackgroundPermission` sonucu
260
+ * geri çağrıyla bildirilmediğinden köprü aynı adımları kendi izin mekanizmasıyla yürütür. İzin zaten varsa true.
261
+ * Android 10 öncesinde arka plan izni ayrı değildir: normal konum izinleri istenir. Android 10+ için uygulama
262
+ * manifest'inde `ACCESS_BACKGROUND_LOCATION` yoksa veya Activity yoksa false. Değilse açıklama diyaloğu gösterilir;
263
+ * "Şimdi değil"/iptal false döner, "Devam" ise [requestSystem] ile sistem izni istenir (Android 11+ Ayarlar ekranı
264
+ * açılır) — sonuç geldiğinde köprü [onBackgroundLocationPermissionResult] yanıtını döndürür.
265
+ */
266
+ fun requestBackgroundLocationPermission(activity: Activity?, args: JSONObject, reply: Reply, requestSystem: (Array<String>) -> Unit) {
267
+ if (!Pushizo.isInitialized) {
268
+ reply.error("NOT_READY", NOT_INITIALIZED)
269
+ return
270
+ }
271
+ if (Pushizo.Location.backgroundPermissionGranted) {
272
+ reply.success(onBackgroundLocationPermissionResult())
273
+ return
274
+ }
275
+ val legacy = Build.VERSION.SDK_INT < Build.VERSION_CODES.Q
276
+ val permissions = if (legacy) declaredLocationPermissions() else declaredPermissions(arrayOf(Manifest.permission.ACCESS_BACKGROUND_LOCATION))
277
+ if (permissions.isEmpty()) {
278
+ HsLog.w(
279
+ if (legacy) "konum izni istenemedi: uygulama manifest'inde ACCESS_COARSE_LOCATION/ACCESS_FINE_LOCATION yok"
280
+ else "arka plan konum izni istenemedi: uygulama manifest'inde ACCESS_BACKGROUND_LOCATION yok",
281
+ )
282
+ reply.success(backgroundLocationPermissionJson())
283
+ return
284
+ }
285
+ if (activity == null || activity.isFinishing || activity.isDestroyed) {
286
+ HsLog.w("arka plan konum izni istenemedi: etkin Activity yok")
287
+ reply.success(backgroundLocationPermissionJson())
288
+ return
289
+ }
290
+ val rationale = args.optStringOrNull("rationale")?.takeIf { it.isNotBlank() }
291
+ val title = if (legacy) com.pushizo.sdk.R.string.hs_location_rationale_title else com.pushizo.sdk.R.string.hs_geofence_rationale_title
292
+ val message = if (legacy) com.pushizo.sdk.R.string.hs_location_rationale_message else com.pushizo.sdk.R.string.hs_geofence_rationale_message
293
+ activity.runOnUiThread {
294
+ if (activity.isFinishing || activity.isDestroyed) {
295
+ reply.success(backgroundLocationPermissionJson())
296
+ return@runOnUiThread
297
+ }
298
+ AlertDialog.Builder(activity)
299
+ .setTitle(title)
300
+ .setMessage(rationale ?: activity.getString(message))
301
+ .setPositiveButton(com.pushizo.sdk.R.string.hs_location_rationale_continue) { _, _ -> requestSystem(permissions) }
302
+ .setNegativeButton(com.pushizo.sdk.R.string.hs_location_rationale_not_now) { _, _ -> reply.success(backgroundLocationPermissionJson()) }
303
+ .setOnCancelListener { reply.success(backgroundLocationPermissionJson()) }
304
+ .show()
305
+ }
306
+ }
307
+
308
+ /** Sistem izin sonucu: SDK bilgilendirilir (bölge izleme açıksa bölgeler yenilenir), güncel arka plan izni döner. */
309
+ fun onBackgroundLocationPermissionResult(): JSONObject {
310
+ Pushizo.Location.onPermissionResult()
311
+ return backgroundLocationPermissionJson()
312
+ }
313
+
314
+ fun backgroundLocationPermissionJson(): JSONObject = JSONObject().put("permission", Pushizo.Location.backgroundPermissionGranted)
315
+
316
+ /** Uygulama manifest'inde tanımlı konum izinleri (eklenti izinleri otomatik eklemez; README "Konum"). */
317
+ private fun declaredLocationPermissions(): Array<String> = declaredPermissions(LOCATION_PERMISSIONS)
318
+
319
+ /** [candidates] içinden uygulama manifest'inde tanımlı olanlar. */
320
+ private fun declaredPermissions(candidates: Array<String>): Array<String> {
321
+ val requested = try {
322
+ val pm = context.packageManager
323
+ val info = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
324
+ pm.getPackageInfo(context.packageName, PackageManager.PackageInfoFlags.of(PackageManager.GET_PERMISSIONS.toLong()))
325
+ } else {
326
+ @Suppress("DEPRECATION")
327
+ pm.getPackageInfo(context.packageName, PackageManager.GET_PERMISSIONS)
328
+ }
329
+ info.requestedPermissions?.toSet().orEmpty()
330
+ } catch (e: PackageManager.NameNotFoundException) {
331
+ emptySet()
332
+ }
333
+ return candidates.filter { it in requested }.toTypedArray()
334
+ }
335
+
336
+ /**
337
+ * Metodu çalıştırır. Bilinmeyen metotta false döner. `requestPermission`, `requestLocationPermission` ve
338
+ * `requestBackgroundLocationPermission` Activity gerektirdiğinden köprü sınıfında ele alınır.
339
+ */
340
+ fun handle(method: String, args: JSONObject, reply: Reply): Boolean {
341
+ try {
342
+ when (method) {
343
+ "initialize" -> {
344
+ val config = PushizoConfigStore.Config(
345
+ appId = args.requireString("appId"),
346
+ apiUrl = args.optStringOrNull("apiUrl") ?: Pushizo.Options().apiUrl,
347
+ requiresPrivacyConsent = args.optBoolean("requiresPrivacyConsent", false),
348
+ logLevel = args.optStringOrNull("logLevel") ?: "warn",
349
+ )
350
+ // Süreç yeniden başladığında (bildirim tıklaması, FCM servisi) SDK erkenden başlatılabilsin diye saklanır.
351
+ PushizoConfigStore.save(context, config)
352
+ Pushizo.initialize(context, config.appId, config.toOptions())
353
+ registerListeners()
354
+ reply.success(null)
355
+ }
356
+ "setConsentGiven" -> { Pushizo.setConsentGiven(args.optBoolean("given", false)); reply.success(null) }
357
+ "isInitialized" -> reply.success(JSONObject().put("initialized", Pushizo.isInitialized))
358
+ "login" -> {
359
+ // Profil (isteğe bağlı): geçersiz e-posta/telefon yerel SDK'da girişten önce reddedilir (INVALID_ARGUMENT).
360
+ val profile = args.optJSONObject("profile")
361
+ if (profile == null) {
362
+ Pushizo.login(args.requireString("externalId"), args.optStringOrNull("identityHash"), args.optStringOrNull("jwt"))
363
+ } else {
364
+ Pushizo.login(
365
+ args.requireString("externalId"),
366
+ HsUserProfile(
367
+ email = profile.optStringOrNull("email"),
368
+ sms = profile.optStringOrNull("sms"),
369
+ tags = profile.stringMap("tags"),
370
+ aliases = profile.stringMap("aliases"),
371
+ ),
372
+ args.optStringOrNull("identityHash"),
373
+ args.optStringOrNull("jwt"),
374
+ )
375
+ }
376
+ reply.success(null)
377
+ }
378
+ "updateUserJwt" -> { Pushizo.updateUserJwt(args.requireString("jwt")); reply.success(null) }
379
+ "logout" -> { Pushizo.logout(); reply.success(null) }
380
+
381
+ "addTags" -> { Pushizo.User.addTags(args.stringMap("tags")); reply.success(null) }
382
+ "removeTags" -> { Pushizo.User.removeTags(args.stringList("keys")); reply.success(null) }
383
+ "getTags" -> reply.success(JSONObject().put("tags", JSONObject(Pushizo.User.getTags())))
384
+ "addAliases" -> { Pushizo.User.addAliases(args.stringMap("aliases")); reply.success(null) }
385
+ "removeAlias" -> { Pushizo.User.removeAlias(args.requireString("label")); reply.success(null) }
386
+ "setLanguage" -> { Pushizo.User.setLanguage(args.requireString("code")); reply.success(null) }
387
+ // Kullanıcı özelliği: JSON null özelliği siler; nesne/dizi yerel SDK'da kuyruk JSON'una çevrilir. Boş anahtar → INVALID_ARGUMENT.
388
+ "setUserProperty" -> {
389
+ Pushizo.User.setProperty(args.requireString("key"), args.opt("value")?.takeUnless { it == JSONObject.NULL })
390
+ reply.success(null)
391
+ }
392
+ // Geçersiz adres → IllegalArgumentException → INVALID_ARGUMENT
393
+ "addEmail" -> { Pushizo.User.addEmail(args.requireString("email")); reply.success(null) }
394
+ "removeEmail" -> { Pushizo.User.removeEmail(args.requireString("email")); reply.success(null) }
395
+ "addSms" -> { Pushizo.User.addSms(args.requireString("phoneNumber")); reply.success(null) }
396
+ "removeSms" -> { Pushizo.User.removeSms(args.requireString("phoneNumber")); reply.success(null) }
397
+ "getUser" -> reply.success(JSONObject().put("id", Pushizo.User.id.orNull()).put("externalId", Pushizo.User.externalId.orNull()))
398
+ "getContacts" -> reply.success(
399
+ JSONObject().put("emails", JSONArray(Pushizo.User.emails)).put("smsNumbers", JSONArray(Pushizo.User.smsNumbers)),
400
+ )
401
+ // Tercihler (ADR-0019 §4): sahiplik kanıtı yerel SDK'da eklenir; doğrulama hatası INVALID_ARGUMENT, abonelik yoksa NOT_READY.
402
+ "getPreferences" -> Pushizo.User.getPreferences(callback(reply) { it.toJson() })
403
+ "setPreferences" -> Pushizo.User.setPreferences(args.preferenceInputs("preferences"), callback(reply) { it.toJson() })
404
+ // Reklam kişiselleştirme rızası (ADR-0037): tercih ucundaki ayrılmış `ads_personalization` anahtarı.
405
+ "setAdsPersonalizationConsent" -> Pushizo.User.setAdsPersonalizationConsent(args.optBoolean("granted", false), callback(reply) { it.toJson() })
406
+ "getConsents" -> Pushizo.User.getConsents(callback(reply) { list -> JSONObject().put("consents", JSONArray(list.map { it.toJson() })) })
407
+ // Fire OS ADM kayıt kimliği; geçersiz kimlik → IllegalArgumentException → INVALID_ARGUMENT.
408
+ "registerAdm" -> { Pushizo.User.registerAdm(args.requireString("token")); reply.success(null) }
409
+ // Reklam kimliği (GAID): null veya sıfır kimlik sunucudaki kaydı siler.
410
+ "setAdvertisingId" -> { Pushizo.Ads.setAdvertisingId(args.optStringOrNull("id")); reply.success(null) }
411
+
412
+ "getPushSubscription" -> reply.success(Pushizo.User.pushSubscription.state.toJson())
413
+ "optIn" -> { Pushizo.User.pushSubscription.optIn(); reply.success(null) }
414
+ "optOut" -> { Pushizo.User.pushSubscription.optOut(); reply.success(null) }
415
+
416
+ "getPermission" -> reply.success(permissionJson())
417
+ "clearAll" -> { Pushizo.Notifications.clearAll(); reply.success(null) }
418
+ "removeNotification" -> {
419
+ // Android tepsi kimliği tamsayıdır; metin kimlik (iOS biçimi) yalnızca sayıysa kabul edilir.
420
+ val id = when {
421
+ args.has("id") -> args.getInt("id")
422
+ else -> args.optStringOrNull("identifier")?.trim()?.toIntOrNull()
423
+ ?: throw IllegalArgumentException("id gerekli (Android bildirim kimliği tamsayıdır)")
424
+ }
425
+ Pushizo.Notifications.removeNotification(id)
426
+ reply.success(null)
427
+ }
428
+ "removeGroupedNotifications" -> { Pushizo.Notifications.removeGroupedNotifications(args.requireString("group")); reply.success(null) }
429
+ // Rozet: yerel SDK sayıyı saklar ve sonraki bildirimlere yazar; `success` rozetin bu cihazda gösterilebildiğini bildirir.
430
+ "setBadgeCount" -> reply.success(JSONObject().put("success", Pushizo.Notifications.setBadgeCount(args.optInt("count", 0))))
431
+ "getBadgeCount" -> reply.success(JSONObject().put("count", Pushizo.Notifications.badgeCount))
432
+ "setForegroundHandlerEnabled" -> { foregroundHandlerEnabled = args.optBoolean("enabled", false); reply.success(null) }
433
+ "displayNotification" -> {
434
+ val id = args.requireString("notificationId")
435
+ val event = synchronized(pendingForeground) { pendingForeground.remove(id) }
436
+ if (event == null) {
437
+ reply.error("NOT_FOUND", "Bildirim bulunamadı veya zaten gösterildi.")
438
+ } else {
439
+ event.display()
440
+ reply.success(null)
441
+ }
442
+ }
443
+
444
+ "sendEvent" -> {
445
+ val value = if (args.has("value") && !args.isNull("value")) args.getDouble("value") else null
446
+ val name = args.requireString("name")
447
+ val properties = args.optJSONObject("properties")?.toMap() ?: emptyMap()
448
+ // Tekilleştirme kimliği (isteğe bağlı): biçim geçersizse yerel SDK kendi kimliğini üretir.
449
+ val eventId = args.optStringOrNull("eventId")
450
+ if (eventId == null) Pushizo.Session.sendEvent(name, properties, value) else Pushizo.Session.sendEvent(name, properties, value, eventId)
451
+ reply.success(null)
452
+ }
453
+ "setLogLevel" -> { Pushizo.Debug.setLogLevel(logLevel(args.optStringOrNull("level"))); reply.success(null) }
454
+
455
+ "addTriggers" -> { Pushizo.InAppMessages.addTriggers(args.stringMap("triggers")); reply.success(null) }
456
+ "removeTriggers" -> { Pushizo.InAppMessages.removeTriggers(args.stringList("keys")); reply.success(null) }
457
+ "clearTriggers" -> { Pushizo.InAppMessages.clearTriggers(); reply.success(null) }
458
+ "getTriggers" -> reply.success(JSONObject().put("triggers", JSONObject(Pushizo.InAppMessages.getTriggers())))
459
+ "setScreen" -> { Pushizo.InAppMessages.setScreen(args.optStringOrNull("name")); reply.success(null) }
460
+ "setInAppPaused" -> { Pushizo.InAppMessages.paused = args.optBoolean("paused", false); reply.success(null) }
461
+ "getInAppPaused" -> reply.success(JSONObject().put("paused", Pushizo.InAppMessages.paused))
462
+
463
+ "inboxList" -> Pushizo.Inbox.list(args.optInt("limit", 50), args.optStringOrNull("cursor"), callback(reply) { it.toJson() })
464
+ "inboxMarkRead" -> Pushizo.Inbox.markRead(args.requireString("id"), callback(reply) { it.toJson() })
465
+ "inboxMarkAllRead" -> Pushizo.Inbox.markAllRead(callback(reply) { JSONObject().put("unreadCount", it) })
466
+ "inboxArchive" -> Pushizo.Inbox.archive(args.requireString("id"), callback(reply) { null })
467
+ "inboxUnreadCount" -> Pushizo.Inbox.unreadCount(callback(reply) { JSONObject().put("unreadCount", it) })
468
+ "contentCardsList" -> Pushizo.ContentCards.list(args.optInt("limit", 50), callback(reply) { it.toJson() })
469
+ "contentCardEvent" -> contentCardEvent(args.requireString("id"), args.optStringOrNull("event"), reply)
470
+
471
+ // Konum (v2 Faz 17b): izin isteği Activity gerektirdiğinden köprü sınıfında ele alınır.
472
+ "setLocationShared" -> {
473
+ check(Pushizo.isInitialized) { NOT_INITIALIZED }
474
+ Pushizo.Location.setShared(args.optBoolean("shared", false))
475
+ reply.success(null)
476
+ }
477
+ "isLocationShared" -> reply.success(JSONObject().put("shared", Pushizo.Location.isShared))
478
+ "getLocationPermission" -> reply.success(
479
+ JSONObject().put("permission", Pushizo.Location.permissionGranted).put("background", Pushizo.Location.backgroundPermissionGranted),
480
+ )
481
+ // Arka plan bölge izleme (ADR-0065): varsayılan kapalı; köprü izin istemez, manifest'e izin eklemez.
482
+ "setGeofencingEnabled" -> {
483
+ check(Pushizo.isInitialized) { NOT_INITIALIZED }
484
+ Pushizo.Location.setGeofencingEnabled(args.optBoolean("enabled", false))
485
+ reply.success(null)
486
+ }
487
+ "isGeofencingEnabled" -> reply.success(JSONObject().put("enabled", Pushizo.Location.isGeofencingEnabled))
488
+
489
+ // Android teslimat güçlendirme (ADR-0092): teşhis, ayar ekranı adayları ve diyalog yerel SDK'dadır; çağrılar istisna atmaz.
490
+ "deliveryStatus" -> reply.success(Pushizo.Delivery.status()?.toJson() ?: JSONObject().put("supported", false))
491
+ "deliveryShouldShowGuidance" -> reply.success(
492
+ JSONObject().put(
493
+ "show",
494
+ if (args.has("minIntervalDays")) Pushizo.Delivery.shouldShowGuidance(args.optInt("minIntervalDays", 14)) else Pushizo.Delivery.shouldShowGuidance(),
495
+ ),
496
+ )
497
+ "deliveryOpenSettings" -> reply.success(
498
+ JSONObject().put("opened", Pushizo.Delivery.openSettings(activityProvider?.invoke() ?: context, deliverySetting(args.optStringOrNull("setting")))),
499
+ )
500
+ "deliveryShowGuidance" -> {
501
+ // Diyalog etkin bir Activity ister; yoksa hiçbir şey gösterilmez ve false döner.
502
+ val activity = activityProvider?.invoke()
503
+ if (activity == null) reply.success(JSONObject().put("opened", false))
504
+ else Pushizo.Delivery.showGuidance(activity, deliverySetting(args.optStringOrNull("setting")), args.optStringOrNull("message")) { opened ->
505
+ reply.success(JSONObject().put("opened", opened))
506
+ }
507
+ }
508
+
509
+ // Özellik bayrakları (ADR-0066): değerler yerel SDK önbelleğinden okunur; `refresh` geri çağrısı arka plan iş parçacığındadır.
510
+ "featureFlagsRefresh" -> Pushizo.FeatureFlags.refresh { ok -> reply.success(JSONObject().put("success", ok)) }
511
+ "featureFlagsIsEnabled" -> reply.success(
512
+ JSONObject().put("enabled", Pushizo.FeatureFlags.isEnabled(args.requireString("key"), args.optBoolean("defaultValue", false))),
513
+ )
514
+ "featureFlagsGetValue" -> reply.success(JSONObject().put("value", Pushizo.FeatureFlags.getValue(args.requireString("key")).orNull()))
515
+
516
+ // Gömülü yerleşimler (ADR-0068): anahtar ve limit denetimi yerel SDK'dadır (IllegalArgumentException → INVALID_ARGUMENT).
517
+ "placementsList" -> Pushizo.Placements.list(args.requireString("key"), args.optInt("limit", 1)) { messages ->
518
+ synchronized(placementMessages) {
519
+ messages.forEach { placementMessages.remove(it.id); placementMessages[it.id] = it }
520
+ }
521
+ reply.success(JSONObject().put("messages", JSONArray(messages.map { it.toBridgeJson() })))
522
+ }
523
+ "placementsReportImpression" -> { placementMessage(args)?.let { Pushizo.Placements.reportImpression(it) }; reply.success(null) }
524
+ "placementsReportClick" -> {
525
+ val buttonId = args.requireString("buttonId")
526
+ placementMessage(args)?.let { Pushizo.Placements.reportClick(it, buttonId) }
527
+ reply.success(null)
528
+ }
529
+ "placementsReportDismiss" -> { placementMessage(args)?.let { Pushizo.Placements.reportDismiss(it) }; reply.success(null) }
530
+
531
+ // Live Activities yalnızca iOS'ta vardır (ADR-0024); Android'de sessizce başarılı dönülmez.
532
+ "setupDefaultLiveActivity" -> reply.error(LIVE_ACTIVITY_UNSUPPORTED_CODE, LIVE_ACTIVITY_UNSUPPORTED_MESSAGE)
533
+ "startDefaultLiveActivity" -> reply.error(LIVE_ACTIVITY_UNSUPPORTED_CODE, LIVE_ACTIVITY_UNSUPPORTED_MESSAGE)
534
+ // Canlı sohbet (ADR-0040): kimlik, kuyruk, akış ve push native SDK'dadır.
535
+ "chatStart" -> Pushizo.Chat.start(args.optStringOrNull("name"), args.optStringOrNull("email"), args.optStringOrNull("language"), callback(reply) { JSONObject(it.toMap()) })
536
+ "chatGetConfig" -> Pushizo.Chat.getConfig(args.optStringOrNull("language"), callback(reply) { JSONObject(it.toMap()) })
537
+ "chatGetConversation" -> Pushizo.Chat.getConversation(callback(reply) { JSONObject(it.toMap()) })
538
+ "chatGetMessages" -> Pushizo.Chat.getMessages(
539
+ args.optLongOrNull("afterSeq"), args.optLongOrNull("beforeSeq"), args.optInt("limit", 50), callback(reply) { JSONObject(it.toMap()) },
540
+ )
541
+ "chatSendMessage" -> Pushizo.Chat.sendMessage(args.requireString("text"), args.optStringOrNull("optionId"), callback(reply) { it.toJson() })
542
+ "chatSendAttachment" -> {
543
+ val fileName = args.requireString("fileName")
544
+ val mimeType = args.requireString("mimeType")
545
+ val text = args.optStringOrNull("text")
546
+ val base64 = args.optStringOrNull("base64")
547
+ if (base64 != null) {
548
+ val bytes = android.util.Base64.decode(base64, android.util.Base64.DEFAULT)
549
+ Pushizo.Chat.sendAttachment(bytes, fileName, mimeType, text, callback(reply) { it.toJson() })
550
+ } else {
551
+ Pushizo.Chat.sendAttachment(android.net.Uri.parse(args.requireString("uri")), fileName, mimeType, text, callback(reply) { it.toJson() })
552
+ }
553
+ }
554
+ "chatMarkRead" -> Pushizo.Chat.markRead(args.optLong("seq", 0L), callback(reply) { JSONObject().put("unreadCount", it) })
555
+ "chatRefreshUnreadCount" -> Pushizo.Chat.refreshUnreadCount(callback(reply) { JSONObject().put("unreadCount", it) })
556
+ "chatGetUnreadCount" -> reply.success(JSONObject().put("unreadCount", Pushizo.Chat.unreadCount))
557
+ "chatLeaveOfflineMessage" -> Pushizo.Chat.leaveOfflineMessage(
558
+ args.requireString("email"), args.requireString("text"), args.optStringOrNull("name"), callback(reply) { it.toJson() },
559
+ )
560
+ "chatSetTyping" -> { Pushizo.Chat.setTyping(args.optBoolean("typing", false)); reply.success(null) }
561
+ "chatStartListening" -> { Pushizo.Chat.startListening(); reply.success(null) }
562
+ "chatStopListening" -> { Pushizo.Chat.stopListening(); reply.success(null) }
563
+ "chatAttachmentUrl" -> reply.success(
564
+ JSONObject().put("url", Pushizo.Chat.attachmentUrl(args.requireString("attachmentId"), args.optBoolean("download", false))),
565
+ )
566
+ "chatGetVisitorId" -> reply.success(JSONObject().put("visitorId", Pushizo.Chat.visitorId.orNull()))
567
+ "chatIsListening" -> reply.success(JSONObject().put("listening", Pushizo.Chat.isListening))
568
+ // Hazır sohbet ekranı (`HsChatActivity`): etkin Activity varsa onun üzerinden, yoksa uygulama bağlamıyla açılır.
569
+ "chatShow" -> {
570
+ check(Pushizo.isInitialized) { NOT_INITIALIZED }
571
+ Pushizo.Chat.show(activityProvider?.invoke() ?: context)
572
+ reply.success(null)
573
+ }
574
+ "chatHide" -> { Pushizo.Chat.hide(); reply.success(null) }
575
+ "chatIsPresented" -> reply.success(JSONObject().put("presented", isChatPresented()))
576
+ else -> return false
577
+ }
578
+ } catch (e: IllegalArgumentException) {
579
+ reply.error("INVALID_ARGUMENT", e.message)
580
+ } catch (e: IllegalStateException) {
581
+ reply.error("NOT_READY", e.message)
582
+ } catch (e: Exception) {
583
+ reply.error("HS_ERROR", e.message)
584
+ }
585
+ return true
586
+ }
587
+
588
+ /** Rapor için mesajı son `placementsList` yanıtlarından bulur; bulunamazsa yok sayılır (yalnızca debug log). */
589
+ private fun placementMessage(args: JSONObject): HsInAppMessage? {
590
+ val id = args.requireString("id")
591
+ return synchronized(placementMessages) { placementMessages[id] } ?: run {
592
+ HsLog.d("yerleşim mesajı bulunamadı: $id")
593
+ null
594
+ }
595
+ }
596
+
597
+ /** SDK geri çağrısını köprü yanıtına çevirir; API hatasında sunucu kodu korunur. */
598
+ // Kart olayı (ADR-0082): olay adı yerel SDK çağrısına eşlenir; bilinmeyen olay INVALID_ARGUMENT.
599
+ private fun contentCardEvent(id: String, event: String?, reply: Reply) {
600
+ val cb = callback<HsContentCard>(reply) { it.toJson() }
601
+ if (event == "impression") Pushizo.ContentCards.logImpression(id, cb)
602
+ else if (event == "click") Pushizo.ContentCards.logClick(id, cb)
603
+ else if (event == "dismiss") Pushizo.ContentCards.dismiss(id, cb)
604
+ else reply.error("INVALID_ARGUMENT", "Kart olayı impression, click veya dismiss olmalı.")
605
+ }
606
+
607
+ private fun <T> callback(reply: Reply, map: (T) -> JSONObject?) = HsCallback<T> { result ->
608
+ result.fold(
609
+ onSuccess = { reply.success(map(it)) },
610
+ onFailure = { e ->
611
+ val code = when (e) {
612
+ is HsApiException -> e.code
613
+ is IllegalStateException -> "NOT_READY"
614
+ is IllegalArgumentException -> "INVALID_ARGUMENT"
615
+ else -> "HS_ERROR"
616
+ }
617
+ reply.error(code, e.message)
618
+ },
619
+ )
620
+ }
621
+
622
+ companion object {
623
+ private const val MAX_PENDING_FOREGROUND = 32
624
+ private const val MAX_PLACEMENT_CACHE = 50
625
+ private const val NOT_INITIALIZED = "Önce Pushizo.initialize çağrılmalı"
626
+ private val LOCATION_PERMISSIONS = arrayOf(Manifest.permission.ACCESS_COARSE_LOCATION, Manifest.permission.ACCESS_FINE_LOCATION)
627
+ private const val LIVE_ACTIVITY_UNSUPPORTED_CODE = "PLATFORM_NOT_SUPPORTED"
628
+ private const val LIVE_ACTIVITY_UNSUPPORTED_MESSAGE = "Live Activities yalnızca iOS'ta desteklenir"
629
+
630
+ fun logLevel(name: String?): HsLog.Level = when (name) {
631
+ "none" -> HsLog.Level.NONE
632
+ "error" -> HsLog.Level.ERROR
633
+ "info" -> HsLog.Level.INFO
634
+ "debug" -> HsLog.Level.DEBUG
635
+ else -> HsLog.Level.WARN
636
+ }
637
+
638
+ /** JS değeri (`auto`, `notifications`, `auto_start`, `battery_optimization`, `app_details`); tanınmayan değer `AUTO`. */
639
+ fun deliverySetting(wire: String?): HsDeliverySetting =
640
+ HsDeliverySetting.values().firstOrNull { it.name.equals(wire, ignoreCase = true) } ?: HsDeliverySetting.AUTO
641
+
642
+ /** Teslim durumu (ADR-0092); enum değerleri küçük harfle (`risk`: none/elevated/high, ayarlar: `auto_start` …). */
643
+ fun HsDeliveryStatus.toJson(): JSONObject = JSONObject()
644
+ .put("supported", true)
645
+ .put("manufacturer", manufacturer)
646
+ .put("brand", brand)
647
+ .put("vendor", vendor.id)
648
+ .put("aggressiveVendor", vendor.aggressive)
649
+ .put("rom", rom)
650
+ .put("romVersion", romVersion.orNull())
651
+ .put("notificationsEnabled", notificationsEnabled)
652
+ .put("channelBlocked", channelBlocked)
653
+ .put("batteryOptimizationExempt", batteryOptimizationExempt)
654
+ .put("backgroundRestricted", backgroundRestricted)
655
+ .put("standbyBucket", standbyBucket?.id.orNull())
656
+ .put("powerSaveMode", powerSaveMode)
657
+ .put("dataSaverEnabled", dataSaverEnabled)
658
+ .put("restricted", restricted)
659
+ .put("risk", risk.name.lowercase())
660
+ .put("recommendedSettings", JSONArray(recommendedSettings.map { it.name.lowercase() }))
661
+
662
+ fun HsNotification.toJson(): JSONObject = JSONObject()
663
+ .put("title", title.orNull())
664
+ .put("body", body.orNull())
665
+ .put("url", url.orNull())
666
+ .put("imageUrl", imageUrl.orNull())
667
+ .put("deliveryId", deliveryId.orNull())
668
+ .put("messageId", messageId.orNull())
669
+ .put("data", JSONObject(data))
670
+ .put("androidNotificationId", androidNotificationId)
671
+
672
+ fun HsPushSubscriptionState.toJson(): JSONObject = JSONObject()
673
+ .put("id", id.orNull())
674
+ .put("token", token.orNull())
675
+ .put("optedIn", optedIn)
676
+ .put("permission", permission)
677
+
678
+ fun HsInboxItem.toJson(): JSONObject = JSONObject()
679
+ .put("id", id)
680
+ .put("messageId", messageId.orNull())
681
+ .put("title", title.orNull())
682
+ .put("body", body.orNull())
683
+ .put("url", url.orNull())
684
+ .put("imageUrl", imageUrl.orNull())
685
+ .put("data", JSONObject(data))
686
+ .put("read", read)
687
+ .put("readAt", readAt.orNull())
688
+ .put("archivedAt", archivedAt.orNull())
689
+ .put("expiresAt", expiresAt.orNull())
690
+ .put("createdAt", createdAt.orNull())
691
+
692
+ fun HsContentCard.toJson(): JSONObject = JSONObject()
693
+ .put("id", id)
694
+ .put("messageId", messageId.orNull())
695
+ .put("type", type.wire)
696
+ .put("title", title.orNull())
697
+ .put("body", body.orNull())
698
+ .put("url", url.orNull())
699
+ .put("imageUrl", imageUrl.orNull())
700
+ .put("buttonText", buttonText.orNull())
701
+ .put("data", JSONObject(data))
702
+ .put("pinned", pinned)
703
+ .put("priority", priority)
704
+ .put("viewed", viewed)
705
+ .put("clicked", clicked)
706
+ .put("expiresAt", expiresAt.orNull())
707
+ .put("createdAt", createdAt.orNull())
708
+
709
+ fun HsContentCardFeed.toJson(): JSONObject = JSONObject()
710
+ .put("cards", JSONArray(cards.map { it.toJson() }))
711
+ .put("unviewedCount", unviewedCount)
712
+
713
+ fun HsInboxPage.toJson(): JSONObject = JSONObject()
714
+ .put("items", JSONArray(items.map { it.toJson() }))
715
+ .put("unreadCount", unreadCount)
716
+ .put("nextCursor", nextCursor.orNull())
717
+ .put("hasMore", hasMore)
718
+
719
+ fun HsPreference.toJson(): JSONObject = JSONObject()
720
+ .put("category", category)
721
+ .put("channel", channel.orNull())
722
+ .put("optedIn", optedIn)
723
+ .put("explicit", explicit)
724
+ .put("source", source.orNull())
725
+ .put("updatedAt", updatedAt.orNull())
726
+
727
+ fun HsMessageCategory.toJson(): JSONObject = JSONObject()
728
+ .put("key", key)
729
+ .put("name", JSONObject(name))
730
+ .put("description", JSONObject(description))
731
+ .put("channels", channels?.let { JSONArray(it) }.orNull())
732
+ .put("defaultOptedIn", defaultOptedIn)
733
+
734
+ /** Rıza kaydı (ADR-0037); `updatedAt` epoch milisaniye. */
735
+ fun HsConsent.toJson(): JSONObject = JSONObject()
736
+ .put("purpose", purpose)
737
+ .put("granted", granted)
738
+ .put("source", source.orNull())
739
+ .put("updatedAt", updatedAt.orNull())
740
+
741
+ fun HsPreferencesResult.toJson(): JSONObject = JSONObject()
742
+ .put("preferences", JSONArray(preferences.map { it.toJson() }))
743
+ .put("categories", JSONArray(categories.map { it.toJson() }))
744
+
745
+ // In-app mesaj modeli → JS `InAppMessage` (alanlar yerel modelle aynı; zamanlar epoch milisaniye).
746
+ fun HsInAppMessage.toBridgeJson(): JSONObject = JSONObject()
747
+ .put("id", id)
748
+ .put("priority", priority)
749
+ .put("triggers", JSONArray(triggers.map { it.toJson() }))
750
+ .put("triggerGroups", JSONArray(triggerGroups.map { group -> JSONArray(group.map { it.toJson() }) }))
751
+ .put("variantId", variantId.orNull())
752
+ .put("display", display.toJson())
753
+ .put("remainingImpressions", remainingImpressions)
754
+ .put("minIntervalSeconds", minIntervalSeconds)
755
+ .put("stopAfterInteraction", stopAfterInteraction)
756
+ .put("lastImpressionAt", lastImpressionAt.orNull())
757
+ .put("endAt", endAt.orNull())
758
+ .put("language", language.orNull())
759
+
760
+ fun HsInAppDisplay.toJson(): JSONObject = JSONObject()
761
+ .put("layout", layout.wire)
762
+ .put("backgroundColor", backgroundColor.orNull())
763
+ .put("textColor", textColor.orNull())
764
+ .put("dismissible", dismissible)
765
+ .put("autoDismissSeconds", autoDismissSeconds.orNull())
766
+ .put("contentType", contentType.wire)
767
+ .put("blocks", JSONArray(blocks.map { it.toJson() }))
768
+ .put("html", html.orNull())
769
+ .put("htmlHeight", htmlHeight.orNull())
770
+
771
+ fun HsInAppTrigger.toJson(): JSONObject = when (this) {
772
+ HsInAppTrigger.SessionStart -> JSONObject().put("kind", "session_start")
773
+ is HsInAppTrigger.Event -> JSONObject().put("kind", "event").put("name", name)
774
+ is HsInAppTrigger.Screen -> JSONObject().put("kind", "screen").put("name", name)
775
+ is HsInAppTrigger.Condition -> JSONObject().put("kind", "trigger").put("key", key).put("op", op).put("value", value.orNull())
776
+ is HsInAppTrigger.SessionDuration -> JSONObject().put("kind", "session_duration").put("seconds", seconds)
777
+ is HsInAppTrigger.Unsupported -> JSONObject().put("kind", "unsupported").put("name", kind)
778
+ }
779
+
780
+ fun HsInAppAction.toJson(): JSONObject = when (this) {
781
+ HsInAppAction.Dismiss -> JSONObject().put("type", "dismiss")
782
+ is HsInAppAction.Url -> JSONObject().put("type", "url").put("url", url)
783
+ is HsInAppAction.Deeplink -> JSONObject().put("type", "deeplink").put("url", url)
784
+ is HsInAppAction.Tags -> JSONObject().put("type", "tags").put("tags", JSONObject(tags))
785
+ HsInAppAction.PushPrompt -> JSONObject().put("type", "push_prompt")
786
+ is HsInAppAction.Outcome -> JSONObject().put("type", "outcome").put("name", name).put("value", value.orNull())
787
+ }
788
+
789
+ fun HsInAppBlock.Button.toJson(): JSONObject = JSONObject()
790
+ .put("id", id)
791
+ .put("text", text)
792
+ .put("action", action.toJson())
793
+ .put("backgroundColor", backgroundColor.orNull())
794
+ .put("textColor", textColor.orNull())
795
+
796
+ fun HsInAppCarouselCard.toJson(): JSONObject = JSONObject()
797
+ .put("id", id)
798
+ .put("title", title)
799
+ .put("body", body.orNull())
800
+ .put("imageUrl", imageUrl.orNull())
801
+ .put("imageAlt", imageAlt.orNull())
802
+ .put("button", button?.toJson().orNull())
803
+
804
+ fun HsInAppBlock.toJson(): JSONObject = when (this) {
805
+ is HsInAppBlock.Image -> JSONObject().put("type", "image").put("url", url).put("alt", alt.orNull())
806
+ is HsInAppBlock.Title -> JSONObject().put("type", "title").put("text", text)
807
+ is HsInAppBlock.Body -> JSONObject().put("type", "body").put("text", text)
808
+ is HsInAppBlock.Button -> toJson().put("type", "button")
809
+ is HsInAppBlock.Carousel -> JSONObject().put("type", "carousel").put("id", id).put("cards", JSONArray(cards.map { it.toJson() }))
810
+ }
811
+
812
+ /** JS `{ category, channel, optedIn }[]` → SDK girdisi; kural denetimi (1-100, kanal) SDK'dadır. */
813
+ fun JSONObject.preferenceInputs(key: String): List<HsPreferenceInput> {
814
+ val arr = optJSONArray(key) ?: throw IllegalArgumentException("$key gerekli")
815
+ return (0 until arr.length()).map { i ->
816
+ val item = arr.optJSONObject(i) ?: throw IllegalArgumentException("$key[$i] nesne olmalı")
817
+ HsPreferenceInput(item.requireString("category"), item.optStringOrNull("channel"), item.optBoolean("optedIn", false))
818
+ }
819
+ }
820
+
821
+ private fun Any?.orNull(): Any = this ?: JSONObject.NULL
822
+
823
+ fun JSONObject.optStringOrNull(key: String): String? = if (has(key) && !isNull(key)) optString(key) else null
824
+
825
+ fun JSONObject.optLongOrNull(key: String): Long? = if (has(key) && !isNull(key)) optLong(key) else null
826
+
827
+ fun JSONObject.requireString(key: String): String =
828
+ optStringOrNull(key)?.takeIf { it.isNotBlank() } ?: throw IllegalArgumentException("$key gerekli")
829
+
830
+ fun JSONObject.stringMap(key: String): Map<String, String> {
831
+ val obj = optJSONObject(key) ?: return emptyMap()
832
+ val out = LinkedHashMap<String, String>()
833
+ obj.keys().forEach { k -> if (!obj.isNull(k)) out[k] = obj.get(k).toString() }
834
+ return out
835
+ }
836
+
837
+ fun JSONObject.stringList(key: String): List<String> {
838
+ val arr = optJSONArray(key) ?: return emptyList()
839
+ return (0 until arr.length()).mapNotNull { i -> if (arr.isNull(i)) null else arr.get(i).toString() }
840
+ }
841
+
842
+ /** JSON nesnesini SDK'nın beklediği Map/List yapısına çevirir (iç içe değerler korunur). */
843
+ fun JSONObject.toMap(): Map<String, Any?> {
844
+ val out = LinkedHashMap<String, Any?>()
845
+ keys().forEach { k -> out[k] = unwrap(get(k)) }
846
+ return out
847
+ }
848
+
849
+ private fun unwrap(value: Any?): Any? = when (value) {
850
+ JSONObject.NULL, null -> null
851
+ is JSONObject -> value.toMap()
852
+ is JSONArray -> (0 until value.length()).map { unwrap(value.get(it)) }
853
+ else -> value
854
+ }
855
+ }
856
+ }