1 /*
2  * Copyright 2024 The Android Open Source Project
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  *      https://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16 package com.android.devicediagnostics.trusted
17 
18 import android.app.Activity
19 import android.content.Intent
20 import android.os.Parcel
21 import android.os.Parcelable
22 import com.android.devicediagnostics.Protos.DeviceReport
23 
24 private const val TRUSTED_STATE_KEY = "trusted_state"
25 
26 class TrustedState(
27     var challenge: ByteArray,
28     var report: DeviceReport,
29 ) : Parcelable {
30     constructor(
31         parcel: Parcel
32     ) : this(parcel.createByteArray()!!, DeviceReport.parseFrom(parcel.createByteArray()!!)) {}
33 
writeToParcelnull34     override fun writeToParcel(parcel: Parcel, flags: Int) {
35         parcel.writeByteArray(challenge)
36         parcel.writeByteArray(report.toByteArray())
37     }
38 
describeContentsnull39     override fun describeContents(): Int {
40         return 0
41     }
42 
43     companion object CREATOR : Parcelable.Creator<TrustedState> {
createFromParcelnull44         override fun createFromParcel(parcel: Parcel): TrustedState {
45             return TrustedState(parcel)
46         }
47 
newArraynull48         override fun newArray(size: Int): Array<TrustedState?> {
49             return arrayOfNulls(size)
50         }
51 
fromActivitynull52         fun fromActivity(activity: Activity): TrustedState? {
53             return activity.intent.getParcelableExtra(TRUSTED_STATE_KEY, TrustedState::class.java)
54         }
55     }
56 }
57 
launchTrustedActivitynull58 fun launchTrustedActivity(from: Activity, className: String, state: TrustedState? = null) {
59     val intent = Intent()
60     intent.setClassName(from, className)
61 
62     var ts = state
63     if (ts == null) ts = TrustedState.fromActivity(from)
64 
65     if (ts != null) intent.putExtra(TRUSTED_STATE_KEY, ts)
66 
67     from.startActivity(intent)
68 }
69