blob: 222bb0a58fab775f9b98d66774dafde60cf08e36 [file] [log] [blame]
Zhomart Mukhamejanov0dd5a832018-04-23 11:38:54 -07001/*
2 * Copyright (C) 2018 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 * http://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
17package com.example.android.systemupdatersample.services;
18
Zhomart Mukhamejanov46a51ac2018-05-09 09:53:45 -070019import static com.example.android.systemupdatersample.util.PackageFiles.COMPATIBILITY_ZIP_FILE_NAME;
Zhomart Mukhamejanov0dd5a832018-04-23 11:38:54 -070020import static com.example.android.systemupdatersample.util.PackageFiles.OTA_PACKAGE_DIR;
21import static com.example.android.systemupdatersample.util.PackageFiles.PAYLOAD_BINARY_FILE_NAME;
22import static com.example.android.systemupdatersample.util.PackageFiles.PAYLOAD_PROPERTIES_FILE_NAME;
23
24import android.app.IntentService;
25import android.content.Context;
26import android.content.Intent;
27import android.os.Bundle;
28import android.os.Handler;
Zhomart Mukhamejanov46a51ac2018-05-09 09:53:45 -070029import android.os.RecoverySystem;
Zhomart Mukhamejanov0dd5a832018-04-23 11:38:54 -070030import android.os.ResultReceiver;
31import android.util.Log;
32
33import com.example.android.systemupdatersample.PayloadSpec;
34import com.example.android.systemupdatersample.UpdateConfig;
35import com.example.android.systemupdatersample.util.FileDownloader;
36import com.example.android.systemupdatersample.util.PackageFiles;
37import com.example.android.systemupdatersample.util.PayloadSpecs;
38import com.example.android.systemupdatersample.util.UpdateConfigs;
39import com.google.common.collect.ImmutableSet;
40
Zhomart Mukhamejanov46a51ac2018-05-09 09:53:45 -070041import java.io.File;
Zhomart Mukhamejanov0dd5a832018-04-23 11:38:54 -070042import java.io.IOException;
Zhomart Mukhamejanov46a51ac2018-05-09 09:53:45 -070043import java.nio.file.Files;
Zhomart Mukhamejanov0dd5a832018-04-23 11:38:54 -070044import java.nio.file.Paths;
45import java.util.Optional;
46
47/**
48 * This IntentService will download/extract the necessary files from the package zip
49 * without downloading the whole package. And it constructs {@link PayloadSpec}.
50 * All this work required to install streaming A/B updates.
51 *
52 * PrepareStreamingService runs on it's own thread. It will notify activity
53 * using interface {@link UpdateResultCallback} when update is ready to install.
54 */
55public class PrepareStreamingService extends IntentService {
56
57 /**
58 * UpdateResultCallback result codes.
59 */
60 public static final int RESULT_CODE_SUCCESS = 0;
61 public static final int RESULT_CODE_ERROR = 1;
62
63 /**
64 * This interface is used to send results from {@link PrepareStreamingService} to
65 * {@code MainActivity}.
66 */
67 public interface UpdateResultCallback {
68
69 /**
70 * Invoked when files are downloaded and payload spec is constructed.
71 *
72 * @param resultCode result code, values are defined in {@link PrepareStreamingService}
73 * @param payloadSpec prepared payload spec for streaming update
74 */
75 void onReceiveResult(int resultCode, PayloadSpec payloadSpec);
76 }
77
78 /**
79 * Starts PrepareStreamingService.
80 *
81 * @param context application context
82 * @param config update config
83 * @param resultCallback callback that will be called when the update is ready to be installed
84 */
85 public static void startService(Context context,
86 UpdateConfig config,
87 UpdateResultCallback resultCallback) {
88 Log.d(TAG, "Starting PrepareStreamingService");
89 ResultReceiver receiver = new CallbackResultReceiver(new Handler(), resultCallback);
90 Intent intent = new Intent(context, PrepareStreamingService.class);
91 intent.putExtra(EXTRA_PARAM_CONFIG, config);
92 intent.putExtra(EXTRA_PARAM_RESULT_RECEIVER, receiver);
93 context.startService(intent);
94 }
95
96 public PrepareStreamingService() {
97 super(TAG);
98 }
99
100 private static final String TAG = "PrepareStreamingService";
101
102 /**
103 * Extra params that will be sent from Activity to IntentService.
104 */
105 private static final String EXTRA_PARAM_CONFIG = "config";
106 private static final String EXTRA_PARAM_RESULT_RECEIVER = "result-receiver";
107
108 /**
109 * The files that should be downloaded before streaming.
110 */
111 private static final ImmutableSet<String> PRE_STREAMING_FILES_SET =
112 ImmutableSet.of(
113 PackageFiles.CARE_MAP_FILE_NAME,
114 PackageFiles.COMPATIBILITY_ZIP_FILE_NAME,
115 PackageFiles.METADATA_FILE_NAME,
116 PackageFiles.PAYLOAD_PROPERTIES_FILE_NAME
117 );
118
119 @Override
120 protected void onHandleIntent(Intent intent) {
121 Log.d(TAG, "On handle intent is called");
122 UpdateConfig config = intent.getParcelableExtra(EXTRA_PARAM_CONFIG);
123 ResultReceiver resultReceiver = intent.getParcelableExtra(EXTRA_PARAM_RESULT_RECEIVER);
124
125 try {
Zhomart Mukhamejanov46a51ac2018-05-09 09:53:45 -0700126 PayloadSpec spec = execute(config);
127 resultReceiver.send(RESULT_CODE_SUCCESS, CallbackResultReceiver.createBundle(spec));
128 } catch (Exception e) {
129 Log.e(TAG, "Failed to prepare streaming update", e);
Zhomart Mukhamejanov0dd5a832018-04-23 11:38:54 -0700130 resultReceiver.send(RESULT_CODE_ERROR, null);
Zhomart Mukhamejanov0dd5a832018-04-23 11:38:54 -0700131 }
Zhomart Mukhamejanov46a51ac2018-05-09 09:53:45 -0700132 }
133
134 /**
135 * 1. Downloads files for streaming updates.
136 * 2. Makes sure required files are present.
137 * 3. Checks OTA package compatibility with the device.
138 * 4. Constructs {@link PayloadSpec} for streaming update.
139 */
140 private static PayloadSpec execute(UpdateConfig config)
141 throws IOException, PreparationFailedException {
142
143 downloadPreStreamingFiles(config, OTA_PACKAGE_DIR);
Zhomart Mukhamejanov0dd5a832018-04-23 11:38:54 -0700144
145 Optional<UpdateConfig.PackageFile> payloadBinary =
146 UpdateConfigs.getPropertyFile(PAYLOAD_BINARY_FILE_NAME, config);
147
148 if (!payloadBinary.isPresent()) {
Zhomart Mukhamejanov46a51ac2018-05-09 09:53:45 -0700149 throw new PreparationFailedException(
150 "Failed to find " + PAYLOAD_BINARY_FILE_NAME + " in config");
Zhomart Mukhamejanov0dd5a832018-04-23 11:38:54 -0700151 }
152
Zhomart Mukhamejanov46a51ac2018-05-09 09:53:45 -0700153 if (!UpdateConfigs.getPropertyFile(PAYLOAD_PROPERTIES_FILE_NAME, config).isPresent()
154 || !Paths.get(OTA_PACKAGE_DIR, PAYLOAD_PROPERTIES_FILE_NAME).toFile().exists()) {
155 throw new IOException(PAYLOAD_PROPERTIES_FILE_NAME + " not found");
Zhomart Mukhamejanov0dd5a832018-04-23 11:38:54 -0700156 }
157
Zhomart Mukhamejanov46a51ac2018-05-09 09:53:45 -0700158 File compatibilityFile = Paths.get(OTA_PACKAGE_DIR, COMPATIBILITY_ZIP_FILE_NAME).toFile();
159 if (compatibilityFile.isFile()) {
160 Log.i(TAG, "Verifying OTA package for compatibility with the device");
161 if (!verifyPackageCompatibility(compatibilityFile)) {
162 throw new PreparationFailedException(
163 "OTA package is not compatible with this device");
164 }
Zhomart Mukhamejanov0dd5a832018-04-23 11:38:54 -0700165 }
166
Zhomart Mukhamejanov46a51ac2018-05-09 09:53:45 -0700167 return PayloadSpecs.forStreaming(config.getUrl(),
168 payloadBinary.get().getOffset(),
169 payloadBinary.get().getSize(),
170 Paths.get(OTA_PACKAGE_DIR, PAYLOAD_PROPERTIES_FILE_NAME).toFile());
Zhomart Mukhamejanov0dd5a832018-04-23 11:38:54 -0700171 }
172
173 /**
174 * Downloads files defined in {@link UpdateConfig#getStreamingMetadata()}
175 * and exists in {@code PRE_STREAMING_FILES_SET}, and put them
176 * in directory {@code dir}.
177 * @throws IOException when can't download a file
178 */
179 private static void downloadPreStreamingFiles(UpdateConfig config, String dir)
180 throws IOException {
Zhomart Mukhamejanov46a51ac2018-05-09 09:53:45 -0700181 Log.d(TAG, "Deleting existing files from " + dir);
182 for (String file : PRE_STREAMING_FILES_SET) {
183 Files.deleteIfExists(Paths.get(OTA_PACKAGE_DIR, file));
184 }
Zhomart Mukhamejanov0dd5a832018-04-23 11:38:54 -0700185 Log.d(TAG, "Downloading files to " + dir);
186 for (UpdateConfig.PackageFile file : config.getStreamingMetadata().getPropertyFiles()) {
187 if (PRE_STREAMING_FILES_SET.contains(file.getFilename())) {
188 Log.d(TAG, "Downloading file " + file.getFilename());
189 FileDownloader downloader = new FileDownloader(
190 config.getUrl(),
191 file.getOffset(),
192 file.getSize(),
193 Paths.get(dir, file.getFilename()).toFile());
194 downloader.download();
195 }
196 }
197 }
198
199 /**
Zhomart Mukhamejanov46a51ac2018-05-09 09:53:45 -0700200 * @param file physical location of {@link PackageFiles#COMPATIBILITY_ZIP_FILE_NAME}
201 * @return true if OTA package is compatible with this device
202 */
203 private static boolean verifyPackageCompatibility(File file) {
204 try {
205 return RecoverySystem.verifyPackageCompatibility(file);
206 } catch (IOException e) {
207 Log.e(TAG, "Failed to verify package compatibility", e);
208 return false;
209 }
210 }
211
212 /**
Zhomart Mukhamejanov0dd5a832018-04-23 11:38:54 -0700213 * Used by {@link PrepareStreamingService} to pass {@link PayloadSpec}
214 * to {@link UpdateResultCallback#onReceiveResult}.
215 */
216 private static class CallbackResultReceiver extends ResultReceiver {
217
218 static Bundle createBundle(PayloadSpec payloadSpec) {
219 Bundle b = new Bundle();
220 b.putSerializable(BUNDLE_PARAM_PAYLOAD_SPEC, payloadSpec);
221 return b;
222 }
223
224 private static final String BUNDLE_PARAM_PAYLOAD_SPEC = "payload-spec";
225
226 private UpdateResultCallback mUpdateResultCallback;
227
228 CallbackResultReceiver(Handler handler, UpdateResultCallback updateResultCallback) {
229 super(handler);
230 this.mUpdateResultCallback = updateResultCallback;
231 }
232
233 @Override
234 protected void onReceiveResult(int resultCode, Bundle resultData) {
235 PayloadSpec payloadSpec = null;
236 if (resultCode == RESULT_CODE_SUCCESS) {
237 payloadSpec = (PayloadSpec) resultData.getSerializable(BUNDLE_PARAM_PAYLOAD_SPEC);
238 }
239 mUpdateResultCallback.onReceiveResult(resultCode, payloadSpec);
240 }
241 }
242
Zhomart Mukhamejanov46a51ac2018-05-09 09:53:45 -0700243 private static class PreparationFailedException extends Exception {
244 PreparationFailedException(String message) {
245 super(message);
246 }
247 }
248
Zhomart Mukhamejanov0dd5a832018-04-23 11:38:54 -0700249}