1717package com.google.firebase.sessions
1818
1919import android.content.Context
20+ import android.os.Build
2021import android.util.Log
2122import androidx.datastore.core.DataMigration
2223import androidx.datastore.core.DataStore
@@ -48,6 +49,8 @@ import dagger.Component
4849import dagger.Module
4950import dagger.Provides
5051import java.io.File
52+ import java.io.IOException
53+ import java.nio.file.Files
5154import javax.inject.Qualifier
5255import javax.inject.Singleton
5356import kotlin.coroutines.CoroutineContext
@@ -146,7 +149,11 @@ internal interface FirebaseSessionsComponent {
146149 SessionConfigsSerializer .defaultValue
147150 },
148151 scope = CoroutineScope (blockingDispatcher),
149- produceFile = { appContext.dataStoreFile(" aqs/sessionConfigsDataStore.data" ) },
152+ produceFile = {
153+ prepDataStoreFile(
154+ appContext.dataStoreFile(" firebaseSessions/sessionConfigsDataStore.data" )
155+ )
156+ },
150157 )
151158
152159 @Provides
@@ -164,7 +171,9 @@ internal interface FirebaseSessionsComponent {
164171 sessionDataSerializer.defaultValue
165172 },
166173 scope = CoroutineScope (blockingDispatcher),
167- produceFile = { appContext.dataStoreFile(" aqs/sessionDataStore.data" ) },
174+ produceFile = {
175+ prepDataStoreFile(appContext.dataStoreFile(" firebaseSessions/sessionDataStore.data" ))
176+ },
168177 )
169178
170179 private fun <T > createDataStore (
@@ -197,6 +206,45 @@ internal interface FirebaseSessionsComponent {
197206 } catch (_: SecurityException ) {
198207 false
199208 }
209+
210+ /* *
211+ * Prepares the DataStore file by ensuring its parent directory exists. Throws [IOException]
212+ * if the directory could not be created, or if a conflicting file could not be removed.
213+ */
214+ private fun prepDataStoreFile (dataStoreFile : File ): File {
215+ val parentDir = dataStoreFile.parentFile ? : return dataStoreFile
216+
217+ // Check if something exists at the path, but isn't a directory
218+ if (parentDir.exists() && ! parentDir.isDirectory) {
219+ // Only delete it if it's the specific file we know we can safely remove
220+ if (parentDir.name == " firebaseSessions" ) {
221+ if (! parentDir.delete()) {
222+ throw IOException (" Failed to delete conflicting file: $parentDir " )
223+ }
224+ }
225+ }
226+
227+ if (parentDir.isDirectory) {
228+ return dataStoreFile
229+ }
230+
231+ if (Build .VERSION .SDK_INT >= Build .VERSION_CODES .O ) {
232+ try {
233+ Files .createDirectories(parentDir.toPath())
234+ } catch (ex: Exception ) {
235+ throw IOException (" Failed to create directory: $parentDir " , ex)
236+ }
237+ } else {
238+ if (! parentDir.mkdirs()) {
239+ // It's possible another thread created it in the meantime, so we double-check
240+ if (! parentDir.isDirectory) {
241+ throw IOException (" Failed to create directory: $parentDir " )
242+ }
243+ }
244+ }
245+
246+ return dataStoreFile
247+ }
200248 }
201249 }
202250}
0 commit comments