1 /* 2 * Copyright (C) 2012 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 17 package com.android.nfc.beam; 18 19 import com.android.nfc.R; 20 21 import android.app.Notification; 22 import android.app.NotificationChannel; 23 import android.app.NotificationManager; 24 import android.app.PendingIntent; 25 import android.app.Notification.Builder; 26 import android.bluetooth.BluetoothDevice; 27 import android.content.ContentResolver; 28 import android.content.Context; 29 import android.content.Intent; 30 import android.media.MediaScannerConnection; 31 import android.net.Uri; 32 import android.os.Environment; 33 import android.os.Handler; 34 import android.os.Looper; 35 import android.os.Message; 36 import android.os.SystemClock; 37 import android.os.UserHandle; 38 import android.util.Log; 39 40 import java.io.File; 41 import java.text.SimpleDateFormat; 42 import java.util.ArrayList; 43 import java.util.Arrays; 44 import java.util.Date; 45 import java.util.HashMap; 46 import java.util.Locale; 47 48 import androidx.core.content.FileProvider; 49 50 /** 51 * A BeamTransferManager object represents a set of files 52 * that were received through NFC connection handover 53 * from the same source address. 54 * 55 * It manages starting, stopping, and processing the transfer, as well 56 * as the user visible notification. 57 * 58 * For Bluetooth, files are received through OPP, and 59 * we have no knowledge how many files will be transferred 60 * as part of a single transaction. 61 * Hence, a transfer has a notion of being "alive": if 62 * the last update to a transfer was within WAIT_FOR_NEXT_TRANSFER_MS 63 * milliseconds, we consider a new file transfer from the 64 * same source address as part of the same transfer. 65 * The corresponding URIs will be grouped in a single folder. 66 * 67 * @hide 68 */ 69 70 public class BeamTransferManager implements Handler.Callback, 71 MediaScannerConnection.OnScanCompletedListener { 72 interface Callback { 73 onTransferComplete(BeamTransferManager transfer, boolean success)74 void onTransferComplete(BeamTransferManager transfer, boolean success); 75 }; 76 static final String TAG = "BeamTransferManager"; 77 78 static final Boolean DBG = true; 79 80 // In the states below we still accept new file transfer 81 static final int STATE_NEW = 0; 82 static final int STATE_IN_PROGRESS = 1; 83 static final int STATE_W4_NEXT_TRANSFER = 2; 84 // In the states below no new files are accepted. 85 static final int STATE_W4_MEDIA_SCANNER = 3; 86 static final int STATE_FAILED = 4; 87 static final int STATE_SUCCESS = 5; 88 static final int STATE_CANCELLED = 6; 89 static final int STATE_CANCELLING = 7; 90 static final int MSG_NEXT_TRANSFER_TIMER = 0; 91 92 static final int MSG_TRANSFER_TIMEOUT = 1; 93 static final int DATA_LINK_TYPE_BLUETOOTH = 1; 94 95 // We need to receive an update within this time period 96 // to still consider this transfer to be "alive" (ie 97 // a reason to keep the handover transport enabled). 98 static final int ALIVE_CHECK_MS = 20000; 99 100 // The amount of time to wait for a new transfer 101 // once the current one completes. 102 static final int WAIT_FOR_NEXT_TRANSFER_MS = 4000; 103 104 static final String BEAM_DIR = "beam"; 105 106 static final String BEAM_NOTIFICATION_CHANNEL = "beam_notification_channel"; 107 108 static final String ACTION_WHITELIST_DEVICE = 109 "android.btopp.intent.action.WHITELIST_DEVICE"; 110 111 static final String ACTION_STOP_BLUETOOTH_TRANSFER = 112 "android.btopp.intent.action.STOP_HANDOVER_TRANSFER"; 113 114 final boolean mIncoming; // whether this is an incoming transfer 115 116 final int mTransferId; // Unique ID of this transfer used for notifications 117 int mBluetoothTransferId; // ID of this transfer in Bluetooth namespace 118 119 final PendingIntent mCancelIntent; 120 final Context mContext; 121 final Handler mHandler; 122 final NotificationManager mNotificationManager; 123 final BluetoothDevice mRemoteDevice; 124 final Callback mCallback; 125 final boolean mRemoteActivating; 126 127 // Variables below are only accessed on the main thread 128 int mState; 129 int mCurrentCount; 130 int mSuccessCount; 131 int mTotalCount; 132 int mDataLinkType; 133 boolean mCalledBack; 134 Long mLastUpdate; // Last time an event occurred for this transfer 135 float mProgress; // Progress in range [0..1] 136 ArrayList<Uri> mUris; // Received uris from transport 137 ArrayList<String> mTransferMimeTypes; // Mime-types received from transport 138 Uri[] mOutgoingUris; // URIs to send 139 ArrayList<String> mPaths; // Raw paths on the filesystem for Beam-stored files 140 HashMap<String, String> mMimeTypes; // Mime-types associated with each path 141 HashMap<String, Uri> mMediaUris; // URIs found by the media scanner for each path 142 int mUrisScanned; 143 Long mStartTime; 144 BeamTransferManager(Context context, Callback callback, BeamTransferRecord pendingTransfer, boolean incoming)145 public BeamTransferManager(Context context, Callback callback, 146 BeamTransferRecord pendingTransfer, boolean incoming) { 147 mContext = context; 148 mCallback = callback; 149 mRemoteDevice = pendingTransfer.remoteDevice; 150 mIncoming = incoming; 151 mTransferId = pendingTransfer.id; 152 mBluetoothTransferId = -1; 153 mDataLinkType = pendingTransfer.dataLinkType; 154 mRemoteActivating = pendingTransfer.remoteActivating; 155 mStartTime = 0L; 156 // For incoming transfers, count can be set later 157 mTotalCount = (pendingTransfer.uris != null) ? pendingTransfer.uris.length : 0; 158 mLastUpdate = SystemClock.elapsedRealtime(); 159 mProgress = 0.0f; 160 mState = STATE_NEW; 161 mUris = pendingTransfer.uris == null 162 ? new ArrayList<Uri>() 163 : new ArrayList<Uri>(Arrays.asList(pendingTransfer.uris)); 164 mTransferMimeTypes = new ArrayList<String>(); 165 mMimeTypes = new HashMap<String, String>(); 166 mPaths = new ArrayList<String>(); 167 mMediaUris = new HashMap<String, Uri>(); 168 mCancelIntent = buildCancelIntent(); 169 mUrisScanned = 0; 170 mCurrentCount = 0; 171 mSuccessCount = 0; 172 mOutgoingUris = pendingTransfer.uris; 173 mHandler = new Handler(Looper.getMainLooper(), this); 174 mHandler.sendEmptyMessageDelayed(MSG_TRANSFER_TIMEOUT, ALIVE_CHECK_MS); 175 mNotificationManager = (NotificationManager) mContext.getSystemService( 176 Context.NOTIFICATION_SERVICE); 177 NotificationChannel notificationChannel = new NotificationChannel( 178 BEAM_NOTIFICATION_CHANNEL, mContext.getString(R.string.app_name), 179 NotificationManager.IMPORTANCE_HIGH); 180 mNotificationManager.createNotificationChannel(notificationChannel); 181 } 182 whitelistOppDevice(BluetoothDevice device)183 void whitelistOppDevice(BluetoothDevice device) { 184 if (DBG) Log.d(TAG, "Whitelisting " + device + " for BT OPP"); 185 Intent intent = new Intent(ACTION_WHITELIST_DEVICE); 186 intent.setPackage(mContext.getString(R.string.bluetooth_package)); 187 intent.putExtra(BluetoothDevice.EXTRA_DEVICE, device); 188 intent.addFlags(Intent.FLAG_RECEIVER_FOREGROUND); 189 mContext.sendBroadcastAsUser(intent, UserHandle.CURRENT); 190 } 191 start()192 public void start() { 193 if (mStartTime > 0) { 194 // already started 195 return; 196 } 197 198 mStartTime = System.currentTimeMillis(); 199 200 if (!mIncoming) { 201 if (mDataLinkType == BeamTransferRecord.DATA_LINK_TYPE_BLUETOOTH) { 202 new BluetoothOppHandover(mContext, mRemoteDevice, mUris, mRemoteActivating).start(); 203 } 204 } 205 } 206 updateFileProgress(float progress)207 public void updateFileProgress(float progress) { 208 if (!isRunning()) return; // Ignore when we're no longer running 209 210 mHandler.removeMessages(MSG_NEXT_TRANSFER_TIMER); 211 212 this.mProgress = progress; 213 214 // We're still receiving data from this device - keep it in 215 // the whitelist for a while longer 216 if (mIncoming && mRemoteDevice != null) whitelistOppDevice(mRemoteDevice); 217 218 updateStateAndNotification(STATE_IN_PROGRESS); 219 } 220 setBluetoothTransferId(int id)221 public synchronized void setBluetoothTransferId(int id) { 222 if (mBluetoothTransferId == -1 && id != -1) { 223 mBluetoothTransferId = id; 224 if (mState == STATE_CANCELLING) { 225 sendBluetoothCancelIntentAndUpdateState(); 226 } 227 } 228 } 229 finishTransfer(boolean success, Uri uri, String mimeType)230 public void finishTransfer(boolean success, Uri uri, String mimeType) { 231 if (!isRunning()) return; // Ignore when we're no longer running 232 233 mCurrentCount++; 234 if (success && uri != null) { 235 mSuccessCount++; 236 if (DBG) Log.d(TAG, "Transfer success, uri " + uri + " mimeType " + mimeType); 237 mProgress = 0.0f; 238 if (mimeType == null) { 239 mimeType = MimeTypeUtil.getMimeTypeForUri(mContext, uri); 240 } 241 if (mimeType != null) { 242 mUris.add(uri); 243 mTransferMimeTypes.add(mimeType); 244 } else { 245 if (DBG) Log.d(TAG, "Could not get mimeType for file."); 246 } 247 } else { 248 Log.e(TAG, "Handover transfer failed"); 249 // Do wait to see if there's another file coming. 250 } 251 mHandler.removeMessages(MSG_NEXT_TRANSFER_TIMER); 252 if (mCurrentCount == mTotalCount) { 253 if (mIncoming) { 254 processFiles(); 255 } else { 256 updateStateAndNotification(mSuccessCount > 0 ? STATE_SUCCESS : STATE_FAILED); 257 } 258 } else { 259 mHandler.sendEmptyMessageDelayed(MSG_NEXT_TRANSFER_TIMER, WAIT_FOR_NEXT_TRANSFER_MS); 260 updateStateAndNotification(STATE_W4_NEXT_TRANSFER); 261 } 262 } 263 isRunning()264 public boolean isRunning() { 265 if (mState != STATE_NEW && mState != STATE_IN_PROGRESS && mState != STATE_W4_NEXT_TRANSFER 266 && mState != STATE_CANCELLING) { 267 return false; 268 } else { 269 return true; 270 } 271 } 272 setObjectCount(int objectCount)273 public void setObjectCount(int objectCount) { 274 mTotalCount = objectCount; 275 } 276 cancel()277 void cancel() { 278 if (!isRunning()) return; 279 280 // Delete all files received so far 281 for (Uri uri : mUris) { 282 File file = new File(uri.getPath()); 283 if (file.exists()) file.delete(); 284 } 285 286 if (mBluetoothTransferId != -1) { 287 // we know the ID, we can cancel immediately 288 sendBluetoothCancelIntentAndUpdateState(); 289 } else { 290 updateStateAndNotification(STATE_CANCELLING); 291 } 292 293 } 294 sendBluetoothCancelIntentAndUpdateState()295 private void sendBluetoothCancelIntentAndUpdateState() { 296 Intent cancelIntent = new Intent(ACTION_STOP_BLUETOOTH_TRANSFER); 297 cancelIntent.setPackage(mContext.getString(R.string.bluetooth_package)); 298 cancelIntent.putExtra(BeamStatusReceiver.EXTRA_TRANSFER_ID, mBluetoothTransferId); 299 mContext.sendBroadcast(cancelIntent); 300 updateStateAndNotification(STATE_CANCELLED); 301 } 302 updateNotification()303 void updateNotification() { 304 Builder notBuilder = new Notification.Builder(mContext, BEAM_NOTIFICATION_CHANNEL); 305 notBuilder.setColor(mContext.getResources().getColor( 306 com.android.internal.R.color.system_notification_accent_color)); 307 notBuilder.setWhen(mStartTime); 308 notBuilder.setVisibility(Notification.VISIBILITY_PUBLIC); 309 notBuilder.setOnlyAlertOnce(true); 310 String beamString; 311 if (mIncoming) { 312 beamString = mContext.getString(R.string.beam_progress); 313 } else { 314 beamString = mContext.getString(R.string.beam_outgoing); 315 } 316 if (mState == STATE_NEW || mState == STATE_IN_PROGRESS || 317 mState == STATE_W4_NEXT_TRANSFER || mState == STATE_W4_MEDIA_SCANNER) { 318 notBuilder.setAutoCancel(false); 319 notBuilder.setSmallIcon(mIncoming ? android.R.drawable.stat_sys_download : 320 android.R.drawable.stat_sys_upload); 321 notBuilder.setTicker(beamString); 322 notBuilder.setContentTitle(beamString); 323 notBuilder.addAction(R.drawable.ic_menu_cancel_holo_dark, 324 mContext.getString(R.string.cancel), mCancelIntent); 325 float progress = 0; 326 if (mTotalCount > 0) { 327 float progressUnit = 1.0f / mTotalCount; 328 progress = (float) mCurrentCount * progressUnit + mProgress * progressUnit; 329 } 330 if (mTotalCount > 0 && progress > 0) { 331 notBuilder.setProgress(100, (int) (100 * progress), false); 332 } else { 333 notBuilder.setProgress(100, 0, true); 334 } 335 } else if (mState == STATE_SUCCESS) { 336 notBuilder.setAutoCancel(true); 337 notBuilder.setSmallIcon(mIncoming ? android.R.drawable.stat_sys_download_done : 338 android.R.drawable.stat_sys_upload_done); 339 notBuilder.setTicker(mContext.getString(R.string.beam_complete)); 340 notBuilder.setContentTitle(mContext.getString(R.string.beam_complete)); 341 342 if (mIncoming) { 343 notBuilder.setContentText(mContext.getString(R.string.beam_tap_to_view)); 344 Intent viewIntent = buildViewIntent(); 345 PendingIntent contentIntent = PendingIntent.getActivity( 346 mContext, mTransferId, viewIntent, 0, null); 347 348 notBuilder.setContentIntent(contentIntent); 349 } 350 } else if (mState == STATE_FAILED) { 351 notBuilder.setAutoCancel(false); 352 notBuilder.setSmallIcon(mIncoming ? android.R.drawable.stat_sys_download_done : 353 android.R.drawable.stat_sys_upload_done); 354 notBuilder.setTicker(mContext.getString(R.string.beam_failed)); 355 notBuilder.setContentTitle(mContext.getString(R.string.beam_failed)); 356 } else if (mState == STATE_CANCELLED || mState == STATE_CANCELLING) { 357 notBuilder.setAutoCancel(false); 358 notBuilder.setSmallIcon(mIncoming ? android.R.drawable.stat_sys_download_done : 359 android.R.drawable.stat_sys_upload_done); 360 notBuilder.setTicker(mContext.getString(R.string.beam_canceled)); 361 notBuilder.setContentTitle(mContext.getString(R.string.beam_canceled)); 362 } else { 363 return; 364 } 365 366 mNotificationManager.notify(null, mTransferId, notBuilder.build()); 367 } 368 updateStateAndNotification(int newState)369 void updateStateAndNotification(int newState) { 370 this.mState = newState; 371 this.mLastUpdate = SystemClock.elapsedRealtime(); 372 373 mHandler.removeMessages(MSG_TRANSFER_TIMEOUT); 374 if (isRunning()) { 375 // Update timeout timer if we're still running 376 mHandler.sendEmptyMessageDelayed(MSG_TRANSFER_TIMEOUT, ALIVE_CHECK_MS); 377 } 378 379 updateNotification(); 380 381 if ((mState == STATE_SUCCESS || mState == STATE_FAILED || mState == STATE_CANCELLED) 382 && !mCalledBack) { 383 mCalledBack = true; 384 // Notify that we're done with this transfer 385 mCallback.onTransferComplete(this, mState == STATE_SUCCESS); 386 } 387 } 388 processFiles()389 void processFiles() { 390 // Check the amount of files we received in this transfer; 391 // If more than one, create a separate directory for it. 392 String extRoot = Environment.getExternalStorageDirectory().getPath(); 393 File beamPath = new File(extRoot + "/" + BEAM_DIR); 394 395 if (!checkMediaStorage(beamPath) || mUris.size() == 0) { 396 Log.e(TAG, "Media storage not valid or no uris received."); 397 updateStateAndNotification(STATE_FAILED); 398 return; 399 } 400 401 if (mUris.size() > 1) { 402 beamPath = generateMultiplePath(extRoot + "/" + BEAM_DIR + "/"); 403 if (!beamPath.isDirectory() && !beamPath.mkdir()) { 404 Log.e(TAG, "Failed to create multiple path " + beamPath.toString()); 405 updateStateAndNotification(STATE_FAILED); 406 return; 407 } 408 } 409 410 for (int i = 0; i < mUris.size(); i++) { 411 Uri uri = mUris.get(i); 412 String mimeType = mTransferMimeTypes.get(i); 413 414 File srcFile = new File(uri.getPath()); 415 416 File dstFile = generateUniqueDestination(beamPath.getAbsolutePath(), 417 uri.getLastPathSegment()); 418 Log.d(TAG, "Renaming from " + srcFile); 419 if (!srcFile.renameTo(dstFile)) { 420 if (DBG) Log.d(TAG, "Failed to rename from " + srcFile + " to " + dstFile); 421 srcFile.delete(); 422 return; 423 } else { 424 mPaths.add(dstFile.getAbsolutePath()); 425 mMimeTypes.put(dstFile.getAbsolutePath(), mimeType); 426 if (DBG) Log.d(TAG, "Did successful rename from " + srcFile + " to " + dstFile); 427 } 428 } 429 430 // We can either add files to the media provider, or provide an ACTION_VIEW 431 // intent to the file directly. We base this decision on the mime type 432 // of the first file; if it's media the platform can deal with, 433 // use the media provider, if it's something else, just launch an ACTION_VIEW 434 // on the file. 435 String mimeType = mMimeTypes.get(mPaths.get(0)); 436 if (mimeType.startsWith("image/") || mimeType.startsWith("video/") || 437 mimeType.startsWith("audio/")) { 438 String[] arrayPaths = new String[mPaths.size()]; 439 MediaScannerConnection.scanFile(mContext, mPaths.toArray(arrayPaths), null, this); 440 updateStateAndNotification(STATE_W4_MEDIA_SCANNER); 441 } else { 442 // We're done. 443 updateStateAndNotification(STATE_SUCCESS); 444 } 445 446 } 447 handleMessage(Message msg)448 public boolean handleMessage(Message msg) { 449 if (msg.what == MSG_NEXT_TRANSFER_TIMER) { 450 // We didn't receive a new transfer in time, finalize this one 451 if (mIncoming) { 452 processFiles(); 453 } else { 454 updateStateAndNotification(mSuccessCount > 0 ? STATE_SUCCESS : STATE_FAILED); 455 } 456 return true; 457 } else if (msg.what == MSG_TRANSFER_TIMEOUT) { 458 // No update on this transfer for a while, fail it. 459 if (DBG) Log.d(TAG, "Transfer timed out for id: " + Integer.toString(mTransferId)); 460 updateStateAndNotification(STATE_FAILED); 461 } 462 return false; 463 } 464 onScanCompleted(String path, Uri uri)465 public synchronized void onScanCompleted(String path, Uri uri) { 466 if (DBG) Log.d(TAG, "Scan completed, path " + path + " uri " + uri); 467 if (uri != null) { 468 mMediaUris.put(path, uri); 469 } 470 mUrisScanned++; 471 if (mUrisScanned == mPaths.size()) { 472 // We're done 473 updateStateAndNotification(STATE_SUCCESS); 474 } 475 } 476 477 buildViewIntent()478 Intent buildViewIntent() { 479 if (mPaths.size() == 0) return null; 480 481 Intent viewIntent = new Intent(Intent.ACTION_VIEW); 482 483 String filePath = mPaths.get(0); 484 Uri mediaUri = mMediaUris.get(filePath); 485 Uri uri = mediaUri != null ? mediaUri : 486 FileProvider.getUriForFile(mContext, "com.google.android.nfc.fileprovider", 487 new File(filePath)); 488 viewIntent.setDataAndTypeAndNormalize(uri, mMimeTypes.get(filePath)); 489 viewIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK | 490 Intent.FLAG_GRANT_READ_URI_PERMISSION | Intent.FLAG_GRANT_WRITE_URI_PERMISSION); 491 return viewIntent; 492 } 493 buildCancelIntent()494 PendingIntent buildCancelIntent() { 495 Intent intent = new Intent(BeamStatusReceiver.ACTION_CANCEL_HANDOVER_TRANSFER); 496 intent.putExtra(BeamStatusReceiver.EXTRA_ADDRESS, mRemoteDevice.getAddress()); 497 intent.putExtra(BeamStatusReceiver.EXTRA_INCOMING, mIncoming ? 498 BeamStatusReceiver.DIRECTION_INCOMING : BeamStatusReceiver.DIRECTION_OUTGOING); 499 PendingIntent pi = PendingIntent.getBroadcast(mContext, mTransferId, intent, 500 PendingIntent.FLAG_ONE_SHOT); 501 502 return pi; 503 } 504 checkMediaStorage(File path)505 static boolean checkMediaStorage(File path) { 506 if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) { 507 if (!path.isDirectory() && !path.mkdir()) { 508 Log.e(TAG, "Not dir or not mkdir " + path.getAbsolutePath()); 509 return false; 510 } 511 return true; 512 } else { 513 Log.e(TAG, "External storage not mounted, can't store file."); 514 return false; 515 } 516 } 517 generateUniqueDestination(String path, String fileName)518 static File generateUniqueDestination(String path, String fileName) { 519 int dotIndex = fileName.lastIndexOf("."); 520 String extension = null; 521 String fileNameWithoutExtension = null; 522 if (dotIndex < 0) { 523 extension = ""; 524 fileNameWithoutExtension = fileName; 525 } else { 526 extension = fileName.substring(dotIndex); 527 fileNameWithoutExtension = fileName.substring(0, dotIndex); 528 } 529 File dstFile = new File(path + File.separator + fileName); 530 int count = 0; 531 while (dstFile.exists()) { 532 dstFile = new File(path + File.separator + fileNameWithoutExtension + "-" + 533 Integer.toString(count) + extension); 534 count++; 535 } 536 return dstFile; 537 } 538 generateMultiplePath(String beamRoot)539 static File generateMultiplePath(String beamRoot) { 540 // Generate a unique directory with the date 541 String format = "yyyy-MM-dd"; 542 SimpleDateFormat sdf = new SimpleDateFormat(format, Locale.US); 543 String newPath = beamRoot + "beam-" + sdf.format(new Date()); 544 File newFile = new File(newPath); 545 int count = 0; 546 while (newFile.exists()) { 547 newPath = beamRoot + "beam-" + sdf.format(new Date()) + "-" + 548 Integer.toString(count); 549 newFile = new File(newPath); 550 count++; 551 } 552 return newFile; 553 } 554 } 555 556