cordova-plugin-pushizo 0.2.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.
package/README.md CHANGED
@@ -34,6 +34,9 @@ Pushizo'nun Cordova eklentisi. Native Pushizo Android (`com.pushizo:pushizo-andr
34
34
  - In-app mesajlar (tetik, ekran, duraklatma, tıklama ve yaşam döngüsü olayları; native çizim)
35
35
  - Konum paylaşımı (yalnızca ön plan, açıklama + izin istemi) ve arka plan bölge izleme
36
36
  - Özellik bayrakları (`FeatureFlags`) ve gömülü yerleşimler (`Placements`)
37
+ - Android teslimat güçlendirme (`Delivery`: üretici/ROM teşhisi, ayar ekranına yönlendirme; iOS'ta zararsız)
38
+ - Profille `login`, reklam kişiselleştirme rızası (`setAdsPersonalizationConsent`, `getConsents`), reklam kimliği (`Ads`), rozet, arka plan konum izni
39
+ - Kullanıcı özellikleri (`User.setProperty`), özellik bayrağı ve bildirim kutusu gözlemcileri, olay tekilleştirme kimliği (`eventId`), hazır sohbet ekranı (`Chat.show`)
37
40
  - Bildirim kutusu, özel olay, KVKK/GDPR gizlilik onayı, günlük seviyesi, bildirim tepsisini temizleme
38
41
 
39
42
  ## Kurulum
@@ -147,6 +150,8 @@ geri çekilme + `after_seq` yoklaması) ve push ile gelen temsilci mesajları (`
147
150
  Mesajlar `seq` ile sıralanır; ağ yokken gönderilen mesaj `pending` döner ve gönderilince olayla sunucu kopyası gelir.
148
151
  Ayrıntı: [android rehberi](https://docs.pushizo.com/docs/sdk/android) / [ios rehberi](https://docs.pushizo.com/docs/sdk/ios) → "Canlı sohbet".
149
152
 
153
+ Hazır sohbet ekranı için kendi arayüzünüzü yazmanız gerekmez: `Pushizo.Chat.show()` yerel SDK'nın sohbet ekranını açar (Android `HsChatActivity`, iOS modal `HSChatViewController`), `Pushizo.Chat.hide()` kapatır, `Pushizo.Chat.isPresented()` ekranın açık olup olmadığını döndürür. Ayrıntı: "Kullanıcı özellikleri, gözlemciler, olay kimliği ve hazır sohbet ekranı".
154
+
150
155
  ### Konum
151
156
 
152
157
  Kullanıcı izin verirse cihazın konumu push aboneliğine yazılır; segmentlerde konuma göre hedefleme için
@@ -200,8 +205,8 @@ const on = await Pushizo.Location.isGeofencingEnabled();
200
205
  ```
201
206
 
202
207
  - Üç koşul birlikte gerekir: `setGeofencingEnabled(true)`, `setShared(true)` ve arka plan konum izni (iOS "Her Zaman",
203
- Android `ACCESS_BACKGROUND_LOCATION`). Köprü bu izni **istemez** ve manifest/Info.plist'e **eklemez**; `Info.plist`'e `NSLocationAlwaysAndWhenInUseUsageDescription`, Android manifest'ine `ACCESS_BACKGROUND_LOCATION` eklemek
204
- (`config.xml` `<config-file>`/`<edit-config>`) ve izni istemek uygulamanın işidir.
208
+ Android `ACCESS_BACKGROUND_LOCATION`). Köprü bu izni manifest/Info.plist'e **eklemez**; `Info.plist`'e `NSLocationAlwaysAndWhenInUseUsageDescription`, Android manifest'ine `ACCESS_BACKGROUND_LOCATION` eklemek
209
+ (`config.xml` `<config-file>`/`<edit-config>`) uygulamanın işidir. İzin `Location.requestBackgroundPermission()` ile istenir (aşağıda).
205
210
  Mağaza beyanları ve aydınlatma metni uygulama geliştiricisinin sorumluluğundadır.
206
211
  - `initialize` öncesinde `setGeofencingEnabled` `NOT_READY` ile reddedilir. `setShared(false)` veya gizlilik onayının geri
207
212
  alınması kayıtlı bölgeleri kaldırır; tercih korunur.
@@ -223,6 +228,94 @@ const refreshed = await Pushizo.FeatureFlags.refresh(); // yeni
223
228
  `isEnabled(key, default = false)` ve `getValue(key, default = null)` yerel önbellekten okur; köprü asenkron olduğundan
224
229
  Promise döndürürler. Boş anahtar `TypeError` ile reddedilir.
225
230
 
231
+ ### Android teslimat güçlendirme
232
+
233
+ Xiaomi, Huawei, Oppo, Vivo ve Samsung gibi üreticilerde pil ve otomatik başlatma yöneticisi arka plandaki uygulamayı durdurur;
234
+ bildirim gecikir ya da gelmez ([rehber](https://docs.pushizo.com/docs/channels/android-delivery)). `Pushizo.Delivery` cihazdaki
235
+ kısıtları okur ve kullanıcıyı ilgili ayar ekranına götürür.
236
+
237
+ ```ts
238
+ const status = await Pushizo.Delivery.status(); // { supported, vendor, rom, risk, restricted, recommendedSettings, … }
239
+ if (await Pushizo.Delivery.shouldShowGuidance()) { // risk var ve diyalog son 14 günde gösterilmedi
240
+ const opened = await Pushizo.Delivery.showGuidance(); // hazır diyalog (22 dil); kabul edilirse ayar ekranı açılır
241
+ }
242
+ await Pushizo.Delivery.openSettings('auto_start'); // kendi arayüzünüzden
243
+ ```
244
+
245
+ | Metot | Açıklama |
246
+ |---|---|
247
+ | `Delivery.status()` | `Promise<DeliveryStatus>`: `supported`, `manufacturer`, `brand`, `vendor`, `aggressiveVendor`, `rom`, `romVersion`, `notificationsEnabled`, `channelBlocked`, `batteryOptimizationExempt`, `backgroundRestricted`, `standbyBucket`, `powerSaveMode`, `dataSaverEnabled`, `restricted`, `risk` (`none` \| `elevated` \| `high`), `recommendedSettings`. |
248
+ | `Delivery.shouldShowGuidance(minIntervalDays = 14)` | `Promise<boolean>`: teslim riski var ve hazır diyalog son `minIntervalDays` günde gösterilmedi. |
249
+ | `Delivery.openSettings(setting = 'auto')` | `Promise<boolean>`: ayar ekranı açıldı mı. `setting`: `auto` \| `notifications` \| `auto_start` \| `battery_optimization` \| `app_details`; üreticiye özgü ekran yoksa standart Android ekranına düşülür. |
250
+ | `Delivery.showGuidance({ setting?, message? })` | `Promise<boolean>`: hazır açıklama diyaloğu; kullanıcı kabul etti ve ayar ekranı açıldıysa `true`. SDK diyaloğu kendiliğinden göstermez. |
251
+
252
+ Yalnızca Android'de etkilidir: iOS'ta `status()` `supported: false` ve `risk: 'none'` döner, `openSettings` ile `showGuidance`
253
+ hiçbir şey yapmadan `false` döner. Köprü `REQUEST_IGNORE_BATTERY_OPTIMIZATIONS` iznini istemez ve manifest'e eklemez.
254
+
255
+ ### Profil, reklam rızası, reklam kimliği ve rozet
256
+
257
+ Yerel SDK'ların kalan yüzeyi de köprüde vardır; tek platforma özgü çağrılar diğer platformda zararsızdır (istisna yok,
258
+ etkisiz ya da `false`).
259
+
260
+ ```js
261
+ await Pushizo.login('user_42', { jwt, profile: { email: 'ali@ornek.com', sms: '+905551112233', tags: { plan: 'pro' }, aliases: { crm: 'c-1' } } });
262
+ await Pushizo.User.setAdsPersonalizationConsent(true); // reklam kişiselleştirme rızası; güncel tercihleri döndürür
263
+ const consents = await Pushizo.User.getConsents(); // [{ purpose, granted, source, updatedAt }]
264
+ await Pushizo.Ads.setAdvertisingId(gaidOrIdfa); // null kaydı siler
265
+ const shown = await Pushizo.Notifications.setBadgeCount(3); // rozet bu cihazda gösterilebiliyorsa true
266
+ await Pushizo.Notifications.clearBadge();
267
+ if (await Pushizo.Location.permissionGranted() && !(await Pushizo.Location.backgroundPermissionGranted())) {
268
+ await Pushizo.Location.requestBackgroundPermission('Mağazaya yaklaşınca haber vermek için'); // iOS: requestAlwaysPermission ile aynı
269
+ }
270
+ const listening = await Pushizo.Chat.isListening();
271
+ const ready = await Pushizo.isInitialized();
272
+ ```
273
+
274
+ | Metot | Açıklama |
275
+ |---|---|
276
+ | `login(externalId, { identityHash?, jwt?, profile? })` | `profile`: `{ email?, sms?, tags?, aliases? }`. Giriş ve profil tek çağrıda; geçersiz e-posta/telefon/takma ad girişten **önce** `INVALID_ARGUMENT` ile reddedilir. Doğrulama ve sıralama yerel SDK'lardadır (Android `login(id, HsUserProfile)`, iOS `login(_:profile:)`). |
277
+ | `User.setAdsPersonalizationConsent(granted)` | `Promise<UserPreferences>`: reklam kişiselleştirme rızası (`ads_personalization`); `false` rızayı geri alır. |
278
+ | `User.getConsents()` | `Promise<UserConsent[]>`: `purpose`, `granted`, `source`, `updatedAt` (epoch ms). Abonelik yoksa `NOT_READY`. |
279
+ | `User.registerAdm(token)` | Fire OS ADM kayıt kimliği (yalnızca Android; geçersiz kimlik `INVALID_ARGUMENT`). iOS: etkisiz. |
280
+ | `Ads.setAdvertisingId(id \| null)` | GAID/IDFA; `null` veya sıfır kimlik sunucudaki kaydı siler. Kimliği uygulama alır (SDK reklam kitaplığı ve ATT istemi içermez). |
281
+ | `Notifications.setBadgeCount(count)` / `clearBadge()` | `Promise<boolean>`: rozet bu cihazda gösterilebiliyorsa `true`. `count` negatif olmayan tam sayı (`RangeError`). iOS: uygulama rozeti ve bildirim uzantısıyla paylaşılan sayaç (her zaman `true`). Android: başlatıcı rozeti için "sayıyı ayarla" API'si olmadığından yerel SDK sayıyı saklar ve sonraki bildirimlere yazar; Android 8 öncesinde, bildirimler ya da kanal rozeti kapalıyken `false`. |
282
+ | `Notifications.getBadgeCount()` | `Promise<number>`: Android'de saklanan son sayı, iOS'ta uygulama simgesindeki rozet. |
283
+ | `Location.permissionGranted()` / `backgroundPermissionGranted()` | `Promise<boolean>`: ön plan / arka plan ("Her Zaman") konum izni; yerel SDK'dan okunur, istem açmaz. |
284
+ | `Location.requestBackgroundPermission(rationale?)` / `requestAlwaysPermission()` | `Promise<boolean>`: arka plan konum izni; iki ad aynı çağrıdır. Android: açıklama diyaloğu + `ACCESS_BACKGROUND_LOCATION` (Android 11+ Ayarlar ekranı; manifest'te yoksa `false`). iOS: "Her Zaman" izni (`rationale` kullanılmaz). |
285
+ | `Chat.isListening()` | `Promise<boolean>`: canlı dinleme açık mı. |
286
+ | `isInitialized()` | `Promise<boolean>`: yerel SDK başlatıldı mı. |
287
+
288
+ ### Kullanıcı özellikleri, gözlemciler, olay kimliği ve hazır sohbet ekranı
289
+
290
+ ```js
291
+ await Pushizo.User.setProperty('plan', 'pro'); // metin, sayı, mantıksal
292
+ await Pushizo.User.setProperty('address', { city: 'İzmir', tags: ['vip'] }); // dizi / düz nesne
293
+ await Pushizo.User.setProperty('plan', null); // null özelliği siler
294
+
295
+ const removeFlags = Pushizo.FeatureFlags.addObserver(async () => {
296
+ applyTheme(await Pushizo.FeatureFlags.getValue('tema', 'acik'));
297
+ });
298
+ const removeInbox = Pushizo.Inbox.addObserver(({ type, itemId, unreadCount }) => setBadge(unreadCount));
299
+
300
+ // Reklam pikseliyle aynı kimlik verilirse sunucu olayı tekilleşir.
301
+ await Pushizo.Session.sendEvent('purchase', { sku: 'A1' }, 49.9, { eventId: 'order_42:purchase' });
302
+
303
+ await Pushizo.Chat.show(); // hazır sohbet ekranı
304
+ if (await Pushizo.Chat.isPresented()) await Pushizo.Chat.hide();
305
+ ```
306
+
307
+ | Metot | Açıklama |
308
+ |---|---|
309
+ | `User.setProperty(key, value)` | Kullanıcı özelliği yazar; `null` siler. `key` 1-64 karakter (`TypeError` / `RangeError`); `value` metin, sonlu sayı, mantıksal ya da bunların dizisi/düz nesnesi (iç içe `null`, `Date`, fonksiyon vb. `TypeError`). Çevrimdışıyken yerel SDK kuyruğunda bekler. |
310
+ | `FeatureFlags.addObserver(cb)` / `removeObserver(cb)` | Bayrak değerleri sunucudan her yenilendiğinde (oturum başı ve `refresh()`) çağrılır; `addObserver` aboneliği kaldıran fonksiyonu döndürür. |
311
+ | `Inbox.addObserver(cb)` / `removeObserver(cb)` | Kutu değişim olayı: `{ type: 'listed' \| 'read' \| 'read_all' \| 'archived' \| 'count', itemId?, unreadCount }`. `read`/`read_all`/`archived` her işlemde, `listed`/`count` yalnızca okunmamış sayısı değiştiğinde bildirilir; `itemId` yalnızca tek öğe olaylarında bulunur. |
312
+ | `Session.sendEvent(name, properties?, value?, { eventId? })` | `eventId` tekilleştirme kimliğidir: 8-64 karakter; harf, rakam ve `. _ : -`. Biçim geçersizse yerel SDK kendi kimliğini üretir; metin olmayan kimlik `TypeError`. |
313
+ | `Chat.show()` / `hide()` | Hazır sohbet ekranını açar / kapatır (Android `HsChatActivity`, iOS modal `HSChatViewController`). Ekran açıksa yenisi açılmaz; `initialize` öncesinde `show()` `NOT_READY` ile reddedilir. |
314
+ | `Chat.isPresented()` | `Promise<boolean>`: hazır sohbet ekranı açık mı. Yerel Android SDK bu durumu dışa açmadığından köprü `HsChatActivity` yaşam döngüsünü izler. |
315
+
316
+ Köprüye bağlanamayan yerel yüzey: yerel görünümler (`HsChatView`, `HsContentCardsView`, iOS `HSChatViewController` gömme) ve
317
+ `InAppMessages.setRenderer` (özel çizici yerel kod ister).
318
+
226
319
  ### Gömülü yerleşimler
227
320
 
228
321
  Uygulamanın ayırdığı bir alana (ana sayfa afişi, liste arası kart) dashboard'dan içerik gönderin
@@ -315,10 +408,10 @@ ve carousel bloklarını çıkarır.
315
408
  </platform>
316
409
  ```
317
410
 
318
- Köprü Kotlin ile yazıldığından `GradlePluginKotlinEnabled` zorunludur. Yerel SDK 0.2.1'in `androidx.work` bağımlılığı
411
+ Köprü Kotlin ile yazıldığından `GradlePluginKotlinEnabled` zorunludur. Yerel SDK 0.3.0'in `androidx.work` bağımlılığı
319
412
  `compileSdk` 35 ister; cordova-android 13'ün varsayılanı 34 olduğundan `android-compileSdkVersion` tercihi gerekir.
320
413
  2. Pushizo dashboard'unda Firebase servis hesabı JSON'unu yükleyin (kurulum sihirbazında **Cordova** seçilebilir); kayıt sonrası otomatik doğrulanır.
321
- 3. Eklenti `com.pushizo:pushizo-android:0.2.1` artefaktına bağlıdır (özellik bayrakları, yerleşimler ve bölge izleme bu sürümle gelir). Maven Central yayınına kadar `sdk/android` içinde `gradle :pushizo:publishToMavenLocal` çalıştırın; eklenti `mavenLocal()` deposunu ekler.
414
+ 3. Eklenti `com.pushizo:pushizo-android:0.3.0` artefaktına bağlıdır (özellik bayrakları, yerleşimler ve bölge izleme bu sürümle gelir). Maven Central yayınına kadar `sdk/android` içinde `gradle :pushizo:publishToMavenLocal` çalıştırın; eklenti `mavenLocal()` deposunu ekler.
322
415
  4. FCM servisi, `POST_NOTIFICATIONS` izni ve bildirim Activity'si SDK manifestinden birleşir. Bildirim ikonu için `AndroidManifest.xml` içinde `com.pushizo.sdk.default_notification_icon` meta-data'sı verilebilir.
323
416
 
324
417
  Eklenti, JS ile yapılan `initialize` ayarlarını (yalnızca uygulama kimliği ve herkese açık ayarlar) saklar; süreç bildirim tıklaması veya FCM mesajıyla yeniden başladığında SDK WebView yüklenmeden başlatılır.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "cordova-plugin-pushizo",
3
- "version": "0.2.0",
3
+ "version": "0.3.0",
4
4
  "description": "Pushizo Cordova eklentisi: push bildirimi, kullanıcı/tag, e-posta/SMS, in-app mesaj ve bildirim kutusu (Android + iOS)",
5
5
  "license": "MIT",
6
6
  "author": "Pushizo <bildirim@pushizo.com>",
package/plugin.xml CHANGED
@@ -3,7 +3,7 @@
3
3
  <plugin xmlns="http://apache.org/cordova/ns/plugins/1.0"
4
4
  xmlns:android="http://schemas.android.com/apk/res/android"
5
5
  id="cordova-plugin-pushizo"
6
- version="0.2.0">
6
+ version="0.3.0">
7
7
  <name>Pushizo</name>
8
8
  <description>Push bildirimi, kullanıcı/tag, e-posta/SMS, in-app mesaj ve bildirim kutusu (Pushizo)</description>
9
9
  <license>MIT</license>
@@ -53,7 +53,7 @@
53
53
  <source-file src="src/android/com/pushizo/cordova/PushizoInitProvider.kt" target-dir="app/src/main/kotlin/com/pushizo/cordova" />
54
54
 
55
55
  <framework src="src/android/pushizo.gradle" custom="true" type="gradleReference" />
56
- <framework src="com.pushizo:pushizo-android:0.2.1" />
56
+ <framework src="com.pushizo:pushizo-android:0.3.0" />
57
57
  </platform>
58
58
 
59
59
  <platform name="ios">
@@ -89,7 +89,7 @@
89
89
  </config>
90
90
  <pods use-frameworks="true">
91
91
  <!-- Monorepo/yerel geliştirme: platforms/ios/Podfile içinde :path => '<repo>/sdk/ios' (README). -->
92
- <pod name="Pushizo" spec="~> 0.2" />
92
+ <pod name="Pushizo" spec="~> 0.3" />
93
93
  </pods>
94
94
  </podspec>
95
95
  </platform>
@@ -3,15 +3,19 @@ package com.pushizo.cordova
3
3
  import android.Manifest
4
4
  import android.app.Activity
5
5
  import android.app.AlertDialog
6
+ import android.app.Application
6
7
  import android.content.Context
7
8
  import android.content.pm.PackageManager
8
9
  import android.os.Build
10
+ import android.os.Bundle
9
11
  import com.pushizo.sdk.Pushizo
10
12
  import com.pushizo.sdk.HsApiException
11
13
  import com.pushizo.sdk.HsCallback
14
+ import com.pushizo.sdk.HsChatActivity
12
15
  import com.pushizo.sdk.HsChatEventAdapter
13
16
  import com.pushizo.sdk.HsChatOpenListener
14
17
  import com.pushizo.sdk.HsClickEvent
18
+ import com.pushizo.sdk.HsConsent
15
19
  import com.pushizo.sdk.HsForegroundEvent
16
20
  import com.pushizo.sdk.HsInAppAction
17
21
  import com.pushizo.sdk.HsInAppBlock
@@ -22,7 +26,13 @@ import com.pushizo.sdk.HsInAppLifecycleEvent
22
26
  import com.pushizo.sdk.HsInAppLifecycleListener
23
27
  import com.pushizo.sdk.HsInAppMessage
24
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
25
34
  import com.pushizo.sdk.HsInboxItem
35
+ import com.pushizo.sdk.HsInboxObserver
26
36
  import com.pushizo.sdk.HsInboxPage
27
37
  import com.pushizo.sdk.HsLog
28
38
  import com.pushizo.sdk.HsMessageCategory
@@ -31,8 +41,11 @@ import com.pushizo.sdk.HsPreference
31
41
  import com.pushizo.sdk.HsPreferenceInput
32
42
  import com.pushizo.sdk.HsPreferencesResult
33
43
  import com.pushizo.sdk.HsPushSubscriptionState
44
+ import com.pushizo.sdk.HsUserProfile
34
45
  import org.json.JSONArray
35
46
  import org.json.JSONObject
47
+ import java.util.Collections
48
+ import java.util.WeakHashMap
36
49
  import java.util.concurrent.atomic.AtomicBoolean
37
50
  import java.util.concurrent.atomic.AtomicLong
38
51
 
@@ -53,6 +66,9 @@ internal class PushizoBridgeCore(
53
66
  /** JS tarafında ön plan dinleyicisi varsa gösterim JS kararına bırakılır. */
54
67
  @Volatile var foregroundHandlerEnabled = false
55
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
+
56
72
  private val listenersRegistered = AtomicBoolean(false)
57
73
  private val foregroundSeq = AtomicLong(0)
58
74
 
@@ -99,6 +115,39 @@ internal class PushizoBridgeCore(
99
115
  /** Sohbet bildirimine tıklama → JS `chatOpen` (cephe dinleyici yoksa bekletir). */
100
116
  private val chatOpenListener = HsChatOpenListener { info -> emit("chatOpen", JSONObject(info.toMap())) }
101
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
+
102
151
  private val inAppLifecycleListener = object : HsInAppLifecycleListener {
103
152
  private fun send(event: String, e: HsInAppLifecycleEvent) =
104
153
  emit("inAppLifecycle", JSONObject().put("event", event).put("message", JSONObject().put("id", e.message.id)))
@@ -124,9 +173,12 @@ internal class PushizoBridgeCore(
124
173
  Pushizo.InAppMessages.addLifecycleListener(inAppLifecycleListener)
125
174
  Pushizo.Chat.addListener(chatListener)
126
175
  Pushizo.Chat.addOpenListener(chatOpenListener)
176
+ Pushizo.FeatureFlags.addObserver(featureFlagObserver)
177
+ Pushizo.Inbox.addObserver(inboxObserver)
127
178
  }
128
179
 
129
180
  fun detach() {
181
+ (context.applicationContext as? Application)?.unregisterActivityLifecycleCallbacks(chatScreenTracker)
130
182
  if (!listenersRegistered.compareAndSet(true, false)) return
131
183
  Pushizo.Notifications.removeClickListener(clickListener)
132
184
  Pushizo.Notifications.removeForegroundLifecycleListener(foregroundListener)
@@ -136,6 +188,8 @@ internal class PushizoBridgeCore(
136
188
  Pushizo.InAppMessages.removeLifecycleListener(inAppLifecycleListener)
137
189
  Pushizo.Chat.removeListener(chatListener)
138
190
  Pushizo.Chat.removeOpenListener(chatOpenListener)
191
+ Pushizo.FeatureFlags.removeObserver(featureFlagObserver)
192
+ Pushizo.Inbox.removeObserver(inboxObserver)
139
193
  // Bekleyen ön plan bildirimleri kaybolmasın diye gösterilir.
140
194
  val pending = synchronized(pendingForeground) { pendingForeground.values.toList().also { pendingForeground.clear() } }
141
195
  pending.forEach { it.display() }
@@ -201,8 +255,69 @@ internal class PushizoBridgeCore(
201
255
 
202
256
  fun locationPermissionJson(): JSONObject = JSONObject().put("permission", Pushizo.Location.permissionGranted)
203
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
+
204
316
  /** Uygulama manifest'inde tanımlı konum izinleri (eklenti izinleri otomatik eklemez; README "Konum"). */
205
- private fun declaredLocationPermissions(): Array<String> {
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> {
206
321
  val requested = try {
207
322
  val pm = context.packageManager
208
323
  val info = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
@@ -215,12 +330,12 @@ internal class PushizoBridgeCore(
215
330
  } catch (e: PackageManager.NameNotFoundException) {
216
331
  emptySet()
217
332
  }
218
- return LOCATION_PERMISSIONS.filter { it in requested }.toTypedArray()
333
+ return candidates.filter { it in requested }.toTypedArray()
219
334
  }
220
335
 
221
336
  /**
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.
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.
224
339
  */
225
340
  fun handle(method: String, args: JSONObject, reply: Reply): Boolean {
226
341
  try {
@@ -239,8 +354,25 @@ internal class PushizoBridgeCore(
239
354
  reply.success(null)
240
355
  }
241
356
  "setConsentGiven" -> { Pushizo.setConsentGiven(args.optBoolean("given", false)); reply.success(null) }
357
+ "isInitialized" -> reply.success(JSONObject().put("initialized", Pushizo.isInitialized))
242
358
  "login" -> {
243
- Pushizo.login(args.requireString("externalId"), args.optStringOrNull("identityHash"), args.optStringOrNull("jwt"))
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
+ }
244
376
  reply.success(null)
245
377
  }
246
378
  "updateUserJwt" -> { Pushizo.updateUserJwt(args.requireString("jwt")); reply.success(null) }
@@ -252,6 +384,11 @@ internal class PushizoBridgeCore(
252
384
  "addAliases" -> { Pushizo.User.addAliases(args.stringMap("aliases")); reply.success(null) }
253
385
  "removeAlias" -> { Pushizo.User.removeAlias(args.requireString("label")); reply.success(null) }
254
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
+ }
255
392
  // Geçersiz adres → IllegalArgumentException → INVALID_ARGUMENT
256
393
  "addEmail" -> { Pushizo.User.addEmail(args.requireString("email")); reply.success(null) }
257
394
  "removeEmail" -> { Pushizo.User.removeEmail(args.requireString("email")); reply.success(null) }
@@ -264,6 +401,13 @@ internal class PushizoBridgeCore(
264
401
  // Tercihler (ADR-0019 §4): sahiplik kanıtı yerel SDK'da eklenir; doğrulama hatası INVALID_ARGUMENT, abonelik yoksa NOT_READY.
265
402
  "getPreferences" -> Pushizo.User.getPreferences(callback(reply) { it.toJson() })
266
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) }
267
411
 
268
412
  "getPushSubscription" -> reply.success(Pushizo.User.pushSubscription.state.toJson())
269
413
  "optIn" -> { Pushizo.User.pushSubscription.optIn(); reply.success(null) }
@@ -282,6 +426,9 @@ internal class PushizoBridgeCore(
282
426
  reply.success(null)
283
427
  }
284
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))
285
432
  "setForegroundHandlerEnabled" -> { foregroundHandlerEnabled = args.optBoolean("enabled", false); reply.success(null) }
286
433
  "displayNotification" -> {
287
434
  val id = args.requireString("notificationId")
@@ -296,7 +443,11 @@ internal class PushizoBridgeCore(
296
443
 
297
444
  "sendEvent" -> {
298
445
  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)
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)
300
451
  reply.success(null)
301
452
  }
302
453
  "setLogLevel" -> { Pushizo.Debug.setLogLevel(logLevel(args.optStringOrNull("level"))); reply.success(null) }
@@ -314,6 +465,8 @@ internal class PushizoBridgeCore(
314
465
  "inboxMarkAllRead" -> Pushizo.Inbox.markAllRead(callback(reply) { JSONObject().put("unreadCount", it) })
315
466
  "inboxArchive" -> Pushizo.Inbox.archive(args.requireString("id"), callback(reply) { null })
316
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)
317
470
 
318
471
  // Konum (v2 Faz 17b): izin isteği Activity gerektirdiğinden köprü sınıfında ele alınır.
319
472
  "setLocationShared" -> {
@@ -322,6 +475,9 @@ internal class PushizoBridgeCore(
322
475
  reply.success(null)
323
476
  }
324
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
+ )
325
481
  // Arka plan bölge izleme (ADR-0065): varsayılan kapalı; köprü izin istemez, manifest'e izin eklemez.
326
482
  "setGeofencingEnabled" -> {
327
483
  check(Pushizo.isInitialized) { NOT_INITIALIZED }
@@ -330,6 +486,26 @@ internal class PushizoBridgeCore(
330
486
  }
331
487
  "isGeofencingEnabled" -> reply.success(JSONObject().put("enabled", Pushizo.Location.isGeofencingEnabled))
332
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
+
333
509
  // Özellik bayrakları (ADR-0066): değerler yerel SDK önbelleğinden okunur; `refresh` geri çağrısı arka plan iş parçacığındadır.
334
510
  "featureFlagsRefresh" -> Pushizo.FeatureFlags.refresh { ok -> reply.success(JSONObject().put("success", ok)) }
335
511
  "featureFlagsIsEnabled" -> reply.success(
@@ -388,6 +564,15 @@ internal class PushizoBridgeCore(
388
564
  JSONObject().put("url", Pushizo.Chat.attachmentUrl(args.requireString("attachmentId"), args.optBoolean("download", false))),
389
565
  )
390
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()))
391
576
  else -> return false
392
577
  }
393
578
  } catch (e: IllegalArgumentException) {
@@ -410,6 +595,15 @@ internal class PushizoBridgeCore(
410
595
  }
411
596
 
412
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
+
413
607
  private fun <T> callback(reply: Reply, map: (T) -> JSONObject?) = HsCallback<T> { result ->
414
608
  result.fold(
415
609
  onSuccess = { reply.success(map(it)) },
@@ -441,6 +635,30 @@ internal class PushizoBridgeCore(
441
635
  else -> HsLog.Level.WARN
442
636
  }
443
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
+
444
662
  fun HsNotification.toJson(): JSONObject = JSONObject()
445
663
  .put("title", title.orNull())
446
664
  .put("body", body.orNull())
@@ -471,6 +689,27 @@ internal class PushizoBridgeCore(
471
689
  .put("expiresAt", expiresAt.orNull())
472
690
  .put("createdAt", createdAt.orNull())
473
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
+
474
713
  fun HsInboxPage.toJson(): JSONObject = JSONObject()
475
714
  .put("items", JSONArray(items.map { it.toJson() }))
476
715
  .put("unreadCount", unreadCount)
@@ -492,6 +731,13 @@ internal class PushizoBridgeCore(
492
731
  .put("channels", channels?.let { JSONArray(it) }.orNull())
493
732
  .put("defaultOptedIn", defaultOptedIn)
494
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
+
495
741
  fun HsPreferencesResult.toJson(): JSONObject = JSONObject()
496
742
  .put("preferences", JSONArray(preferences.map { it.toJson() }))
497
743
  .put("categories", JSONArray(categories.map { it.toJson() }))