blob: ad48a70c40754dc40c7b4942e2aad34cc977b522 [file] [log] [blame]
Steve McKay14e827a2016-01-06 18:32:13 -08001/*
2 * Copyright (C) 2016 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.android.documentsui.services;
18
19import static android.os.SystemClock.elapsedRealtime;
Steve McKayecbf3c52016-01-13 17:17:39 -080020import static android.provider.DocumentsContract.buildChildDocumentsUri;
21import static android.provider.DocumentsContract.buildDocumentUri;
22import static android.provider.DocumentsContract.getDocumentId;
23import static android.provider.DocumentsContract.isChildDocument;
Tomasz Mikolajewski748ea8c2016-01-22 16:22:51 +090024import static com.android.documentsui.OperationDialogFragment.DIALOG_TYPE_CONVERTED;
Steve McKay14e827a2016-01-06 18:32:13 -080025import static com.android.documentsui.Shared.DEBUG;
26import static com.android.documentsui.model.DocumentInfo.getCursorLong;
27import static com.android.documentsui.model.DocumentInfo.getCursorString;
Tomasz Mikolajewski748ea8c2016-01-22 16:22:51 +090028import static com.android.documentsui.services.FileOperationService.EXTRA_DIALOG_TYPE;
29import static com.android.documentsui.services.FileOperationService.EXTRA_OPERATION;
30import static com.android.documentsui.services.FileOperationService.EXTRA_SRC_LIST;
Steve McKay14e827a2016-01-06 18:32:13 -080031import static com.android.documentsui.services.FileOperationService.OPERATION_COPY;
Steve McKay14e827a2016-01-06 18:32:13 -080032
33import android.annotation.StringRes;
34import android.app.Notification;
35import android.app.Notification.Builder;
Tomasz Mikolajewski748ea8c2016-01-22 16:22:51 +090036import android.app.PendingIntent;
Steve McKay14e827a2016-01-06 18:32:13 -080037import android.content.ContentProviderClient;
38import android.content.Context;
Tomasz Mikolajewski748ea8c2016-01-22 16:22:51 +090039import android.content.Intent;
Steve McKay14e827a2016-01-06 18:32:13 -080040import android.content.res.AssetFileDescriptor;
41import android.database.Cursor;
42import android.net.Uri;
43import android.os.CancellationSignal;
44import android.os.ParcelFileDescriptor;
45import android.os.RemoteException;
46import android.provider.DocumentsContract;
47import android.provider.DocumentsContract.Document;
48import android.text.format.DateUtils;
49import android.util.Log;
50import android.webkit.MimeTypeMap;
51
Ben Kwad5b2af12016-01-28 16:39:57 -080052import com.android.documentsui.Metrics;
Steve McKay14e827a2016-01-06 18:32:13 -080053import com.android.documentsui.R;
54import com.android.documentsui.model.DocumentInfo;
55import com.android.documentsui.model.DocumentStack;
Steve McKayecbf3c52016-01-13 17:17:39 -080056import com.android.documentsui.services.FileOperationService.OpType;
Steve McKay14e827a2016-01-06 18:32:13 -080057
58import libcore.io.IoUtils;
59
60import java.io.FileNotFoundException;
61import java.io.IOException;
62import java.io.InputStream;
63import java.io.OutputStream;
64import java.text.NumberFormat;
Tomasz Mikolajewski748ea8c2016-01-22 16:22:51 +090065import java.util.ArrayList;
Steve McKay14e827a2016-01-06 18:32:13 -080066import java.util.List;
67
68class CopyJob extends Job {
Steve McKay7a3b8112016-02-23 10:06:50 -080069
Steve McKay14e827a2016-01-06 18:32:13 -080070 private static final String TAG = "CopyJob";
Steve McKay7a3b8112016-02-23 10:06:50 -080071 private static final int PROGRESS_INTERVAL_MILLIS = 500;
72
Steve McKay35645432016-01-20 15:09:35 -080073 final List<DocumentInfo> mSrcs;
Tomasz Mikolajewski748ea8c2016-01-22 16:22:51 +090074 final ArrayList<DocumentInfo> convertedFiles = new ArrayList<>();
Steve McKay14e827a2016-01-06 18:32:13 -080075
76 private long mStartTime = -1;
Steve McKay7a3b8112016-02-23 10:06:50 -080077
Steve McKay14e827a2016-01-06 18:32:13 -080078 private long mBatchSize;
79 private long mBytesCopied;
80 private long mLastNotificationTime;
81 // Speed estimation
82 private long mBytesCopiedSample;
83 private long mSampleTime;
84 private long mSpeed;
85 private long mRemainingTime;
86
87 /**
88 * Copies files to a destination identified by {@code destination}.
89 * @see @link {@link Job} constructor for most param descriptions.
90 *
91 * @param srcs List of files to be copied.
92 */
Steve McKayecbf3c52016-01-13 17:17:39 -080093 CopyJob(Context service, Context appContext, Listener listener,
Steve McKay35645432016-01-20 15:09:35 -080094 String id, DocumentStack stack, List<DocumentInfo> srcs) {
95 super(service, appContext, listener, OPERATION_COPY, id, stack);
Steve McKayecbf3c52016-01-13 17:17:39 -080096
Steve McKaya1f76802016-02-25 13:34:03 -080097 assert(!srcs.isEmpty());
Steve McKay35645432016-01-20 15:09:35 -080098 this.mSrcs = srcs;
Steve McKayecbf3c52016-01-13 17:17:39 -080099 }
100
101 /**
102 * @see @link {@link Job} constructor for most param descriptions.
103 *
104 * @param srcs List of files to be copied.
105 */
106 CopyJob(Context service, Context appContext, Listener listener,
107 @OpType int opType, String id, DocumentStack destination, List<DocumentInfo> srcs) {
108 super(service, appContext, listener, opType, id, destination);
Steve McKay14e827a2016-01-06 18:32:13 -0800109
Steve McKaya1f76802016-02-25 13:34:03 -0800110 assert(!srcs.isEmpty());
Steve McKay35645432016-01-20 15:09:35 -0800111 this.mSrcs = srcs;
Steve McKay14e827a2016-01-06 18:32:13 -0800112 }
113
114 @Override
115 Builder createProgressBuilder() {
116 return super.createProgressBuilder(
Steve McKayecbf3c52016-01-13 17:17:39 -0800117 service.getString(R.string.copy_notification_title),
Steve McKay14e827a2016-01-06 18:32:13 -0800118 R.drawable.ic_menu_copy,
Steve McKayecbf3c52016-01-13 17:17:39 -0800119 service.getString(android.R.string.cancel),
Steve McKay14e827a2016-01-06 18:32:13 -0800120 R.drawable.ic_cab_cancel);
121 }
122
123 @Override
124 public Notification getSetupNotification() {
Steve McKayecbf3c52016-01-13 17:17:39 -0800125 return getSetupNotification(service.getString(R.string.copy_preparing));
Steve McKay14e827a2016-01-06 18:32:13 -0800126 }
127
128 public boolean shouldUpdateProgress() {
129 // Wait a while between updates :)
130 return elapsedRealtime() - mLastNotificationTime > PROGRESS_INTERVAL_MILLIS;
131 }
132
133 Notification getProgressNotification(@StringRes int msgId) {
Tomasz Mikolajewski0fa97e82016-02-18 16:45:44 +0900134 if (mBatchSize >= 0) {
135 double completed = (double) this.mBytesCopied / mBatchSize;
136 mProgressBuilder.setProgress(100, (int) (completed * 100), false);
137 mProgressBuilder.setContentInfo(
138 NumberFormat.getPercentInstance().format(completed));
139 } else {
140 // If the total file size failed to compute on some files, then show
141 // an indeterminate spinner. CopyJob would most likely fail on those
142 // files while copying, but would continue with another files.
143 // Also, if the total size is 0 bytes, show an indeterminate spinner.
144 mProgressBuilder.setProgress(0, 0, true);
145 }
146
Steve McKay14e827a2016-01-06 18:32:13 -0800147 if (mRemainingTime > 0) {
Steve McKayecbf3c52016-01-13 17:17:39 -0800148 mProgressBuilder.setContentText(service.getString(msgId,
Steve McKay14e827a2016-01-06 18:32:13 -0800149 DateUtils.formatDuration(mRemainingTime)));
150 } else {
151 mProgressBuilder.setContentText(null);
152 }
153
154 // Remember when we last returned progress so we can provide an answer
155 // in shouldUpdateProgress.
156 mLastNotificationTime = elapsedRealtime();
157 return mProgressBuilder.build();
158 }
159
160 public Notification getProgressNotification() {
161 return getProgressNotification(R.string.copy_remaining);
162 }
163
164 void onBytesCopied(long numBytes) {
165 this.mBytesCopied += numBytes;
166 }
167
168 /**
169 * Generates an estimate of the remaining time in the copy.
170 */
171 void updateRemainingTimeEstimate() {
172 long elapsedTime = elapsedRealtime() - mStartTime;
173
174 final long sampleDuration = elapsedTime - mSampleTime;
175 final long sampleSpeed = ((mBytesCopied - mBytesCopiedSample) * 1000) / sampleDuration;
176 if (mSpeed == 0) {
177 mSpeed = sampleSpeed;
178 } else {
179 mSpeed = ((3 * mSpeed) + sampleSpeed) / 4;
180 }
181
182 if (mSampleTime > 0 && mSpeed > 0) {
183 mRemainingTime = ((mBatchSize - mBytesCopied) * 1000) / mSpeed;
184 } else {
185 mRemainingTime = 0;
186 }
187
188 mSampleTime = elapsedTime;
189 mBytesCopiedSample = mBytesCopied;
190 }
191
192 @Override
193 Notification getFailureNotification() {
194 return getFailureNotification(
195 R.plurals.copy_error_notification_title, R.drawable.ic_menu_copy);
196 }
197
198 @Override
Tomasz Mikolajewski748ea8c2016-01-22 16:22:51 +0900199 Notification getWarningNotification() {
Tomasz Mikolajewskicd270152016-02-01 12:01:14 +0900200 final Intent navigateIntent = buildNavigateIntent(INTENT_TAG_WARNING);
Tomasz Mikolajewski748ea8c2016-01-22 16:22:51 +0900201 navigateIntent.putExtra(EXTRA_DIALOG_TYPE, DIALOG_TYPE_CONVERTED);
202 navigateIntent.putExtra(EXTRA_OPERATION, operationType);
203
204 navigateIntent.putParcelableArrayListExtra(EXTRA_SRC_LIST, convertedFiles);
205
206 // TODO: Consider adding a dialog on tapping the notification with a list of
207 // converted files.
208 final Notification.Builder warningBuilder = new Notification.Builder(service)
209 .setContentTitle(service.getResources().getString(
210 R.string.notification_copy_files_converted_title))
211 .setContentText(service.getString(
212 R.string.notification_touch_for_details))
213 .setContentIntent(PendingIntent.getActivity(appContext, 0, navigateIntent,
214 PendingIntent.FLAG_UPDATE_CURRENT | PendingIntent.FLAG_ONE_SHOT))
215 .setCategory(Notification.CATEGORY_ERROR)
216 .setSmallIcon(R.drawable.ic_menu_copy)
217 .setAutoCancel(true);
218 return warningBuilder.build();
219 }
220
221 @Override
Tomasz Mikolajewski0fa97e82016-02-18 16:45:44 +0900222 void start() {
Steve McKay14e827a2016-01-06 18:32:13 -0800223 mStartTime = elapsedRealtime();
224
Tomasz Mikolajewski0fa97e82016-02-18 16:45:44 +0900225 try {
226 mBatchSize = calculateSize(mSrcs);
227 } catch (ResourceException e) {
228 Log.w(TAG, "Failed to calculate total size. Copying without progress.");
229 mBatchSize = -1;
230 }
Steve McKay14e827a2016-01-06 18:32:13 -0800231
232 DocumentInfo srcInfo;
Ben Kwad5b2af12016-01-28 16:39:57 -0800233 DocumentInfo dstInfo = stack.peek();
Steve McKay35645432016-01-20 15:09:35 -0800234 for (int i = 0; i < mSrcs.size() && !isCanceled(); ++i) {
235 srcInfo = mSrcs.get(i);
Steve McKay14e827a2016-01-06 18:32:13 -0800236
237 // Guard unsupported recursive operation.
Tomasz Mikolajewski0fa97e82016-02-18 16:45:44 +0900238 try {
239 if (dstInfo.equals(srcInfo) || isDescendentOf(srcInfo, dstInfo)) {
240 throw new ResourceException("Cannot copy to itself recursively.");
241 }
242 } catch (ResourceException e) {
243 Log.e(TAG, e.toString());
244 onFileFailed(srcInfo);
Steve McKay14e827a2016-01-06 18:32:13 -0800245 continue;
246 }
247
248 if (DEBUG) Log.d(TAG,
Steve McKayecbf3c52016-01-13 17:17:39 -0800249 "Copying " + srcInfo.displayName + " (" + srcInfo.derivedUri + ")"
250 + " to " + dstInfo.displayName + " (" + dstInfo.derivedUri + ")");
Steve McKay14e827a2016-01-06 18:32:13 -0800251
Tomasz Mikolajewski0fa97e82016-02-18 16:45:44 +0900252 try {
253 processDocument(srcInfo, null, dstInfo);
254 } catch (ResourceException e) {
255 Log.e(TAG, e.toString());
256 onFileFailed(srcInfo);
257 }
Steve McKay14e827a2016-01-06 18:32:13 -0800258 }
Ben Kwad5b2af12016-01-28 16:39:57 -0800259 Metrics.logFileOperation(service, operationType, mSrcs, dstInfo);
Steve McKay14e827a2016-01-06 18:32:13 -0800260 }
261
Tomasz Mikolajewski748ea8c2016-01-22 16:22:51 +0900262 @Override
263 boolean hasWarnings() {
264 return !convertedFiles.isEmpty();
265 }
266
Steve McKay14e827a2016-01-06 18:32:13 -0800267 /**
268 * Logs progress on the current copy operation. Displays/Updates the progress notification.
269 *
270 * @param bytesCopied
271 */
272 private void makeCopyProgress(long bytesCopied) {
273 onBytesCopied(bytesCopied);
274 if (shouldUpdateProgress()) {
275 updateRemainingTimeEstimate();
276 listener.onProgress(this);
277 }
278 }
279
280 /**
281 * Copies a the given document to the given location.
282 *
Steve McKay35645432016-01-20 15:09:35 -0800283 * @param src DocumentInfos for the documents to copy.
Tomasz Mikolajewskib8436af2016-01-25 16:20:15 +0900284 * @param srcParent DocumentInfo for the parent of the document to process.
Steve McKay14e827a2016-01-06 18:32:13 -0800285 * @param dstDirInfo The destination directory.
Tomasz Mikolajewski0fa97e82016-02-18 16:45:44 +0900286 * @throws ResourceException
Tomasz Mikolajewskib8436af2016-01-25 16:20:15 +0900287 *
288 * TODO: Stop passing srcParent, as it's not used for copy, but for move only.
Steve McKay14e827a2016-01-06 18:32:13 -0800289 */
Tomasz Mikolajewski0fa97e82016-02-18 16:45:44 +0900290 void processDocument(DocumentInfo src, DocumentInfo srcParent,
291 DocumentInfo dstDirInfo) throws ResourceException {
Steve McKay14e827a2016-01-06 18:32:13 -0800292
293 // TODO: When optimized copy kicks in, we'll not making any progress updates.
294 // For now. Local storage isn't using optimized copy.
295
Tomasz Mikolajewski67048082016-01-21 10:00:33 +0900296 // When copying within the same provider, try to use optimized copying.
Steve McKay14e827a2016-01-06 18:32:13 -0800297 // If not supported, then fallback to byte-by-byte copy/move.
Steve McKay35645432016-01-20 15:09:35 -0800298 if (src.authority.equals(dstDirInfo.authority)) {
299 if ((src.flags & Document.FLAG_SUPPORTS_COPY) != 0) {
Tomasz Mikolajewski0fa97e82016-02-18 16:45:44 +0900300 try {
301 if (DocumentsContract.copyDocument(getClient(src), src.derivedUri,
302 dstDirInfo.derivedUri) == null) {
303 throw new ResourceException("Provider side copy failed for document %s.",
304 src.derivedUri);
305 }
306 } catch (ResourceException e) {
307 throw e;
308 } catch (RemoteException | RuntimeException e) {
309 throw new ResourceException(
310 "Provider side copy failed for document %s due to an exception.",
311 src.derivedUri, e);
Steve McKay14e827a2016-01-06 18:32:13 -0800312 }
Tomasz Mikolajewski0fa97e82016-02-18 16:45:44 +0900313 return;
Steve McKay14e827a2016-01-06 18:32:13 -0800314 }
315 }
316
317 // If we couldn't do an optimized copy...we fall back to vanilla byte copy.
Tomasz Mikolajewski0fa97e82016-02-18 16:45:44 +0900318 byteCopyDocument(src, dstDirInfo);
Steve McKay14e827a2016-01-06 18:32:13 -0800319 }
320
Tomasz Mikolajewski0fa97e82016-02-18 16:45:44 +0900321 void byteCopyDocument(DocumentInfo src, DocumentInfo dest) throws ResourceException {
Steve McKay14e827a2016-01-06 18:32:13 -0800322 final String dstMimeType;
323 final String dstDisplayName;
324
Steve McKay35645432016-01-20 15:09:35 -0800325 if (DEBUG) Log.d(TAG, "Doing byte copy of document: " + src);
Steve McKay14e827a2016-01-06 18:32:13 -0800326 // If the file is virtual, but can be converted to another format, then try to copy it
327 // as such format. Also, append an extension for the target mime type (if known).
Steve McKay35645432016-01-20 15:09:35 -0800328 if (src.isVirtualDocument()) {
Tomasz Mikolajewski0fa97e82016-02-18 16:45:44 +0900329 String[] streamTypes = null;
330 try {
331 streamTypes = getContentResolver().getStreamTypes(src.derivedUri, "*/*");
332 } catch (RuntimeException e) {
333 throw new ResourceException(
334 "Failed to obtain streamable types for %s due to an exception.",
335 src.derivedUri, e);
336 }
Steve McKay14e827a2016-01-06 18:32:13 -0800337 if (streamTypes != null && streamTypes.length > 0) {
338 dstMimeType = streamTypes[0];
339 final String extension = MimeTypeMap.getSingleton().
340 getExtensionFromMimeType(dstMimeType);
Steve McKay35645432016-01-20 15:09:35 -0800341 dstDisplayName = src.displayName +
342 (extension != null ? "." + extension : src.displayName);
Steve McKay14e827a2016-01-06 18:32:13 -0800343 } else {
Tomasz Mikolajewski0fa97e82016-02-18 16:45:44 +0900344 throw new ResourceException("Cannot copy virtual file %s. No streamable formats "
345 + "available.", src.derivedUri);
Steve McKay14e827a2016-01-06 18:32:13 -0800346 }
347 } else {
Steve McKay35645432016-01-20 15:09:35 -0800348 dstMimeType = src.mimeType;
349 dstDisplayName = src.displayName;
Steve McKay14e827a2016-01-06 18:32:13 -0800350 }
351
352 // Create the target document (either a file or a directory), then copy recursively the
353 // contents (bytes or children).
Tomasz Mikolajewski0fa97e82016-02-18 16:45:44 +0900354 Uri dstUri = null;
355 try {
356 dstUri = DocumentsContract.createDocument(
357 getClient(dest), dest.derivedUri, dstMimeType, dstDisplayName);
358 } catch (RemoteException | RuntimeException e) {
359 throw new ResourceException(
360 "Couldn't create destination document " + dstDisplayName + " in directory %s "
361 + "due to an exception.", dest.derivedUri, e);
362 }
Steve McKay14e827a2016-01-06 18:32:13 -0800363 if (dstUri == null) {
364 // If this is a directory, the entire subdir will not be copied over.
Tomasz Mikolajewski0fa97e82016-02-18 16:45:44 +0900365 throw new ResourceException(
366 "Couldn't create destination document " + dstDisplayName + " in directory %s.",
367 dest.derivedUri);
Steve McKay14e827a2016-01-06 18:32:13 -0800368 }
369
370 DocumentInfo dstInfo = null;
371 try {
372 dstInfo = DocumentInfo.fromUri(getContentResolver(), dstUri);
Tomasz Mikolajewski0fa97e82016-02-18 16:45:44 +0900373 } catch (FileNotFoundException | RuntimeException e) {
374 throw new ResourceException("Could not load DocumentInfo for newly created file %s.",
375 dstUri);
Steve McKay14e827a2016-01-06 18:32:13 -0800376 }
377
Steve McKay35645432016-01-20 15:09:35 -0800378 if (Document.MIME_TYPE_DIR.equals(src.mimeType)) {
Tomasz Mikolajewski0fa97e82016-02-18 16:45:44 +0900379 copyDirectoryHelper(src, dstInfo);
Steve McKay14e827a2016-01-06 18:32:13 -0800380 } else {
Tomasz Mikolajewskidb875432016-02-23 15:12:54 +0900381 copyFileHelper(src, dstInfo, dest, dstMimeType);
Steve McKay14e827a2016-01-06 18:32:13 -0800382 }
Steve McKay14e827a2016-01-06 18:32:13 -0800383 }
384
385 /**
386 * Handles recursion into a directory and copying its contents. Note that in linux terms, this
387 * does the equivalent of "cp src/* dst", not "cp -r src dst".
388 *
Steve McKay35645432016-01-20 15:09:35 -0800389 * @param srcDir Info of the directory to copy from. The routine will copy the directory's
Steve McKay14e827a2016-01-06 18:32:13 -0800390 * contents, not the directory itself.
Steve McKay35645432016-01-20 15:09:35 -0800391 * @param destDir Info of the directory to copy to. Must be created beforehand.
Tomasz Mikolajewski0fa97e82016-02-18 16:45:44 +0900392 * @throws ResourceException
Steve McKay14e827a2016-01-06 18:32:13 -0800393 */
Tomasz Mikolajewski0fa97e82016-02-18 16:45:44 +0900394 private void copyDirectoryHelper(DocumentInfo srcDir, DocumentInfo destDir)
395 throws ResourceException {
Steve McKay14e827a2016-01-06 18:32:13 -0800396 // Recurse into directories. Copy children into the new subdirectory.
397 final String queryColumns[] = new String[] {
398 Document.COLUMN_DISPLAY_NAME,
399 Document.COLUMN_DOCUMENT_ID,
400 Document.COLUMN_MIME_TYPE,
401 Document.COLUMN_SIZE,
402 Document.COLUMN_FLAGS
403 };
404 Cursor cursor = null;
405 boolean success = true;
Tomasz Mikolajewski0fa97e82016-02-18 16:45:44 +0900406 // Iterate over srcs in the directory; copy to the destination directory.
407 final Uri queryUri = buildChildDocumentsUri(srcDir.authority, srcDir.documentId);
Steve McKay14e827a2016-01-06 18:32:13 -0800408 try {
Tomasz Mikolajewski0fa97e82016-02-18 16:45:44 +0900409 try {
410 cursor = getClient(srcDir).query(queryUri, queryColumns, null, null, null);
411 } catch (RemoteException | RuntimeException e) {
412 throw new ResourceException("Failed to query children of %s due to an exception.",
413 srcDir.derivedUri, e);
Steve McKay14e827a2016-01-06 18:32:13 -0800414 }
Tomasz Mikolajewski0fa97e82016-02-18 16:45:44 +0900415
416 DocumentInfo src;
417 while (cursor.moveToNext() && !isCanceled()) {
418 try {
419 src = DocumentInfo.fromCursor(cursor, srcDir.authority);
420 processDocument(src, srcDir, destDir);
421 } catch (RuntimeException e) {
422 Log.e(TAG, "Failed to recursively process a file %s due to an exception."
423 .format(srcDir.derivedUri.toString()), e);
424 success = false;
425 }
426 }
427 } catch (RuntimeException e) {
428 Log.e(TAG, "Failed to copy a file %s to %s. "
429 .format(srcDir.derivedUri.toString(), destDir.derivedUri.toString()), e);
430 success = false;
Steve McKay14e827a2016-01-06 18:32:13 -0800431 } finally {
432 IoUtils.closeQuietly(cursor);
433 }
434
Tomasz Mikolajewski0fa97e82016-02-18 16:45:44 +0900435 if (!success) {
436 throw new RuntimeException("Some files failed to copy during a recursive "
437 + "directory copy.");
438 }
Steve McKay14e827a2016-01-06 18:32:13 -0800439 }
440
441 /**
442 * Handles copying a single file.
443 *
Tomasz Mikolajewskidb875432016-02-23 15:12:54 +0900444 * @param src Info of the file to copy from.
445 * @param dest Info of the *file* to copy to. Must be created beforehand.
446 * @param destParent Info of the parent of the destination.
Steve McKay14e827a2016-01-06 18:32:13 -0800447 * @param mimeType Mime type for the target. Can be different than source for virtual files.
Tomasz Mikolajewski0fa97e82016-02-18 16:45:44 +0900448 * @throws ResourceException
Steve McKay14e827a2016-01-06 18:32:13 -0800449 */
Tomasz Mikolajewskidb875432016-02-23 15:12:54 +0900450 private void copyFileHelper(DocumentInfo src, DocumentInfo dest, DocumentInfo destParent,
451 String mimeType) throws ResourceException {
Steve McKay14e827a2016-01-06 18:32:13 -0800452 CancellationSignal canceller = new CancellationSignal();
Tomasz Mikolajewski0fa97e82016-02-18 16:45:44 +0900453 AssetFileDescriptor srcFileAsAsset = null;
Steve McKay14e827a2016-01-06 18:32:13 -0800454 ParcelFileDescriptor srcFile = null;
455 ParcelFileDescriptor dstFile = null;
Steve McKay35645432016-01-20 15:09:35 -0800456 InputStream in = null;
457 OutputStream out = null;
Tomasz Mikolajewski0fa97e82016-02-18 16:45:44 +0900458 boolean success = false;
Steve McKay14e827a2016-01-06 18:32:13 -0800459
Steve McKay14e827a2016-01-06 18:32:13 -0800460 try {
461 // If the file is virtual, but can be converted to another format, then try to copy it
462 // as such format.
Steve McKay35645432016-01-20 15:09:35 -0800463 if (src.isVirtualDocument()) {
Tomasz Mikolajewski0fa97e82016-02-18 16:45:44 +0900464 try {
465 srcFileAsAsset = getClient(src).openTypedAssetFileDescriptor(
Steve McKay35645432016-01-20 15:09:35 -0800466 src.derivedUri, mimeType, null, canceller);
Tomasz Mikolajewski0fa97e82016-02-18 16:45:44 +0900467 } catch (FileNotFoundException | RemoteException | RuntimeException e) {
468 throw new ResourceException("Failed to open a file as asset for %s due to an "
469 + "exception.", src.derivedUri, e);
470 }
Steve McKay14e827a2016-01-06 18:32:13 -0800471 srcFile = srcFileAsAsset.getParcelFileDescriptor();
Tomasz Mikolajewski0fa97e82016-02-18 16:45:44 +0900472 try {
473 in = new AssetFileDescriptor.AutoCloseInputStream(srcFileAsAsset);
474 } catch (IOException e) {
475 throw new ResourceException("Failed to open a file input stream for %s due "
476 + "an exception.", src.derivedUri, e);
477 }
Steve McKay14e827a2016-01-06 18:32:13 -0800478 } else {
Tomasz Mikolajewski0fa97e82016-02-18 16:45:44 +0900479 try {
480 srcFile = getClient(src).openFile(src.derivedUri, "r", canceller);
481 } catch (FileNotFoundException | RemoteException | RuntimeException e) {
482 throw new ResourceException(
483 "Failed to open a file for %s due to an exception.", src.derivedUri, e);
484 }
Steve McKay35645432016-01-20 15:09:35 -0800485 in = new ParcelFileDescriptor.AutoCloseInputStream(srcFile);
Steve McKay14e827a2016-01-06 18:32:13 -0800486 }
487
Tomasz Mikolajewski0fa97e82016-02-18 16:45:44 +0900488 try {
489 dstFile = getClient(dest).openFile(dest.derivedUri, "w", canceller);
490 } catch (FileNotFoundException | RemoteException | RuntimeException e) {
491 throw new ResourceException("Failed to open the destination file %s for writing "
492 + "due to an exception.", dest.derivedUri, e);
493 }
Steve McKay35645432016-01-20 15:09:35 -0800494 out = new ParcelFileDescriptor.AutoCloseOutputStream(dstFile);
Steve McKay14e827a2016-01-06 18:32:13 -0800495
Steve McKayecbf3c52016-01-13 17:17:39 -0800496 byte[] buffer = new byte[32 * 1024];
Steve McKay14e827a2016-01-06 18:32:13 -0800497 int len;
Tomasz Mikolajewski0fa97e82016-02-18 16:45:44 +0900498 try {
499 while ((len = in.read(buffer)) != -1) {
500 if (isCanceled()) {
Steve McKay7a3b8112016-02-23 10:06:50 -0800501 if (DEBUG) Log.d(TAG, "Canceled copy mid-copy of: " + src.derivedUri);
502 return;
Tomasz Mikolajewski0fa97e82016-02-18 16:45:44 +0900503 }
504 out.write(buffer, 0, len);
505 makeCopyProgress(len);
Steve McKay14e827a2016-01-06 18:32:13 -0800506 }
Tomasz Mikolajewski0fa97e82016-02-18 16:45:44 +0900507
508 srcFile.checkError();
509 } catch (IOException e) {
510 throw new ResourceException(
511 "Failed to copy bytes from %s to %s due to an IO exception.",
512 src.derivedUri, dest.derivedUri, e);
Steve McKay14e827a2016-01-06 18:32:13 -0800513 }
514
Tomasz Mikolajewski0fa97e82016-02-18 16:45:44 +0900515 if (src.isVirtualDocument()) {
516 convertedFiles.add(src);
Steve McKay14e827a2016-01-06 18:32:13 -0800517 }
Tomasz Mikolajewski0fa97e82016-02-18 16:45:44 +0900518
519 success = true;
Steve McKay14e827a2016-01-06 18:32:13 -0800520 } finally {
Tomasz Mikolajewski0fa97e82016-02-18 16:45:44 +0900521 if (!success) {
522 if (dstFile != null) {
523 try {
524 dstFile.closeWithError("Error copying bytes.");
525 } catch (IOException closeError) {
526 Log.w(TAG, "Error closing destination.", closeError);
527 }
528 }
529
530 if (DEBUG) Log.d(TAG, "Cleaning up failed operation leftovers.");
531 canceller.cancel();
532 try {
Tomasz Mikolajewskidb875432016-02-23 15:12:54 +0900533 deleteDocument(dest, destParent);
534 } catch (ResourceException e) {
Tomasz Mikolajewski0fa97e82016-02-18 16:45:44 +0900535 Log.w(TAG, "Failed to cleanup after copy error: " + src.derivedUri, e);
536 }
537 }
538
Steve McKay14e827a2016-01-06 18:32:13 -0800539 // This also ensures the file descriptors are closed.
Steve McKay35645432016-01-20 15:09:35 -0800540 IoUtils.closeQuietly(in);
541 IoUtils.closeQuietly(out);
Steve McKay14e827a2016-01-06 18:32:13 -0800542 }
Steve McKay14e827a2016-01-06 18:32:13 -0800543 }
544
545 /**
546 * Calculates the cumulative size of all the documents in the list. Directories are recursed
547 * into and totaled up.
548 *
549 * @param srcs
550 * @return Size in bytes.
Tomasz Mikolajewski0fa97e82016-02-18 16:45:44 +0900551 * @throws ResourceException
Steve McKay14e827a2016-01-06 18:32:13 -0800552 */
Tomasz Mikolajewski0fa97e82016-02-18 16:45:44 +0900553 private long calculateSize(List<DocumentInfo> srcs) throws ResourceException {
Steve McKay14e827a2016-01-06 18:32:13 -0800554 long result = 0;
555
556 for (DocumentInfo src : srcs) {
557 if (src.isDirectory()) {
558 // Directories need to be recursed into.
Tomasz Mikolajewski0fa97e82016-02-18 16:45:44 +0900559 try {
560 result += calculateFileSizesRecursively(getClient(src), src.derivedUri);
561 } catch (RemoteException e) {
562 throw new ResourceException("Failed to obtain the client for %s.",
563 src.derivedUri);
564 }
Steve McKay14e827a2016-01-06 18:32:13 -0800565 } else {
566 result += src.size;
567 }
568 }
569 return result;
570 }
571
572 /**
573 * Calculates (recursively) the cumulative size of all the files under the given directory.
574 *
Tomasz Mikolajewski0fa97e82016-02-18 16:45:44 +0900575 * @throws ResourceException
Steve McKay14e827a2016-01-06 18:32:13 -0800576 */
577 private static long calculateFileSizesRecursively(
Tomasz Mikolajewski0fa97e82016-02-18 16:45:44 +0900578 ContentProviderClient client, Uri uri) throws ResourceException {
Steve McKay14e827a2016-01-06 18:32:13 -0800579 final String authority = uri.getAuthority();
Steve McKayecbf3c52016-01-13 17:17:39 -0800580 final Uri queryUri = buildChildDocumentsUri(authority, getDocumentId(uri));
Steve McKay14e827a2016-01-06 18:32:13 -0800581 final String queryColumns[] = new String[] {
582 Document.COLUMN_DOCUMENT_ID,
583 Document.COLUMN_MIME_TYPE,
584 Document.COLUMN_SIZE
585 };
586
587 long result = 0;
588 Cursor cursor = null;
589 try {
590 cursor = client.query(queryUri, queryColumns, null, null, null);
591 while (cursor.moveToNext()) {
592 if (Document.MIME_TYPE_DIR.equals(
593 getCursorString(cursor, Document.COLUMN_MIME_TYPE))) {
594 // Recurse into directories.
Steve McKayecbf3c52016-01-13 17:17:39 -0800595 final Uri dirUri = buildDocumentUri(authority,
Steve McKay14e827a2016-01-06 18:32:13 -0800596 getCursorString(cursor, Document.COLUMN_DOCUMENT_ID));
597 result += calculateFileSizesRecursively(client, dirUri);
598 } else {
599 // This may return -1 if the size isn't defined. Ignore those cases.
600 long size = getCursorLong(cursor, Document.COLUMN_SIZE);
601 result += size > 0 ? size : 0;
602 }
603 }
Tomasz Mikolajewski0fa97e82016-02-18 16:45:44 +0900604 } catch (RemoteException | RuntimeException e) {
605 throw new ResourceException(
606 "Failed to calculate size for %s due to an exception.", uri, e);
Steve McKay14e827a2016-01-06 18:32:13 -0800607 } finally {
608 IoUtils.closeQuietly(cursor);
609 }
610
611 return result;
612 }
613
Steve McKay14e827a2016-01-06 18:32:13 -0800614 /**
615 * Returns true if {@code doc} is a descendant of {@code parentDoc}.
Tomasz Mikolajewski0fa97e82016-02-18 16:45:44 +0900616 * @throws ResourceException
Steve McKay14e827a2016-01-06 18:32:13 -0800617 */
Steve McKay35645432016-01-20 15:09:35 -0800618 boolean isDescendentOf(DocumentInfo doc, DocumentInfo parent)
Tomasz Mikolajewski0fa97e82016-02-18 16:45:44 +0900619 throws ResourceException {
Steve McKay35645432016-01-20 15:09:35 -0800620 if (parent.isDirectory() && doc.authority.equals(parent.authority)) {
Tomasz Mikolajewski0fa97e82016-02-18 16:45:44 +0900621 try {
622 return isChildDocument(getClient(doc), doc.derivedUri, parent.derivedUri);
623 } catch (RemoteException | RuntimeException e) {
624 throw new ResourceException(
625 "Failed to check if %s is a child of %s due to an exception.",
626 doc.derivedUri, parent.derivedUri, e);
627 }
Steve McKay14e827a2016-01-06 18:32:13 -0800628 }
629 return false;
630 }
Steve McKayecbf3c52016-01-13 17:17:39 -0800631
Steve McKay35645432016-01-20 15:09:35 -0800632 @Override
633 public String toString() {
634 return new StringBuilder()
635 .append("CopyJob")
636 .append("{")
637 .append("id=" + id)
Tomasz Mikolajewskib8436af2016-01-25 16:20:15 +0900638 .append(", srcs=" + mSrcs)
Steve McKay35645432016-01-20 15:09:35 -0800639 .append(", destination=" + stack)
640 .append("}")
641 .toString();
642 }
Steve McKayecbf3c52016-01-13 17:17:39 -0800643}