cordova-plugin-pushizo 0.1.0 → 0.2.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,610 @@
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.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.HsInAppAction
17
+ import com.pushizo.sdk.HsInAppBlock
18
+ import com.pushizo.sdk.HsInAppCarouselCard
19
+ import com.pushizo.sdk.HsInAppClickEvent
20
+ import com.pushizo.sdk.HsInAppDisplay
21
+ import com.pushizo.sdk.HsInAppLifecycleEvent
22
+ import com.pushizo.sdk.HsInAppLifecycleListener
23
+ import com.pushizo.sdk.HsInAppMessage
24
+ import com.pushizo.sdk.HsInAppTrigger
25
+ import com.pushizo.sdk.HsInboxItem
26
+ import com.pushizo.sdk.HsInboxPage
27
+ import com.pushizo.sdk.HsLog
28
+ import com.pushizo.sdk.HsMessageCategory
29
+ import com.pushizo.sdk.HsNotification
30
+ import com.pushizo.sdk.HsPreference
31
+ import com.pushizo.sdk.HsPreferenceInput
32
+ import com.pushizo.sdk.HsPreferencesResult
33
+ import com.pushizo.sdk.HsPushSubscriptionState
34
+ import org.json.JSONArray
35
+ import org.json.JSONObject
36
+ import java.util.concurrent.atomic.AtomicBoolean
37
+ import java.util.concurrent.atomic.AtomicLong
38
+
39
+ /**
40
+ * Köprüden bağımsız Android çekirdeği: JS metot adlarını Pushizo Android SDK çağrılarına çevirir,
41
+ * SDK olaylarını `emit(tür, veri)` ile köprüye iletir. Cordova eklentisi bu sınıfı sarar.
42
+ */
43
+ internal class PushizoBridgeCore(
44
+ private val context: Context,
45
+ private val emit: (type: String, payload: JSONObject) -> Unit,
46
+ ) {
47
+ /** Metot sonucu; `success(null)` boş yanıt demektir. */
48
+ interface Reply {
49
+ fun success(data: JSONObject?)
50
+ fun error(code: String, message: String?)
51
+ }
52
+
53
+ /** JS tarafında ön plan dinleyicisi varsa gösterim JS kararına bırakılır. */
54
+ @Volatile var foregroundHandlerEnabled = false
55
+
56
+ private val listenersRegistered = AtomicBoolean(false)
57
+ private val foregroundSeq = AtomicLong(0)
58
+
59
+ /** Karar bekleyen ön plan bildirimleri; en eski kayıtlar düşürülür (sınırlı bellek). */
60
+ private val pendingForeground = object : LinkedHashMap<String, HsForegroundEvent>() {
61
+ override fun removeEldestEntry(eldest: MutableMap.MutableEntry<String, HsForegroundEvent>?): Boolean = size > MAX_PENDING_FOREGROUND
62
+ }
63
+
64
+ /** Son `placementsList` yanıtlarındaki mesajlar (kimliğe göre); raporlar bu nesnelerle yapılır, en eski kayıtlar düşürülür. */
65
+ private val placementMessages = object : LinkedHashMap<String, HsInAppMessage>() {
66
+ override fun removeEldestEntry(eldest: MutableMap.MutableEntry<String, HsInAppMessage>?): Boolean = size > MAX_PLACEMENT_CACHE
67
+ }
68
+
69
+ private val clickListener: (HsClickEvent) -> Unit = { e ->
70
+ emit("click", JSONObject().put("notification", e.notification.toJson()).put("result", JSONObject().put("actionId", e.actionId.orNull()).put("url", e.url.orNull())))
71
+ }
72
+
73
+ private val foregroundListener: (HsForegroundEvent) -> Unit = { e ->
74
+ val id = "fg-${foregroundSeq.incrementAndGet()}"
75
+ val pending = foregroundHandlerEnabled
76
+ if (pending) {
77
+ // Yerel gösterim ertelenir; JS `display()` çağırırsa veya hiçbir dinleyici engellemezse gösterilir.
78
+ e.preventDefault()
79
+ synchronized(pendingForeground) { pendingForeground[id] = e }
80
+ }
81
+ emit("foregroundWillDisplay", JSONObject().put("notificationId", id).put("pending", pending).put("notification", e.notification.toJson()))
82
+ }
83
+
84
+ private val subscriptionObserver: (HsPushSubscriptionState) -> Unit = { s -> emit("pushSubscriptionChange", s.toJson()) }
85
+
86
+ /**
87
+ * Yerel SDK izin gözlemcisi: izin isteği sonucu ve uygulama ön plana döndüğünde (izin sistem ayarlarından
88
+ * değişmiş olabilir) etkin izin değiştiyse çağrılır.
89
+ */
90
+ private val permissionObserver: (Boolean) -> Unit = { granted -> emit("permissionChange", JSONObject().put("permission", granted)) }
91
+
92
+ private val inAppClickListener: (HsInAppClickEvent) -> Unit = { e ->
93
+ emit("inAppClick", JSONObject().put("message", JSONObject().put("id", e.messageId)).put("result", JSONObject().put("actionId", e.actionId).put("url", e.url.orNull())))
94
+ }
95
+
96
+ /** Canlı sohbet olayları → JS `chatEvent` (`{ type: message|typing|read|unread|conversation|connection|error, ... }`). */
97
+ private val chatListener = HsChatEventAdapter { type, payload -> emit("chatEvent", JSONObject(payload).put("type", type)) }
98
+
99
+ /** Sohbet bildirimine tıklama → JS `chatOpen` (cephe dinleyici yoksa bekletir). */
100
+ private val chatOpenListener = HsChatOpenListener { info -> emit("chatOpen", JSONObject(info.toMap())) }
101
+
102
+ private val inAppLifecycleListener = object : HsInAppLifecycleListener {
103
+ private fun send(event: String, e: HsInAppLifecycleEvent) =
104
+ emit("inAppLifecycle", JSONObject().put("event", event).put("message", JSONObject().put("id", e.message.id)))
105
+ override fun onWillDisplay(event: HsInAppLifecycleEvent) = send("willDisplay", event)
106
+ override fun onDidDisplay(event: HsInAppLifecycleEvent) = send("didDisplay", event)
107
+ override fun onWillDismiss(event: HsInAppLifecycleEvent) = send("willDismiss", event)
108
+ override fun onDidDismiss(event: HsInAppLifecycleEvent) = send("didDismiss", event)
109
+ }
110
+
111
+ /** SDK zaten başlatıldıysa (kayıtlı ayarlarla süreç başında) dinleyicileri bağlar. */
112
+ fun attachIfInitialized() {
113
+ if (Pushizo.isInitialized) registerListeners()
114
+ }
115
+
116
+ /** SDK dinleyicileri bir kez eklenir; soğuk başlatma tıklaması ilk tıklama dinleyicisine teslim edilir. */
117
+ private fun registerListeners() {
118
+ if (!listenersRegistered.compareAndSet(false, true)) return
119
+ Pushizo.Notifications.addClickListener(clickListener)
120
+ Pushizo.Notifications.addForegroundLifecycleListener(foregroundListener)
121
+ Pushizo.User.pushSubscription.addObserver(subscriptionObserver)
122
+ Pushizo.Notifications.addPermissionObserver(permissionObserver)
123
+ Pushizo.InAppMessages.addClickListener(inAppClickListener)
124
+ Pushizo.InAppMessages.addLifecycleListener(inAppLifecycleListener)
125
+ Pushizo.Chat.addListener(chatListener)
126
+ Pushizo.Chat.addOpenListener(chatOpenListener)
127
+ }
128
+
129
+ fun detach() {
130
+ if (!listenersRegistered.compareAndSet(true, false)) return
131
+ Pushizo.Notifications.removeClickListener(clickListener)
132
+ Pushizo.Notifications.removeForegroundLifecycleListener(foregroundListener)
133
+ Pushizo.User.pushSubscription.removeObserver(subscriptionObserver)
134
+ Pushizo.Notifications.removePermissionObserver(permissionObserver)
135
+ Pushizo.InAppMessages.removeClickListener(inAppClickListener)
136
+ Pushizo.InAppMessages.removeLifecycleListener(inAppLifecycleListener)
137
+ Pushizo.Chat.removeListener(chatListener)
138
+ Pushizo.Chat.removeOpenListener(chatOpenListener)
139
+ // Bekleyen ön plan bildirimleri kaybolmasın diye gösterilir.
140
+ val pending = synchronized(pendingForeground) { pendingForeground.values.toList().also { pendingForeground.clear() } }
141
+ pending.forEach { it.display() }
142
+ }
143
+
144
+ /** İzin isteği sonuçlandı: SDK aboneliği günceller; izin değiştiyse yerel izin gözlemcisi olayı gönderir. */
145
+ fun onPermissionResult() {
146
+ Pushizo.Notifications.onPermissionResult()
147
+ }
148
+
149
+ fun permissionJson(): JSONObject = JSONObject().put("permission", Pushizo.Notifications.permission)
150
+
151
+ // --- Konum izni (v2 Faz 17b) ---
152
+
153
+ /**
154
+ * Konum izni akışı: Android SDK'nın `Location.requestPermission` sonucu geri çağrıyla bildirilmediğinden köprü aynı
155
+ * adımları kendi izin mekanizmasıyla yürütür. İzin zaten varsa true; uygulama manifest'inde konum izni yoksa veya
156
+ * Activity yoksa false. Değilse açıklama diyaloğu gösterilir (başlık/düğmeler SDK string kaynakları, mesaj
157
+ * `rationale` ya da SDK varsayılanı); "Şimdi değil"/iptal false döner, "Devam" ise [requestSystem] ile köprünün izin
158
+ * API'si üzerinden sistem izni istenir — sonuç geldiğinde köprü [onLocationPermissionResult] yanıtını döndürür.
159
+ */
160
+ fun requestLocationPermission(activity: Activity?, args: JSONObject, reply: Reply, requestSystem: (Array<String>) -> Unit) {
161
+ if (!Pushizo.isInitialized) {
162
+ reply.error("NOT_READY", NOT_INITIALIZED)
163
+ return
164
+ }
165
+ if (Pushizo.Location.permissionGranted) {
166
+ reply.success(onLocationPermissionResult())
167
+ return
168
+ }
169
+ val permissions = declaredLocationPermissions()
170
+ if (permissions.isEmpty()) {
171
+ HsLog.w("konum izni istenemedi: uygulama manifest'inde ACCESS_COARSE_LOCATION/ACCESS_FINE_LOCATION yok")
172
+ reply.success(locationPermissionJson())
173
+ return
174
+ }
175
+ if (activity == null || activity.isFinishing || activity.isDestroyed) {
176
+ HsLog.w("konum izni istenemedi: etkin Activity yok")
177
+ reply.success(locationPermissionJson())
178
+ return
179
+ }
180
+ val rationale = args.optStringOrNull("rationale")?.takeIf { it.isNotBlank() }
181
+ activity.runOnUiThread {
182
+ if (activity.isFinishing || activity.isDestroyed) {
183
+ reply.success(locationPermissionJson())
184
+ return@runOnUiThread
185
+ }
186
+ AlertDialog.Builder(activity)
187
+ .setTitle(com.pushizo.sdk.R.string.hs_location_rationale_title)
188
+ .setMessage(rationale ?: activity.getString(com.pushizo.sdk.R.string.hs_location_rationale_message))
189
+ .setPositiveButton(com.pushizo.sdk.R.string.hs_location_rationale_continue) { _, _ -> requestSystem(permissions) }
190
+ .setNegativeButton(com.pushizo.sdk.R.string.hs_location_rationale_not_now) { _, _ -> reply.success(locationPermissionJson()) }
191
+ .setOnCancelListener { reply.success(locationPermissionJson()) }
192
+ .show()
193
+ }
194
+ }
195
+
196
+ /** Sistem izin sonucu: SDK bilgilendirilir (izin verildiyse ve paylaşım açıksa konum gönderilir), güncel izin döner. */
197
+ fun onLocationPermissionResult(): JSONObject {
198
+ Pushizo.Location.onPermissionResult()
199
+ return locationPermissionJson()
200
+ }
201
+
202
+ fun locationPermissionJson(): JSONObject = JSONObject().put("permission", Pushizo.Location.permissionGranted)
203
+
204
+ /** Uygulama manifest'inde tanımlı konum izinleri (eklenti izinleri otomatik eklemez; README "Konum"). */
205
+ private fun declaredLocationPermissions(): Array<String> {
206
+ val requested = try {
207
+ val pm = context.packageManager
208
+ val info = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
209
+ pm.getPackageInfo(context.packageName, PackageManager.PackageInfoFlags.of(PackageManager.GET_PERMISSIONS.toLong()))
210
+ } else {
211
+ @Suppress("DEPRECATION")
212
+ pm.getPackageInfo(context.packageName, PackageManager.GET_PERMISSIONS)
213
+ }
214
+ info.requestedPermissions?.toSet().orEmpty()
215
+ } catch (e: PackageManager.NameNotFoundException) {
216
+ emptySet()
217
+ }
218
+ return LOCATION_PERMISSIONS.filter { it in requested }.toTypedArray()
219
+ }
220
+
221
+ /**
222
+ * Metodu çalıştırır. Bilinmeyen metotta false döner. `requestPermission` ve `requestLocationPermission` Activity
223
+ * gerektirdiğinden köprü sınıfında ele alınır.
224
+ */
225
+ fun handle(method: String, args: JSONObject, reply: Reply): Boolean {
226
+ try {
227
+ when (method) {
228
+ "initialize" -> {
229
+ val config = PushizoConfigStore.Config(
230
+ appId = args.requireString("appId"),
231
+ apiUrl = args.optStringOrNull("apiUrl") ?: Pushizo.Options().apiUrl,
232
+ requiresPrivacyConsent = args.optBoolean("requiresPrivacyConsent", false),
233
+ logLevel = args.optStringOrNull("logLevel") ?: "warn",
234
+ )
235
+ // Süreç yeniden başladığında (bildirim tıklaması, FCM servisi) SDK erkenden başlatılabilsin diye saklanır.
236
+ PushizoConfigStore.save(context, config)
237
+ Pushizo.initialize(context, config.appId, config.toOptions())
238
+ registerListeners()
239
+ reply.success(null)
240
+ }
241
+ "setConsentGiven" -> { Pushizo.setConsentGiven(args.optBoolean("given", false)); reply.success(null) }
242
+ "login" -> {
243
+ Pushizo.login(args.requireString("externalId"), args.optStringOrNull("identityHash"), args.optStringOrNull("jwt"))
244
+ reply.success(null)
245
+ }
246
+ "updateUserJwt" -> { Pushizo.updateUserJwt(args.requireString("jwt")); reply.success(null) }
247
+ "logout" -> { Pushizo.logout(); reply.success(null) }
248
+
249
+ "addTags" -> { Pushizo.User.addTags(args.stringMap("tags")); reply.success(null) }
250
+ "removeTags" -> { Pushizo.User.removeTags(args.stringList("keys")); reply.success(null) }
251
+ "getTags" -> reply.success(JSONObject().put("tags", JSONObject(Pushizo.User.getTags())))
252
+ "addAliases" -> { Pushizo.User.addAliases(args.stringMap("aliases")); reply.success(null) }
253
+ "removeAlias" -> { Pushizo.User.removeAlias(args.requireString("label")); reply.success(null) }
254
+ "setLanguage" -> { Pushizo.User.setLanguage(args.requireString("code")); reply.success(null) }
255
+ // Geçersiz adres → IllegalArgumentException → INVALID_ARGUMENT
256
+ "addEmail" -> { Pushizo.User.addEmail(args.requireString("email")); reply.success(null) }
257
+ "removeEmail" -> { Pushizo.User.removeEmail(args.requireString("email")); reply.success(null) }
258
+ "addSms" -> { Pushizo.User.addSms(args.requireString("phoneNumber")); reply.success(null) }
259
+ "removeSms" -> { Pushizo.User.removeSms(args.requireString("phoneNumber")); reply.success(null) }
260
+ "getUser" -> reply.success(JSONObject().put("id", Pushizo.User.id.orNull()).put("externalId", Pushizo.User.externalId.orNull()))
261
+ "getContacts" -> reply.success(
262
+ JSONObject().put("emails", JSONArray(Pushizo.User.emails)).put("smsNumbers", JSONArray(Pushizo.User.smsNumbers)),
263
+ )
264
+ // Tercihler (ADR-0019 §4): sahiplik kanıtı yerel SDK'da eklenir; doğrulama hatası INVALID_ARGUMENT, abonelik yoksa NOT_READY.
265
+ "getPreferences" -> Pushizo.User.getPreferences(callback(reply) { it.toJson() })
266
+ "setPreferences" -> Pushizo.User.setPreferences(args.preferenceInputs("preferences"), callback(reply) { it.toJson() })
267
+
268
+ "getPushSubscription" -> reply.success(Pushizo.User.pushSubscription.state.toJson())
269
+ "optIn" -> { Pushizo.User.pushSubscription.optIn(); reply.success(null) }
270
+ "optOut" -> { Pushizo.User.pushSubscription.optOut(); reply.success(null) }
271
+
272
+ "getPermission" -> reply.success(permissionJson())
273
+ "clearAll" -> { Pushizo.Notifications.clearAll(); reply.success(null) }
274
+ "removeNotification" -> {
275
+ // Android tepsi kimliği tamsayıdır; metin kimlik (iOS biçimi) yalnızca sayıysa kabul edilir.
276
+ val id = when {
277
+ args.has("id") -> args.getInt("id")
278
+ else -> args.optStringOrNull("identifier")?.trim()?.toIntOrNull()
279
+ ?: throw IllegalArgumentException("id gerekli (Android bildirim kimliği tamsayıdır)")
280
+ }
281
+ Pushizo.Notifications.removeNotification(id)
282
+ reply.success(null)
283
+ }
284
+ "removeGroupedNotifications" -> { Pushizo.Notifications.removeGroupedNotifications(args.requireString("group")); reply.success(null) }
285
+ "setForegroundHandlerEnabled" -> { foregroundHandlerEnabled = args.optBoolean("enabled", false); reply.success(null) }
286
+ "displayNotification" -> {
287
+ val id = args.requireString("notificationId")
288
+ val event = synchronized(pendingForeground) { pendingForeground.remove(id) }
289
+ if (event == null) {
290
+ reply.error("NOT_FOUND", "Bildirim bulunamadı veya zaten gösterildi.")
291
+ } else {
292
+ event.display()
293
+ reply.success(null)
294
+ }
295
+ }
296
+
297
+ "sendEvent" -> {
298
+ val value = if (args.has("value") && !args.isNull("value")) args.getDouble("value") else null
299
+ Pushizo.Session.sendEvent(args.requireString("name"), args.optJSONObject("properties")?.toMap() ?: emptyMap(), value)
300
+ reply.success(null)
301
+ }
302
+ "setLogLevel" -> { Pushizo.Debug.setLogLevel(logLevel(args.optStringOrNull("level"))); reply.success(null) }
303
+
304
+ "addTriggers" -> { Pushizo.InAppMessages.addTriggers(args.stringMap("triggers")); reply.success(null) }
305
+ "removeTriggers" -> { Pushizo.InAppMessages.removeTriggers(args.stringList("keys")); reply.success(null) }
306
+ "clearTriggers" -> { Pushizo.InAppMessages.clearTriggers(); reply.success(null) }
307
+ "getTriggers" -> reply.success(JSONObject().put("triggers", JSONObject(Pushizo.InAppMessages.getTriggers())))
308
+ "setScreen" -> { Pushizo.InAppMessages.setScreen(args.optStringOrNull("name")); reply.success(null) }
309
+ "setInAppPaused" -> { Pushizo.InAppMessages.paused = args.optBoolean("paused", false); reply.success(null) }
310
+ "getInAppPaused" -> reply.success(JSONObject().put("paused", Pushizo.InAppMessages.paused))
311
+
312
+ "inboxList" -> Pushizo.Inbox.list(args.optInt("limit", 50), args.optStringOrNull("cursor"), callback(reply) { it.toJson() })
313
+ "inboxMarkRead" -> Pushizo.Inbox.markRead(args.requireString("id"), callback(reply) { it.toJson() })
314
+ "inboxMarkAllRead" -> Pushizo.Inbox.markAllRead(callback(reply) { JSONObject().put("unreadCount", it) })
315
+ "inboxArchive" -> Pushizo.Inbox.archive(args.requireString("id"), callback(reply) { null })
316
+ "inboxUnreadCount" -> Pushizo.Inbox.unreadCount(callback(reply) { JSONObject().put("unreadCount", it) })
317
+
318
+ // Konum (v2 Faz 17b): izin isteği Activity gerektirdiğinden köprü sınıfında ele alınır.
319
+ "setLocationShared" -> {
320
+ check(Pushizo.isInitialized) { NOT_INITIALIZED }
321
+ Pushizo.Location.setShared(args.optBoolean("shared", false))
322
+ reply.success(null)
323
+ }
324
+ "isLocationShared" -> reply.success(JSONObject().put("shared", Pushizo.Location.isShared))
325
+ // Arka plan bölge izleme (ADR-0065): varsayılan kapalı; köprü izin istemez, manifest'e izin eklemez.
326
+ "setGeofencingEnabled" -> {
327
+ check(Pushizo.isInitialized) { NOT_INITIALIZED }
328
+ Pushizo.Location.setGeofencingEnabled(args.optBoolean("enabled", false))
329
+ reply.success(null)
330
+ }
331
+ "isGeofencingEnabled" -> reply.success(JSONObject().put("enabled", Pushizo.Location.isGeofencingEnabled))
332
+
333
+ // Özellik bayrakları (ADR-0066): değerler yerel SDK önbelleğinden okunur; `refresh` geri çağrısı arka plan iş parçacığındadır.
334
+ "featureFlagsRefresh" -> Pushizo.FeatureFlags.refresh { ok -> reply.success(JSONObject().put("success", ok)) }
335
+ "featureFlagsIsEnabled" -> reply.success(
336
+ JSONObject().put("enabled", Pushizo.FeatureFlags.isEnabled(args.requireString("key"), args.optBoolean("defaultValue", false))),
337
+ )
338
+ "featureFlagsGetValue" -> reply.success(JSONObject().put("value", Pushizo.FeatureFlags.getValue(args.requireString("key")).orNull()))
339
+
340
+ // Gömülü yerleşimler (ADR-0068): anahtar ve limit denetimi yerel SDK'dadır (IllegalArgumentException → INVALID_ARGUMENT).
341
+ "placementsList" -> Pushizo.Placements.list(args.requireString("key"), args.optInt("limit", 1)) { messages ->
342
+ synchronized(placementMessages) {
343
+ messages.forEach { placementMessages.remove(it.id); placementMessages[it.id] = it }
344
+ }
345
+ reply.success(JSONObject().put("messages", JSONArray(messages.map { it.toBridgeJson() })))
346
+ }
347
+ "placementsReportImpression" -> { placementMessage(args)?.let { Pushizo.Placements.reportImpression(it) }; reply.success(null) }
348
+ "placementsReportClick" -> {
349
+ val buttonId = args.requireString("buttonId")
350
+ placementMessage(args)?.let { Pushizo.Placements.reportClick(it, buttonId) }
351
+ reply.success(null)
352
+ }
353
+ "placementsReportDismiss" -> { placementMessage(args)?.let { Pushizo.Placements.reportDismiss(it) }; reply.success(null) }
354
+
355
+ // Live Activities yalnızca iOS'ta vardır (ADR-0024); Android'de sessizce başarılı dönülmez.
356
+ "setupDefaultLiveActivity" -> reply.error(LIVE_ACTIVITY_UNSUPPORTED_CODE, LIVE_ACTIVITY_UNSUPPORTED_MESSAGE)
357
+ "startDefaultLiveActivity" -> reply.error(LIVE_ACTIVITY_UNSUPPORTED_CODE, LIVE_ACTIVITY_UNSUPPORTED_MESSAGE)
358
+ // Canlı sohbet (ADR-0040): kimlik, kuyruk, akış ve push native SDK'dadır.
359
+ "chatStart" -> Pushizo.Chat.start(args.optStringOrNull("name"), args.optStringOrNull("email"), args.optStringOrNull("language"), callback(reply) { JSONObject(it.toMap()) })
360
+ "chatGetConfig" -> Pushizo.Chat.getConfig(args.optStringOrNull("language"), callback(reply) { JSONObject(it.toMap()) })
361
+ "chatGetConversation" -> Pushizo.Chat.getConversation(callback(reply) { JSONObject(it.toMap()) })
362
+ "chatGetMessages" -> Pushizo.Chat.getMessages(
363
+ args.optLongOrNull("afterSeq"), args.optLongOrNull("beforeSeq"), args.optInt("limit", 50), callback(reply) { JSONObject(it.toMap()) },
364
+ )
365
+ "chatSendMessage" -> Pushizo.Chat.sendMessage(args.requireString("text"), args.optStringOrNull("optionId"), callback(reply) { it.toJson() })
366
+ "chatSendAttachment" -> {
367
+ val fileName = args.requireString("fileName")
368
+ val mimeType = args.requireString("mimeType")
369
+ val text = args.optStringOrNull("text")
370
+ val base64 = args.optStringOrNull("base64")
371
+ if (base64 != null) {
372
+ val bytes = android.util.Base64.decode(base64, android.util.Base64.DEFAULT)
373
+ Pushizo.Chat.sendAttachment(bytes, fileName, mimeType, text, callback(reply) { it.toJson() })
374
+ } else {
375
+ Pushizo.Chat.sendAttachment(android.net.Uri.parse(args.requireString("uri")), fileName, mimeType, text, callback(reply) { it.toJson() })
376
+ }
377
+ }
378
+ "chatMarkRead" -> Pushizo.Chat.markRead(args.optLong("seq", 0L), callback(reply) { JSONObject().put("unreadCount", it) })
379
+ "chatRefreshUnreadCount" -> Pushizo.Chat.refreshUnreadCount(callback(reply) { JSONObject().put("unreadCount", it) })
380
+ "chatGetUnreadCount" -> reply.success(JSONObject().put("unreadCount", Pushizo.Chat.unreadCount))
381
+ "chatLeaveOfflineMessage" -> Pushizo.Chat.leaveOfflineMessage(
382
+ args.requireString("email"), args.requireString("text"), args.optStringOrNull("name"), callback(reply) { it.toJson() },
383
+ )
384
+ "chatSetTyping" -> { Pushizo.Chat.setTyping(args.optBoolean("typing", false)); reply.success(null) }
385
+ "chatStartListening" -> { Pushizo.Chat.startListening(); reply.success(null) }
386
+ "chatStopListening" -> { Pushizo.Chat.stopListening(); reply.success(null) }
387
+ "chatAttachmentUrl" -> reply.success(
388
+ JSONObject().put("url", Pushizo.Chat.attachmentUrl(args.requireString("attachmentId"), args.optBoolean("download", false))),
389
+ )
390
+ "chatGetVisitorId" -> reply.success(JSONObject().put("visitorId", Pushizo.Chat.visitorId.orNull()))
391
+ else -> return false
392
+ }
393
+ } catch (e: IllegalArgumentException) {
394
+ reply.error("INVALID_ARGUMENT", e.message)
395
+ } catch (e: IllegalStateException) {
396
+ reply.error("NOT_READY", e.message)
397
+ } catch (e: Exception) {
398
+ reply.error("HS_ERROR", e.message)
399
+ }
400
+ return true
401
+ }
402
+
403
+ /** Rapor için mesajı son `placementsList` yanıtlarından bulur; bulunamazsa yok sayılır (yalnızca debug log). */
404
+ private fun placementMessage(args: JSONObject): HsInAppMessage? {
405
+ val id = args.requireString("id")
406
+ return synchronized(placementMessages) { placementMessages[id] } ?: run {
407
+ HsLog.d("yerleşim mesajı bulunamadı: $id")
408
+ null
409
+ }
410
+ }
411
+
412
+ /** SDK geri çağrısını köprü yanıtına çevirir; API hatasında sunucu kodu korunur. */
413
+ private fun <T> callback(reply: Reply, map: (T) -> JSONObject?) = HsCallback<T> { result ->
414
+ result.fold(
415
+ onSuccess = { reply.success(map(it)) },
416
+ onFailure = { e ->
417
+ val code = when (e) {
418
+ is HsApiException -> e.code
419
+ is IllegalStateException -> "NOT_READY"
420
+ is IllegalArgumentException -> "INVALID_ARGUMENT"
421
+ else -> "HS_ERROR"
422
+ }
423
+ reply.error(code, e.message)
424
+ },
425
+ )
426
+ }
427
+
428
+ companion object {
429
+ private const val MAX_PENDING_FOREGROUND = 32
430
+ private const val MAX_PLACEMENT_CACHE = 50
431
+ private const val NOT_INITIALIZED = "Önce Pushizo.initialize çağrılmalı"
432
+ private val LOCATION_PERMISSIONS = arrayOf(Manifest.permission.ACCESS_COARSE_LOCATION, Manifest.permission.ACCESS_FINE_LOCATION)
433
+ private const val LIVE_ACTIVITY_UNSUPPORTED_CODE = "PLATFORM_NOT_SUPPORTED"
434
+ private const val LIVE_ACTIVITY_UNSUPPORTED_MESSAGE = "Live Activities yalnızca iOS'ta desteklenir"
435
+
436
+ fun logLevel(name: String?): HsLog.Level = when (name) {
437
+ "none" -> HsLog.Level.NONE
438
+ "error" -> HsLog.Level.ERROR
439
+ "info" -> HsLog.Level.INFO
440
+ "debug" -> HsLog.Level.DEBUG
441
+ else -> HsLog.Level.WARN
442
+ }
443
+
444
+ fun HsNotification.toJson(): JSONObject = JSONObject()
445
+ .put("title", title.orNull())
446
+ .put("body", body.orNull())
447
+ .put("url", url.orNull())
448
+ .put("imageUrl", imageUrl.orNull())
449
+ .put("deliveryId", deliveryId.orNull())
450
+ .put("messageId", messageId.orNull())
451
+ .put("data", JSONObject(data))
452
+ .put("androidNotificationId", androidNotificationId)
453
+
454
+ fun HsPushSubscriptionState.toJson(): JSONObject = JSONObject()
455
+ .put("id", id.orNull())
456
+ .put("token", token.orNull())
457
+ .put("optedIn", optedIn)
458
+ .put("permission", permission)
459
+
460
+ fun HsInboxItem.toJson(): JSONObject = JSONObject()
461
+ .put("id", id)
462
+ .put("messageId", messageId.orNull())
463
+ .put("title", title.orNull())
464
+ .put("body", body.orNull())
465
+ .put("url", url.orNull())
466
+ .put("imageUrl", imageUrl.orNull())
467
+ .put("data", JSONObject(data))
468
+ .put("read", read)
469
+ .put("readAt", readAt.orNull())
470
+ .put("archivedAt", archivedAt.orNull())
471
+ .put("expiresAt", expiresAt.orNull())
472
+ .put("createdAt", createdAt.orNull())
473
+
474
+ fun HsInboxPage.toJson(): JSONObject = JSONObject()
475
+ .put("items", JSONArray(items.map { it.toJson() }))
476
+ .put("unreadCount", unreadCount)
477
+ .put("nextCursor", nextCursor.orNull())
478
+ .put("hasMore", hasMore)
479
+
480
+ fun HsPreference.toJson(): JSONObject = JSONObject()
481
+ .put("category", category)
482
+ .put("channel", channel.orNull())
483
+ .put("optedIn", optedIn)
484
+ .put("explicit", explicit)
485
+ .put("source", source.orNull())
486
+ .put("updatedAt", updatedAt.orNull())
487
+
488
+ fun HsMessageCategory.toJson(): JSONObject = JSONObject()
489
+ .put("key", key)
490
+ .put("name", JSONObject(name))
491
+ .put("description", JSONObject(description))
492
+ .put("channels", channels?.let { JSONArray(it) }.orNull())
493
+ .put("defaultOptedIn", defaultOptedIn)
494
+
495
+ fun HsPreferencesResult.toJson(): JSONObject = JSONObject()
496
+ .put("preferences", JSONArray(preferences.map { it.toJson() }))
497
+ .put("categories", JSONArray(categories.map { it.toJson() }))
498
+
499
+ // In-app mesaj modeli → JS `InAppMessage` (alanlar yerel modelle aynı; zamanlar epoch milisaniye).
500
+ fun HsInAppMessage.toBridgeJson(): JSONObject = JSONObject()
501
+ .put("id", id)
502
+ .put("priority", priority)
503
+ .put("triggers", JSONArray(triggers.map { it.toJson() }))
504
+ .put("triggerGroups", JSONArray(triggerGroups.map { group -> JSONArray(group.map { it.toJson() }) }))
505
+ .put("variantId", variantId.orNull())
506
+ .put("display", display.toJson())
507
+ .put("remainingImpressions", remainingImpressions)
508
+ .put("minIntervalSeconds", minIntervalSeconds)
509
+ .put("stopAfterInteraction", stopAfterInteraction)
510
+ .put("lastImpressionAt", lastImpressionAt.orNull())
511
+ .put("endAt", endAt.orNull())
512
+ .put("language", language.orNull())
513
+
514
+ fun HsInAppDisplay.toJson(): JSONObject = JSONObject()
515
+ .put("layout", layout.wire)
516
+ .put("backgroundColor", backgroundColor.orNull())
517
+ .put("textColor", textColor.orNull())
518
+ .put("dismissible", dismissible)
519
+ .put("autoDismissSeconds", autoDismissSeconds.orNull())
520
+ .put("contentType", contentType.wire)
521
+ .put("blocks", JSONArray(blocks.map { it.toJson() }))
522
+ .put("html", html.orNull())
523
+ .put("htmlHeight", htmlHeight.orNull())
524
+
525
+ fun HsInAppTrigger.toJson(): JSONObject = when (this) {
526
+ HsInAppTrigger.SessionStart -> JSONObject().put("kind", "session_start")
527
+ is HsInAppTrigger.Event -> JSONObject().put("kind", "event").put("name", name)
528
+ is HsInAppTrigger.Screen -> JSONObject().put("kind", "screen").put("name", name)
529
+ is HsInAppTrigger.Condition -> JSONObject().put("kind", "trigger").put("key", key).put("op", op).put("value", value.orNull())
530
+ is HsInAppTrigger.SessionDuration -> JSONObject().put("kind", "session_duration").put("seconds", seconds)
531
+ is HsInAppTrigger.Unsupported -> JSONObject().put("kind", "unsupported").put("name", kind)
532
+ }
533
+
534
+ fun HsInAppAction.toJson(): JSONObject = when (this) {
535
+ HsInAppAction.Dismiss -> JSONObject().put("type", "dismiss")
536
+ is HsInAppAction.Url -> JSONObject().put("type", "url").put("url", url)
537
+ is HsInAppAction.Deeplink -> JSONObject().put("type", "deeplink").put("url", url)
538
+ is HsInAppAction.Tags -> JSONObject().put("type", "tags").put("tags", JSONObject(tags))
539
+ HsInAppAction.PushPrompt -> JSONObject().put("type", "push_prompt")
540
+ is HsInAppAction.Outcome -> JSONObject().put("type", "outcome").put("name", name).put("value", value.orNull())
541
+ }
542
+
543
+ fun HsInAppBlock.Button.toJson(): JSONObject = JSONObject()
544
+ .put("id", id)
545
+ .put("text", text)
546
+ .put("action", action.toJson())
547
+ .put("backgroundColor", backgroundColor.orNull())
548
+ .put("textColor", textColor.orNull())
549
+
550
+ fun HsInAppCarouselCard.toJson(): JSONObject = JSONObject()
551
+ .put("id", id)
552
+ .put("title", title)
553
+ .put("body", body.orNull())
554
+ .put("imageUrl", imageUrl.orNull())
555
+ .put("imageAlt", imageAlt.orNull())
556
+ .put("button", button?.toJson().orNull())
557
+
558
+ fun HsInAppBlock.toJson(): JSONObject = when (this) {
559
+ is HsInAppBlock.Image -> JSONObject().put("type", "image").put("url", url).put("alt", alt.orNull())
560
+ is HsInAppBlock.Title -> JSONObject().put("type", "title").put("text", text)
561
+ is HsInAppBlock.Body -> JSONObject().put("type", "body").put("text", text)
562
+ is HsInAppBlock.Button -> toJson().put("type", "button")
563
+ is HsInAppBlock.Carousel -> JSONObject().put("type", "carousel").put("id", id).put("cards", JSONArray(cards.map { it.toJson() }))
564
+ }
565
+
566
+ /** JS `{ category, channel, optedIn }[]` → SDK girdisi; kural denetimi (1-100, kanal) SDK'dadır. */
567
+ fun JSONObject.preferenceInputs(key: String): List<HsPreferenceInput> {
568
+ val arr = optJSONArray(key) ?: throw IllegalArgumentException("$key gerekli")
569
+ return (0 until arr.length()).map { i ->
570
+ val item = arr.optJSONObject(i) ?: throw IllegalArgumentException("$key[$i] nesne olmalı")
571
+ HsPreferenceInput(item.requireString("category"), item.optStringOrNull("channel"), item.optBoolean("optedIn", false))
572
+ }
573
+ }
574
+
575
+ private fun Any?.orNull(): Any = this ?: JSONObject.NULL
576
+
577
+ fun JSONObject.optStringOrNull(key: String): String? = if (has(key) && !isNull(key)) optString(key) else null
578
+
579
+ fun JSONObject.optLongOrNull(key: String): Long? = if (has(key) && !isNull(key)) optLong(key) else null
580
+
581
+ fun JSONObject.requireString(key: String): String =
582
+ optStringOrNull(key)?.takeIf { it.isNotBlank() } ?: throw IllegalArgumentException("$key gerekli")
583
+
584
+ fun JSONObject.stringMap(key: String): Map<String, String> {
585
+ val obj = optJSONObject(key) ?: return emptyMap()
586
+ val out = LinkedHashMap<String, String>()
587
+ obj.keys().forEach { k -> if (!obj.isNull(k)) out[k] = obj.get(k).toString() }
588
+ return out
589
+ }
590
+
591
+ fun JSONObject.stringList(key: String): List<String> {
592
+ val arr = optJSONArray(key) ?: return emptyList()
593
+ return (0 until arr.length()).mapNotNull { i -> if (arr.isNull(i)) null else arr.get(i).toString() }
594
+ }
595
+
596
+ /** JSON nesnesini SDK'nın beklediği Map/List yapısına çevirir (iç içe değerler korunur). */
597
+ fun JSONObject.toMap(): Map<String, Any?> {
598
+ val out = LinkedHashMap<String, Any?>()
599
+ keys().forEach { k -> out[k] = unwrap(get(k)) }
600
+ return out
601
+ }
602
+
603
+ private fun unwrap(value: Any?): Any? = when (value) {
604
+ JSONObject.NULL, null -> null
605
+ is JSONObject -> value.toMap()
606
+ is JSONArray -> (0 until value.length()).map { unwrap(value.get(it)) }
607
+ else -> value
608
+ }
609
+ }
610
+ }