ProfileDownloadFragment.kt 9.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266
  1. package im.angry.openeuicc.ui
  2. import android.annotation.SuppressLint
  3. import android.app.Dialog
  4. import android.content.DialogInterface
  5. import android.graphics.BitmapFactory
  6. import android.os.Bundle
  7. import android.text.Editable
  8. import android.util.Log
  9. import android.view.*
  10. import android.widget.ProgressBar
  11. import android.widget.TextView
  12. import android.widget.Toast
  13. import androidx.activity.result.contract.ActivityResultContracts
  14. import androidx.appcompat.widget.Toolbar
  15. import androidx.lifecycle.lifecycleScope
  16. import com.google.android.material.textfield.TextInputLayout
  17. import com.journeyapps.barcodescanner.ScanContract
  18. import com.journeyapps.barcodescanner.ScanOptions
  19. import im.angry.openeuicc.common.R
  20. import im.angry.openeuicc.util.*
  21. import kotlinx.coroutines.Dispatchers
  22. import kotlinx.coroutines.flow.first
  23. import kotlinx.coroutines.launch
  24. import kotlinx.coroutines.withContext
  25. import net.typeblog.lpac_jni.ProfileDownloadCallback
  26. import kotlin.Exception
  27. class ProfileDownloadFragment : BaseMaterialDialogFragment(),
  28. Toolbar.OnMenuItemClickListener, EuiccChannelFragmentMarker {
  29. companion object {
  30. const val TAG = "ProfileDownloadFragment"
  31. fun newInstance(slotId: Int, portId: Int, finishWhenDone: Boolean = false): ProfileDownloadFragment =
  32. newInstanceEuicc(ProfileDownloadFragment::class.java, slotId, portId) {
  33. putBoolean("finishWhenDone", finishWhenDone)
  34. }
  35. }
  36. private lateinit var toolbar: Toolbar
  37. private lateinit var profileDownloadServer: TextInputLayout
  38. private lateinit var profileDownloadCode: TextInputLayout
  39. private lateinit var profileDownloadConfirmationCode: TextInputLayout
  40. private lateinit var profileDownloadIMEI: TextInputLayout
  41. private lateinit var profileDownloadFreeSpace: TextView
  42. private lateinit var progress: ProgressBar
  43. private var freeNvram: Int = -1
  44. private var downloading = false
  45. private val finishWhenDone by lazy {
  46. requireArguments().getBoolean("finishWhenDone", false)
  47. }
  48. private val barcodeScannerLauncher = registerForActivityResult(ScanContract()) { result ->
  49. result.contents?.let { content ->
  50. Log.d(TAG, content)
  51. onScanResult(content)
  52. }
  53. }
  54. private val gallerySelectorLauncher = registerForActivityResult(ActivityResultContracts.GetContent()) { result ->
  55. if (result == null) return@registerForActivityResult
  56. lifecycleScope.launch(Dispatchers.IO) {
  57. runCatching {
  58. requireContext().contentResolver.openInputStream(result)?.let { input ->
  59. val bmp = BitmapFactory.decodeStream(input)
  60. input.close()
  61. decodeQrFromBitmap(bmp)?.let {
  62. withContext(Dispatchers.Main) {
  63. onScanResult(it)
  64. }
  65. }
  66. bmp.recycle()
  67. }
  68. }
  69. }
  70. }
  71. private fun onScanResult(result: String) {
  72. val components = result.split("$")
  73. if (components.size < 3 || components[0] != "LPA:1") return
  74. profileDownloadServer.editText?.setText(components[1])
  75. profileDownloadCode.editText?.setText(components[2])
  76. }
  77. override fun onCreateView(
  78. inflater: LayoutInflater,
  79. container: ViewGroup?,
  80. savedInstanceState: Bundle?
  81. ): View {
  82. val view = inflater.inflate(R.layout.fragment_profile_download, container, false)
  83. toolbar = view.requireViewById(R.id.toolbar)
  84. profileDownloadServer = view.requireViewById(R.id.profile_download_server)
  85. profileDownloadCode = view.requireViewById(R.id.profile_download_code)
  86. profileDownloadConfirmationCode = view.requireViewById(R.id.profile_download_confirmation_code)
  87. profileDownloadIMEI = view.requireViewById(R.id.profile_download_imei)
  88. profileDownloadFreeSpace = view.requireViewById(R.id.profile_download_free_space)
  89. progress = view.requireViewById(R.id.progress)
  90. toolbar.inflateMenu(R.menu.fragment_profile_download)
  91. return view
  92. }
  93. override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
  94. super.onViewCreated(view, savedInstanceState)
  95. toolbar.apply {
  96. setTitle(R.string.profile_download)
  97. setNavigationOnClickListener {
  98. if (!downloading) {
  99. dismiss()
  100. }
  101. }
  102. setOnMenuItemClickListener(this@ProfileDownloadFragment)
  103. }
  104. }
  105. override fun onMenuItemClick(item: MenuItem): Boolean = downloading ||
  106. when (item.itemId) {
  107. R.id.scan -> {
  108. barcodeScannerLauncher.launch(ScanOptions().apply {
  109. setDesiredBarcodeFormats(ScanOptions.QR_CODE)
  110. setOrientationLocked(false)
  111. })
  112. true
  113. }
  114. R.id.scan_from_gallery -> {
  115. gallerySelectorLauncher.launch("image/*")
  116. true
  117. }
  118. R.id.ok -> {
  119. startDownloadProfile()
  120. true
  121. }
  122. else -> false
  123. }
  124. override fun onResume() {
  125. super.onResume()
  126. setWidthPercent(95)
  127. }
  128. @SuppressLint("MissingPermission")
  129. override fun onStart() {
  130. super.onStart()
  131. profileDownloadIMEI.editText!!.text = Editable.Factory.getInstance().newEditable(
  132. try {
  133. telephonyManager.getImei(channel.logicalSlotId) ?: ""
  134. } catch (e: Exception) {
  135. ""
  136. }
  137. )
  138. lifecycleScope.launch(Dispatchers.IO) {
  139. // Fetch remaining NVRAM
  140. val str = channel.lpa.euiccInfo2?.freeNvram?.also {
  141. freeNvram = it
  142. }?.let { formatFreeSpace(it) }
  143. withContext(Dispatchers.Main) {
  144. profileDownloadFreeSpace.text = getString(R.string.profile_download_free_space,
  145. str ?: getText(R.string.unknown))
  146. }
  147. }
  148. }
  149. override fun onCreateDialog(savedInstanceState: Bundle?): Dialog {
  150. return super.onCreateDialog(savedInstanceState).also {
  151. it.setCanceledOnTouchOutside(false)
  152. }
  153. }
  154. private fun startDownloadProfile() {
  155. val server = profileDownloadServer.editText!!.let {
  156. it.text.toString().trim().apply {
  157. if (isEmpty()) {
  158. it.requestFocus()
  159. return@startDownloadProfile
  160. }
  161. }
  162. }
  163. val code = profileDownloadCode.editText!!.text.toString().trim()
  164. .ifBlank { null }
  165. val confirmationCode = profileDownloadConfirmationCode.editText!!.text.toString().trim()
  166. .ifBlank { null }
  167. val imei = profileDownloadIMEI.editText!!.text.toString().trim()
  168. .ifBlank { null }
  169. downloading = true
  170. profileDownloadServer.editText!!.isEnabled = false
  171. profileDownloadCode.editText!!.isEnabled = false
  172. profileDownloadConfirmationCode.editText!!.isEnabled = false
  173. profileDownloadIMEI.editText!!.isEnabled = false
  174. progress.isIndeterminate = true
  175. progress.visibility = View.VISIBLE
  176. lifecycleScope.launch {
  177. try {
  178. doDownloadProfile(server, code, confirmationCode, imei)
  179. } catch (e: Exception) {
  180. Log.d(TAG, "Error downloading profile")
  181. Log.d(TAG, Log.getStackTraceString(e))
  182. Toast.makeText(context, R.string.profile_download_failed, Toast.LENGTH_LONG).show()
  183. } finally {
  184. if (parentFragment is EuiccProfilesChangedListener) {
  185. (parentFragment as EuiccProfilesChangedListener).onEuiccProfilesChanged()
  186. }
  187. dismiss()
  188. }
  189. }
  190. }
  191. private suspend fun doDownloadProfile(
  192. server: String,
  193. code: String?,
  194. confirmationCode: String?,
  195. imei: String?
  196. ) = beginTrackedOperation {
  197. val res = channel.lpa.downloadProfile(
  198. server,
  199. code,
  200. imei,
  201. confirmationCode,
  202. object : ProfileDownloadCallback {
  203. override fun onStateUpdate(state: ProfileDownloadCallback.DownloadState) {
  204. lifecycleScope.launch(Dispatchers.Main) {
  205. progress.isIndeterminate = false
  206. progress.progress = state.progress
  207. }
  208. }
  209. })
  210. if (!res) {
  211. // TODO: Provide more details on the error
  212. throw RuntimeException("Failed to download profile; this is typically caused by another error happened before.")
  213. }
  214. // If we get here, we are successful
  215. // This function is wrapped in beginTrackedOperation, so by returning the settings value,
  216. // We only send notifications if the user allowed us to
  217. preferenceRepository.notificationDownloadFlow.first()
  218. }
  219. override fun onDismiss(dialog: DialogInterface) {
  220. super.onDismiss(dialog)
  221. if (finishWhenDone) {
  222. activity?.finish()
  223. }
  224. }
  225. override fun onCancel(dialog: DialogInterface) {
  226. super.onCancel(dialog)
  227. if (finishWhenDone) {
  228. activity?.finish()
  229. }
  230. }
  231. }