<lambda>null1 package expo.modules.devlauncher.helpers
2 
3 import android.content.Context
4 import android.util.Log
5 import java.io.BufferedReader
6 import java.io.File
7 import java.io.FileReader
8 import java.io.FileWriter
9 import java.lang.Exception
10 import java.util.*
11 
12 class DevLauncherInstallationIDHelper {
13   private var installationID: String? = null
14 
15   fun getOrCreateInstallationID(context: Context): String {
16     val savedID = getInstallationID(context)
17     if (savedID != null) {
18       return savedID
19     }
20 
21     val newID = UUID.randomUUID().toString()
22     setInstallationID(newID, context)
23     return newID
24   }
25 
26   private fun getInstallationID(context: Context): String? {
27     if (installationID != null) {
28       return installationID
29     }
30 
31     val installationIDFile = getInstallationIDFile(context)
32     try {
33       if (installationIDFile.exists()) {
34         FileReader(installationIDFile).use { fileReader ->
35           BufferedReader(fileReader).use { bufferedReader ->
36             installationID = bufferedReader.readLine()
37           }
38         }
39       }
40     } catch (e: Exception) {
41       Log.e(TAG, "Failed to read stored installation ID", e)
42     }
43 
44     // return either persisted value or nil
45     return installationID
46   }
47 
48   private fun setInstallationID(newID: String, context: Context) {
49     // store in memory, in case there's a problem writing to persistent storage
50     // then at least subsequent calls during this session will return the same value
51     installationID = newID
52 
53     val installationIDFile = getInstallationIDFile(context)
54     try {
55       FileWriter(installationIDFile).use { it.write(installationID) }
56     } catch (e: Exception) {
57       Log.e(TAG, "Failed to write or set resource values to installation ID file", e)
58     }
59   }
60 
61   internal fun getInstallationIDFile(context: Context): File {
62     return File(context.noBackupFilesDir, INSTALLATION_ID_FILENAME)
63   }
64 
65   companion object {
66     private val TAG = DevLauncherInstallationIDHelper::class.java.simpleName
67     internal const val INSTALLATION_ID_FILENAME = "expo-dev-launcher-installation-id.txt"
68   }
69 }
70