|
| 1 | +package com.onesignal; |
| 2 | + |
| 3 | +import android.os.SystemClock; |
| 4 | +import android.support.annotation.NonNull; |
| 5 | +import android.support.annotation.Nullable; |
| 6 | +import android.support.annotation.WorkerThread; |
| 7 | + |
| 8 | +import org.json.JSONException; |
| 9 | +import org.json.JSONObject; |
| 10 | + |
| 11 | +import java.util.Arrays; |
| 12 | +import java.util.List; |
| 13 | +import java.util.concurrent.atomic.AtomicBoolean; |
| 14 | + |
| 15 | + |
| 16 | +/** |
| 17 | + * Entry points that could cause on_focus to fire: |
| 18 | + * 1. OSSessionManager.session changed (onSessionEnded) - Send any attributed session time |
| 19 | + * 2. App is foregrounded (appForegrounded) - Set start focused time |
| 20 | + * 3. App is backgrounded (appBackgrounded) - Kick off job to sync when session ends |
| 21 | + */ |
| 22 | + |
| 23 | + |
| 24 | +class FocusTimeController { |
| 25 | + // Only present if app is currently in focus. |
| 26 | + @Nullable private Long timeFocusedAtMs; |
| 27 | + |
| 28 | + private static FocusTimeController sInstance; |
| 29 | + |
| 30 | + private List<FocusTimeProcessorBase> focusTimeProcessors = |
| 31 | + Arrays.asList(new FocusTimeProcessorUnattributed(), new FocusTimeProcessorAttributed()); |
| 32 | + |
| 33 | + private enum FocusEventType { |
| 34 | + BACKGROUND, |
| 35 | + END_SESSION |
| 36 | + } |
| 37 | + |
| 38 | + private FocusTimeController() { } |
| 39 | + public static synchronized FocusTimeController getInstance() { |
| 40 | + if (sInstance == null) |
| 41 | + sInstance = new FocusTimeController(); |
| 42 | + return sInstance; |
| 43 | + } |
| 44 | + |
| 45 | + void appForegrounded() { |
| 46 | + timeFocusedAtMs = SystemClock.elapsedRealtime(); |
| 47 | + } |
| 48 | + |
| 49 | + void appBackgrounded() { |
| 50 | + giveProcessorsValidFocusTime(OneSignal.getSessionManager().getSessionResult(), FocusEventType.BACKGROUND); |
| 51 | + timeFocusedAtMs = null; |
| 52 | + } |
| 53 | + |
| 54 | + void onSessionEnded(@NonNull OSSessionManager.SessionResult lastSessionResult) { |
| 55 | + final FocusEventType focusEventType = FocusEventType.END_SESSION; |
| 56 | + boolean hadValidTime = giveProcessorsValidFocusTime(lastSessionResult, focusEventType); |
| 57 | + |
| 58 | + // If there is no in focus time to be added we just need to send the time from the last session that just ended. |
| 59 | + if (!hadValidTime) { |
| 60 | + for (FocusTimeProcessorBase focusTimeProcessor : focusTimeProcessors) |
| 61 | + focusTimeProcessor.sendUnsentTimeNow(focusEventType); |
| 62 | + } |
| 63 | + } |
| 64 | + |
| 65 | + void doBlockingBackgroundSyncOfUnsentTime() { |
| 66 | + if (OneSignal.isForeground()) |
| 67 | + return; |
| 68 | + |
| 69 | + for(FocusTimeProcessorBase focusTimeProcessor : focusTimeProcessors) |
| 70 | + focusTimeProcessor.syncUnsentTimeFromSyncJob(); |
| 71 | + } |
| 72 | + |
| 73 | + private boolean giveProcessorsValidFocusTime(@NonNull OSSessionManager.SessionResult lastSessionResult, @NonNull FocusEventType focusType) { |
| 74 | + Long timeElapsed = getTimeFocusedElapsed(); |
| 75 | + if (timeElapsed == null) |
| 76 | + return false; |
| 77 | + |
| 78 | + for(FocusTimeProcessorBase focusTimeProcessor : focusTimeProcessors) |
| 79 | + focusTimeProcessor.addTime(timeElapsed, lastSessionResult.session, focusType); |
| 80 | + return true; |
| 81 | + } |
| 82 | + |
| 83 | + // Get time past since app was put into focus. |
| 84 | + // Will be null if time is invalid or 0 |
| 85 | + private @Nullable Long getTimeFocusedElapsed() { |
| 86 | + // timeFocusedAtMs is cleared when the app goes into the background so we don't have a focus time |
| 87 | + if (timeFocusedAtMs == null) |
| 88 | + return null; |
| 89 | + |
| 90 | + long timeElapsed = (long)(((SystemClock.elapsedRealtime() - timeFocusedAtMs) / 1_000d) + 0.5d); |
| 91 | + |
| 92 | + // Time is invalid if below 1 or over a day |
| 93 | + if (timeElapsed < 1 || timeElapsed > 86_400) |
| 94 | + return null; |
| 95 | + return timeElapsed; |
| 96 | + } |
| 97 | + |
| 98 | + private static class FocusTimeProcessorUnattributed extends FocusTimeProcessorBase { |
| 99 | + FocusTimeProcessorUnattributed() { |
| 100 | + MIN_ON_FOCUS_TIME_SEC = 60; |
| 101 | + PREF_KEY_FOR_UNSENT_TIME = OneSignalPrefs.PREFS_GT_UNSENT_ACTIVE_TIME; |
| 102 | + } |
| 103 | + |
| 104 | + protected boolean timeTypeApplies(@NonNull OSSessionManager.Session session) { |
| 105 | + return session.isUnattributed() || session.isDisabled(); |
| 106 | + } |
| 107 | + |
| 108 | + protected void sendTime(@NonNull FocusEventType focusType) { |
| 109 | + // We only need to send unattributed focus time when the app goes out of focus. |
| 110 | + if (focusType.equals(FocusEventType.END_SESSION)) |
| 111 | + return; |
| 112 | + |
| 113 | + syncUnsentTimeOnBackgroundEvent(); |
| 114 | + } |
| 115 | + } |
| 116 | + |
| 117 | + private static class FocusTimeProcessorAttributed extends FocusTimeProcessorBase { |
| 118 | + FocusTimeProcessorAttributed() { |
| 119 | + MIN_ON_FOCUS_TIME_SEC = 1; |
| 120 | + PREF_KEY_FOR_UNSENT_TIME = OneSignalPrefs.PREFS_OS_UNSENT_ATTRIBUTED_ACTIVE_TIME; |
| 121 | + } |
| 122 | + |
| 123 | + protected boolean timeTypeApplies(@NonNull OSSessionManager.Session session) { |
| 124 | + return session.isAttributed(); |
| 125 | + } |
| 126 | + |
| 127 | + protected void additionalFieldsToAddToOnFocusPayload(@NonNull JSONObject jsonBody) { |
| 128 | + OneSignal.getSessionManager().addSessionNotificationsIds(jsonBody); |
| 129 | + } |
| 130 | + |
| 131 | + protected void sendTime(@NonNull FocusEventType focusType) { |
| 132 | + if (focusType.equals(FocusEventType.END_SESSION)) |
| 133 | + syncOnFocusTime(); |
| 134 | + else |
| 135 | + OneSignalSyncServiceUtils.scheduleSyncTask(OneSignal.appContext); |
| 136 | + } |
| 137 | + } |
| 138 | + |
| 139 | + private static abstract class FocusTimeProcessorBase { |
| 140 | + // These values are set by child classes that inherit this base class |
| 141 | + protected long MIN_ON_FOCUS_TIME_SEC; |
| 142 | + protected @NonNull String PREF_KEY_FOR_UNSENT_TIME; |
| 143 | + |
| 144 | + protected abstract boolean timeTypeApplies(@NonNull OSSessionManager.Session session); |
| 145 | + protected abstract void sendTime(@NonNull FocusEventType focusType); |
| 146 | + |
| 147 | + @Nullable private Long unsentActiveTime = null; |
| 148 | + |
| 149 | + private long getUnsentActiveTime() { |
| 150 | + if (unsentActiveTime == null) { |
| 151 | + unsentActiveTime = OneSignalPrefs.getLong( |
| 152 | + OneSignalPrefs.PREFS_ONESIGNAL, |
| 153 | + PREF_KEY_FOR_UNSENT_TIME, |
| 154 | + 0 |
| 155 | + ); |
| 156 | + } |
| 157 | + OneSignal.Log(OneSignal.LOG_LEVEL.DEBUG, this.getClass().getSimpleName() + ":getUnsentActiveTime: " + unsentActiveTime); |
| 158 | + return unsentActiveTime; |
| 159 | + } |
| 160 | + |
| 161 | + private void saveUnsentActiveTime(long time) { |
| 162 | + unsentActiveTime = time; |
| 163 | + OneSignal.Log(OneSignal.LOG_LEVEL.DEBUG, this.getClass().getSimpleName() + ":saveUnsentActiveTime: " + unsentActiveTime); |
| 164 | + OneSignalPrefs.saveLong( |
| 165 | + OneSignalPrefs.PREFS_ONESIGNAL, |
| 166 | + PREF_KEY_FOR_UNSENT_TIME, |
| 167 | + time |
| 168 | + ); |
| 169 | + } |
| 170 | + |
| 171 | + private void addTime(long time, @NonNull OSSessionManager.Session session, @NonNull FocusEventType focusType) { |
| 172 | + if (!timeTypeApplies(session)) |
| 173 | + return; |
| 174 | + |
| 175 | + long totalTime = getUnsentActiveTime() + time; |
| 176 | + saveUnsentActiveTime(totalTime); |
| 177 | + sendUnsentTimeNow(focusType); |
| 178 | + } |
| 179 | + |
| 180 | + private void sendUnsentTimeNow(FocusEventType focusType) { |
| 181 | + if (!OneSignal.hasUserId()) |
| 182 | + return; |
| 183 | + |
| 184 | + sendTime(focusType); |
| 185 | + } |
| 186 | + |
| 187 | + private boolean hasMinSyncTime() { |
| 188 | + return getUnsentActiveTime() >= MIN_ON_FOCUS_TIME_SEC; |
| 189 | + } |
| 190 | + |
| 191 | + protected void syncUnsentTimeOnBackgroundEvent() { |
| 192 | + if (!hasMinSyncTime()) |
| 193 | + return; |
| 194 | + // Schedule this sync in case app is killed before completing |
| 195 | + OneSignalSyncServiceUtils.scheduleSyncTask(OneSignal.appContext); |
| 196 | + syncOnFocusTime(); |
| 197 | + } |
| 198 | + |
| 199 | + private void syncUnsentTimeFromSyncJob() { |
| 200 | + if (hasMinSyncTime()) |
| 201 | + syncOnFocusTime(); |
| 202 | + } |
| 203 | + |
| 204 | + @NonNull private final AtomicBoolean runningOnFocusTime = new AtomicBoolean(); |
| 205 | + @WorkerThread |
| 206 | + protected void syncOnFocusTime() { |
| 207 | + if (runningOnFocusTime.get()) |
| 208 | + return; |
| 209 | + |
| 210 | + synchronized (runningOnFocusTime) { |
| 211 | + runningOnFocusTime.set(true); |
| 212 | + if (hasMinSyncTime()) |
| 213 | + sendOnFocus(getUnsentActiveTime()); |
| 214 | + runningOnFocusTime.set(false); |
| 215 | + } |
| 216 | + } |
| 217 | + |
| 218 | + private void sendOnFocusToPlayer(@NonNull String userId, @NonNull JSONObject jsonBody) { |
| 219 | + OneSignalRestClient.ResponseHandler responseHandler = new OneSignalRestClient.ResponseHandler() { |
| 220 | + @Override |
| 221 | + void onFailure(int statusCode, String response, Throwable throwable) { |
| 222 | + OneSignal.logHttpError("sending on_focus Failed", statusCode, throwable, response); |
| 223 | + } |
| 224 | + |
| 225 | + @Override |
| 226 | + void onSuccess(String response) { |
| 227 | + // TODO: PRE-EXISTING: This time is shared between the email + push player and |
| 228 | + // is cleared no matter which one is successful. |
| 229 | + // TODO: PRE-EXISTING: This could be clearing time more then was persisted while the network call was in flight |
| 230 | + saveUnsentActiveTime(0); |
| 231 | + } |
| 232 | + }; |
| 233 | + String url = "players/" + userId + "/on_focus"; |
| 234 | + OneSignalRestClient.postSync(url, jsonBody, responseHandler); |
| 235 | + } |
| 236 | + |
| 237 | + // Override Optional |
| 238 | + protected void additionalFieldsToAddToOnFocusPayload(@NonNull JSONObject jsonBody) { } |
| 239 | + |
| 240 | + private @NonNull JSONObject generateOnFocusPayload(long totalTimeActive) throws JSONException { |
| 241 | + JSONObject jsonBody = new JSONObject() |
| 242 | + .put("app_id", OneSignal.appId) |
| 243 | + .put("type", 1) // Always 1, where this type means do NOT increase session_count |
| 244 | + .put("state", "ping") // Always ping, other types are not used |
| 245 | + .put("active_time", totalTimeActive) |
| 246 | + .put("device_type", new OSUtils().getDeviceType()); |
| 247 | + OneSignal.addNetType(jsonBody); |
| 248 | + return jsonBody; |
| 249 | + } |
| 250 | + |
| 251 | + private void sendOnFocus(long totalTimeActive) { |
| 252 | + try { |
| 253 | + JSONObject jsonBody = generateOnFocusPayload(totalTimeActive); |
| 254 | + additionalFieldsToAddToOnFocusPayload(jsonBody); |
| 255 | + sendOnFocusToPlayer(OneSignal.getUserId(), jsonBody); |
| 256 | + |
| 257 | + // For email we omit additionalFieldsToAddToOnFocusPayload as we don't want to add |
| 258 | + // outcome fields which would double report the session time |
| 259 | + if (OneSignal.hasEmailId()) |
| 260 | + sendOnFocusToPlayer(OneSignal.getEmailId(), generateOnFocusPayload(totalTimeActive)); |
| 261 | + } |
| 262 | + catch (JSONException t) { |
| 263 | + OneSignal.Log(OneSignal.LOG_LEVEL.ERROR, "Generating on_focus:JSON Failed.", t); |
| 264 | + } |
| 265 | + } |
| 266 | + } |
| 267 | +} |
0 commit comments