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 android.app.Notification; 20 import android.app.Notification.Builder; 21 import android.app.NotificationChannel; 22 import android.app.NotificationManager; 23 import android.app.PendingIntent; 24 import android.bluetooth.BluetoothDevice; 25 import android.content.Context; 26 import android.content.Intent; 27 import android.media.MediaScannerConnection; 28 import android.net.Uri; 29 import android.os.Environment; 30 import android.os.Handler; 31 import android.os.Looper; 32 import android.os.Message; 33 import android.os.SystemClock; 34 import android.os.UserHandle; 35 import android.util.Log; 36 37 import androidx.core.content.FileProvider; 38 39 import com.android.nfc.R; 40 41 import java.io.File; 42 import java.text.SimpleDateFormat; 43 import java.util.ArrayList; 44 import java.util.Arrays; 45 import java.util.Date; 46 import java.util.HashMap; 47 import java.util.Locale; 48 49 /** 50 * A BeamTransferManager object represents a set of files 51 * that were received through NFC connection handover 52 * from the same source address. 53 * 54 * It manages starting, stopping, and processing the transfer, as well 55 * as the user visible notification. 56 * 57 * For Bluetooth, files are received through OPP, and 58 * we have no knowledge how many files will be transferred 59 * as part of a single transaction. 60 * Hence, a transfer has a notion of being "alive": if 61 * the last update to a transfer was within WAIT_FOR_NEXT_TRANSFER_MS 62 * milliseconds, we consider a new file transfer from the 63 * same source address as part of the same transfer. 64 * The corresponding URIs will be grouped in a single folder. 65 * 66 * @hide 67 */ 68 69 public class BeamTransferManager implements Handler.Callback, 70 MediaScannerConnection.OnScanCompletedListener { 71 interface Callback { 72 onTransferComplete(BeamTransferManager transfer, boolean success)73 void onTransferComplete(BeamTransferManager transfer, boolean success); 74 }; 75 static final String TAG = "BeamTransferManager"; 76 77 static final Boolean DBG = true; 78 79 // In the states below we still accept new file transfer 80 static final int STATE_NEW = 0; 81 static final int STATE_IN_PROGRESS = 1; 82 static final int STATE_W4_NEXT_TRANSFER = 2; 83 // In the states below no new files are accepted. 84 static final int STATE_W4_MEDIA_SCANNER = 3; 85 static final int STATE_FAILED = 4; 86 static final int STATE_SUCCESS = 5; 87 static final int STATE_CANCELLED = 6; 88 static final int STATE_CANCELLING = 7; 89 static final int MSG_NEXT_TRANSFER_TIMER = 0; 90 91 static final int MSG_TRANSFER_TIMEOUT = 1; 92 static final int DATA_LINK_TYPE_BLUETOOTH = 1; 93 94 // We need to receive an update within this time period 95 // to still consider this transfer to be "alive" (ie 96 // a reason to keep the handover transport enabled). 97 static final int ALIVE_CHECK_MS = 20000; 98 99 // The amount of time to wait for a new transfer 100 // once the current one completes. 101 static final int WAIT_FOR_NEXT_TRANSFER_MS = 4000; 102 103 static final String BEAM_DIR = "beam"; 104 105 static final String BEAM_NOTIFICATION_CHANNEL = "beam_notification_channel"; 106 107 static final String ACTION_ALLOWLIST_DEVICE = 108 "android.btopp.intent.action.WHITELIST_DEVICE"; 109 110 static final String ACTION_STOP_BLUETOOTH_TRANSFER = 111 "android.btopp.intent.action.STOP_HANDOVER_TRANSFER"; 112 113 final boolean mIncoming; // whether this is an incoming transfer 114 115 final int mTransferId; // Unique ID of this transfer used for notifications 116 int mBluetoothTransferId; // ID of this transfer in Bluetooth namespace 117 118 final PendingIntent mCancelIntent; 119 final Context mContext; 120 final Handler mHandler; 121 final NotificationManager mNotificationManager; 122 final BluetoothDevice mRemoteDevice; 123 final Callback mCallback; 124 final boolean mRemoteActivating; 125 126 // Variables below are only accessed on the main thread 127 int mState; 128 int mCurrentCount; 129 int mSuccessCount; 130 int mTotalCount; 131 int mDataLinkType; 132 boolean mCalledBack; 133 Long mLastUpdate; // Last time an event occurred for this transfer 134 float mProgress; // Progress in range [0..1] 135 ArrayList<Uri> mUris; // Received uris from transport 136 ArrayList<String> mTransferMimeTypes; // Mime-types received from transport 137 Uri[] mOutgoingUris; // URIs to send 138 ArrayList<String> mPaths; // Raw paths on the filesystem for Beam-stored files 139 HashMap<String, String> mMimeTypes; // Mime-types associated with each path 140 HashMap<String, Uri> mMediaUris; // URIs found by the media scanner for each path 141 int mUrisScanned; 142 Long mStartTime; 143 BeamTransferManager(Context context, Callback callback, BeamTransferRecord pendingTransfer, boolean incoming)144 public BeamTransferManager(Context context, Callback callback, 145 BeamTransferRecord pendingTransfer, boolean incoming) { 146 mContext = context; 147 mCallback = callback; 148 mRemoteDevice = pendingTransfer.remoteDevice; 149 mIncoming = incoming; 150 mTransferId = pendingTransfer.id; 151 mBluetoothTransferId = -1; 152 mDataLinkType = pendingTransfer.dataLinkType; 153 mRemoteActivating = pendingTransfer.remoteActivating; 154 mStartTime = 0L; 155 // For incoming transfers, count can be set later 156 mTotalCount = (pendingTransfer.uris != null) ? pendingTransfer.uris.length : 0; 157 mLastUpdate = SystemClock.elapsedRealtime(); 158 mProgress = 0.0f; 159 mState = STATE_NEW; 160 mUris = pendingTransfer.uris == null 161 ? new ArrayList<Uri>() 162 : new ArrayList<Uri>(Arrays.asList(pendingTransfer.uris)); 163 mTransferMimeTypes = new ArrayList<String>(); 164 mMimeTypes = new HashMap<String, String>(); 165 mPaths = new ArrayList<String>(); 166 mMediaUris = new HashMap<String, Uri>(); 167 mCancelIntent = buildCancelIntent(); 168 mUrisScanned = 0; 169 mCurrentCount = 0; 170 mSuccessCount = 0; 171 mOutgoingUris = pendingTransfer.uris; 172 mHandler = new Handler(Looper.getMainLooper(), this); 173 mHandler.sendEmptyMessageDelayed(MSG_TRANSFER_TIMEOUT, ALIVE_CHECK_MS); 174 mNotificationManager = (NotificationManager) mContext.getSystemService( 175 Context.NOTIFICATION_SERVICE); 176 NotificationChannel notificationChannel = new NotificationChannel( 177 BEAM_NOTIFICATION_CHANNEL, mContext.getString(R.string.app_name), 178 NotificationManager.IMPORTANCE_HIGH); 179 mNotificationManager.createNotificationChannel(notificationChannel); 180 } 181 allowlistOppDevice(BluetoothDevice device)182 void allowlistOppDevice(BluetoothDevice device) { 183 if (DBG) Log.d(TAG, "Allowlist " + device + " for BT OPP"); 184 Intent intent = new Intent(ACTION_ALLOWLIST_DEVICE); 185 intent.setPackage(mContext.getString(R.string.bluetooth_package)); 186 intent.putExtra(BluetoothDevice.EXTRA_DEVICE, device); 187 intent.addFlags(Intent.FLAG_RECEIVER_FOREGROUND); 188 mContext.sendBroadcastAsUser(intent, UserHandle.CURRENT); 189 } 190 start()191 public void start() { 192 if (mStartTime > 0) { 193 // already started 194 return; 195 } 196 197 mStartTime = System.currentTimeMillis(); 198 199 if (!mIncoming) { 200 if (mDataLinkType == BeamTransferRecord.DATA_LINK_TYPE_BLUETOOTH) { 201 new BluetoothOppHandover(mContext, mRemoteDevice, mUris, mRemoteActivating).start(); 202 } 203 } 204 } 205 updateFileProgress(float progress)206 public void updateFileProgress(float progress) { 207 if (!isRunning()) return; // Ignore when we're no longer running 208 209 mHandler.removeMessages(MSG_NEXT_TRANSFER_TIMER); 210 211 this.mProgress = progress; 212 213 // We're still receiving data from this device - keep it in 214 // the allowlist for a while longer 215 if (mIncoming && mRemoteDevice != null) allowlistOppDevice(mRemoteDevice); 216 217 updateStateAndNotification(STATE_IN_PROGRESS); 218 } 219 setBluetoothTransferId(int id)220 public synchronized void setBluetoothTransferId(int id) { 221 if (mBluetoothTransferId == -1 && id != -1) { 222 mBluetoothTransferId = id; 223 if (mState == STATE_CANCELLING) { 224 sendBluetoothCancelIntentAndUpdateState(); 225 } 226 } 227 } 228 finishTransfer(boolean success, Uri uri, String mimeType)229 public void finishTransfer(boolean success, Uri uri, String mimeType) { 230 if (!isRunning()) return; // Ignore when we're no longer running 231 232 mCurrentCount++; 233 if (success && uri != null) { 234 mSuccessCount++; 235 if (DBG) Log.d(TAG, "Transfer success, uri " + uri + " mimeType " + mimeType); 236 mProgress = 0.0f; 237 if (mimeType == null) { 238 mimeType = MimeTypeUtil.getMimeTypeForUri(mContext, uri); 239 } 240 if (mimeType != null) { 241 mUris.add(uri); 242 mTransferMimeTypes.add(mimeType); 243 } else { 244 if (DBG) Log.d(TAG, "Could not get mimeType for file."); 245 } 246 } else { 247 Log.e(TAG, "Handover transfer failed"); 248 // Do wait to see if there's another file coming. 249 } 250 mHandler.removeMessages(MSG_NEXT_TRANSFER_TIMER); 251 if (mCurrentCount == mTotalCount) { 252 if (mIncoming) { 253 processFiles(); 254 } else { 255 updateStateAndNotification(mSuccessCount > 0 ? STATE_SUCCESS : STATE_FAILED); 256 } 257 } else { 258 mHandler.sendEmptyMessageDelayed(MSG_NEXT_TRANSFER_TIMER, WAIT_FOR_NEXT_TRANSFER_MS); 259 updateStateAndNotification(STATE_W4_NEXT_TRANSFER); 260 } 261 } 262 isRunning()263 public boolean isRunning() { 264 if (mState != STATE_NEW && mState != STATE_IN_PROGRESS && mState != STATE_W4_NEXT_TRANSFER 265 && mState != STATE_CANCELLING) { 266 return false; 267 } else { 268 return true; 269 } 270 } 271 setObjectCount(int objectCount)272 public void setObjectCount(int objectCount) { 273 mTotalCount = objectCount; 274 } 275 cancel()276 void cancel() { 277 if (!isRunning()) return; 278 279 // Delete all files received so far 280 for (Uri uri : mUris) { 281 File file = new File(uri.getPath()); 282 if (file.exists()) file.delete(); 283 } 284 285 if (mBluetoothTransferId != -1) { 286 // we know the ID, we can cancel immediately 287 sendBluetoothCancelIntentAndUpdateState(); 288 } else { 289 updateStateAndNotification(STATE_CANCELLING); 290 } 291 292 } 293 sendBluetoothCancelIntentAndUpdateState()294 private void sendBluetoothCancelIntentAndUpdateState() { 295 Intent cancelIntent = new Intent(ACTION_STOP_BLUETOOTH_TRANSFER); 296 cancelIntent.setPackage(mContext.getString(R.string.bluetooth_package)); 297 cancelIntent.putExtra(BeamStatusReceiver.EXTRA_TRANSFER_ID, mBluetoothTransferId); 298 mContext.sendBroadcast(cancelIntent); 299 updateStateAndNotification(STATE_CANCELLED); 300 } 301 updateNotification()302 void updateNotification() { 303 Builder notBuilder = new Notification.Builder(mContext, BEAM_NOTIFICATION_CHANNEL); 304 notBuilder.setColor(mContext.getResources().getColor( 305 com.android.internal.R.color.system_notification_accent_color)); 306 notBuilder.setWhen(mStartTime); 307 notBuilder.setVisibility(Notification.VISIBILITY_PUBLIC); 308 notBuilder.setOnlyAlertOnce(true); 309 String beamString; 310 if (mIncoming) { 311 beamString = mContext.getString(R.string.beam_progress); 312 } else { 313 beamString = mContext.getString(R.string.beam_outgoing); 314 } 315 if (mState == STATE_NEW || mState == STATE_IN_PROGRESS || 316 mState == STATE_W4_NEXT_TRANSFER || mState == STATE_W4_MEDIA_SCANNER) { 317 notBuilder.setAutoCancel(false); 318 notBuilder.setSmallIcon(mIncoming ? android.R.drawable.stat_sys_download : 319 android.R.drawable.stat_sys_upload); 320 notBuilder.setTicker(beamString); 321 notBuilder.setContentTitle(beamString); 322 notBuilder.addAction(R.drawable.ic_menu_cancel_holo_dark, 323 mContext.getString(R.string.cancel), mCancelIntent); 324 float progress = 0; 325 if (mTotalCount > 0) { 326 float progressUnit = 1.0f / mTotalCount; 327 progress = (float) mCurrentCount * progressUnit + mProgress * progressUnit; 328 } 329 if (mTotalCount > 0 && progress > 0) { 330 notBuilder.setProgress(100, (int) (100 * progress), false); 331 } else { 332 notBuilder.setProgress(100, 0, true); 333 } 334 } else if (mState == STATE_SUCCESS) { 335 notBuilder.setAutoCancel(true); 336 notBuilder.setSmallIcon(mIncoming ? android.R.drawable.stat_sys_download_done : 337 android.R.drawable.stat_sys_upload_done); 338 notBuilder.setTicker(mContext.getString(R.string.beam_complete)); 339 notBuilder.setContentTitle(mContext.getString(R.string.beam_complete)); 340 341 if (mIncoming) { 342 notBuilder.setContentText(mContext.getString(R.string.beam_tap_to_view)); 343 Intent viewIntent = buildViewIntent(); 344 PendingIntent contentIntent = PendingIntent.getActivity( 345 mContext, mTransferId, viewIntent, 346 PendingIntent.FLAG_ONE_SHOT | PendingIntent.FLAG_IMMUTABLE, 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.setPackage("com.android.nfc"); 497 intent.putExtra(BeamStatusReceiver.EXTRA_ADDRESS, mRemoteDevice.getAddress()); 498 intent.putExtra(BeamStatusReceiver.EXTRA_INCOMING, mIncoming ? 499 BeamStatusReceiver.DIRECTION_INCOMING : BeamStatusReceiver.DIRECTION_OUTGOING); 500 PendingIntent pi = PendingIntent.getBroadcast(mContext, mTransferId, intent, 501 PendingIntent.FLAG_ONE_SHOT); 502 503 return pi; 504 } 505 checkMediaStorage(File path)506 static boolean checkMediaStorage(File path) { 507 if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) { 508 if (!path.isDirectory() && !path.mkdir()) { 509 Log.e(TAG, "Not dir or not mkdir " + path.getAbsolutePath()); 510 return false; 511 } 512 return true; 513 } else { 514 Log.e(TAG, "External storage not mounted, can't store file."); 515 return false; 516 } 517 } 518 generateUniqueDestination(String path, String fileName)519 static File generateUniqueDestination(String path, String fileName) { 520 int dotIndex = fileName.lastIndexOf("."); 521 String extension = null; 522 String fileNameWithoutExtension = null; 523 if (dotIndex < 0) { 524 extension = ""; 525 fileNameWithoutExtension = fileName; 526 } else { 527 extension = fileName.substring(dotIndex); 528 fileNameWithoutExtension = fileName.substring(0, dotIndex); 529 } 530 File dstFile = new File(path + File.separator + fileName); 531 int count = 0; 532 while (dstFile.exists()) { 533 dstFile = new File(path + File.separator + fileNameWithoutExtension + "-" + 534 Integer.toString(count) + extension); 535 count++; 536 } 537 return dstFile; 538 } 539 generateMultiplePath(String beamRoot)540 static File generateMultiplePath(String beamRoot) { 541 // Generate a unique directory with the date 542 String format = "yyyy-MM-dd"; 543 SimpleDateFormat sdf = new SimpleDateFormat(format, Locale.US); 544 String newPath = beamRoot + "beam-" + sdf.format(new Date()); 545 File newFile = new File(newPath); 546 int count = 0; 547 while (newFile.exists()) { 548 newPath = beamRoot + "beam-" + sdf.format(new Date()) + "-" + 549 Integer.toString(count); 550 newFile = new File(newPath); 551 count++; 552 } 553 return newFile; 554 } 555 } 556