17
17
package com.google.firebase.sessions
18
18
19
19
import android.content.Context
20
+ import android.os.Build
20
21
import android.util.Log
21
22
import androidx.datastore.core.DataMigration
22
23
import androidx.datastore.core.DataStore
@@ -48,6 +49,8 @@ import dagger.Component
48
49
import dagger.Module
49
50
import dagger.Provides
50
51
import java.io.File
52
+ import java.io.IOException
53
+ import java.nio.file.Files
51
54
import javax.inject.Qualifier
52
55
import javax.inject.Singleton
53
56
import kotlin.coroutines.CoroutineContext
@@ -146,7 +149,11 @@ internal interface FirebaseSessionsComponent {
146
149
SessionConfigsSerializer .defaultValue
147
150
},
148
151
scope = CoroutineScope (blockingDispatcher),
149
- produceFile = { appContext.dataStoreFile(" aqs/sessionConfigsDataStore.data" ) },
152
+ produceFile = {
153
+ appContext.dataStoreFile(" firebaseSessions/sessionConfigsDataStore.data" ).also {
154
+ prepDataStoreFile(it)
155
+ }
156
+ },
150
157
)
151
158
152
159
@Provides
@@ -164,7 +171,11 @@ internal interface FirebaseSessionsComponent {
164
171
sessionDataSerializer.defaultValue
165
172
},
166
173
scope = CoroutineScope (blockingDispatcher),
167
- produceFile = { appContext.dataStoreFile(" aqs/sessionDataStore.data" ) },
174
+ produceFile = {
175
+ appContext.dataStoreFile(" firebaseSessions/sessionDataStore.data" ).also {
176
+ prepDataStoreFile(it)
177
+ }
178
+ },
168
179
)
169
180
170
181
private fun <T > createDataStore (
@@ -197,6 +208,43 @@ internal interface FirebaseSessionsComponent {
197
208
} catch (_: SecurityException ) {
198
209
false
199
210
}
211
+
212
+ /* *
213
+ * Prepares the DataStore file by ensuring its parent directory exists. Throws [IOException]
214
+ * if the directory could not be created, or if a conflicting file could not be removed.
215
+ */
216
+ private fun prepDataStoreFile (dataStoreFile : File ) {
217
+ val parentDir = dataStoreFile.parentFile ? : return
218
+
219
+ // Check if something exists at the path, but isn't a directory
220
+ if (parentDir.exists() && ! parentDir.isDirectory) {
221
+ // Only delete it if it's the specific file we know we can safely remove
222
+ if (parentDir.name == " firebaseSessions" ) {
223
+ if (! parentDir.delete()) {
224
+ throw IOException (" Failed to delete conflicting file: $parentDir " )
225
+ }
226
+ }
227
+ }
228
+
229
+ if (parentDir.isDirectory) {
230
+ return
231
+ }
232
+
233
+ if (Build .VERSION .SDK_INT >= Build .VERSION_CODES .O ) {
234
+ try {
235
+ Files .createDirectories(parentDir.toPath())
236
+ } catch (ex: Exception ) {
237
+ throw IOException (" Failed to create directory: $parentDir " , ex)
238
+ }
239
+ } else {
240
+ if (! parentDir.mkdirs()) {
241
+ // It's possible another thread created it in the meantime, so we double-check
242
+ if (! parentDir.isDirectory) {
243
+ throw IOException (" Failed to create directory: $parentDir " )
244
+ }
245
+ }
246
+ }
247
+ }
200
248
}
201
249
}
202
250
}
0 commit comments