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_ALLOWLIST_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 allowlistOppDevice(BluetoothDevice device)183 void allowlistOppDevice(BluetoothDevice device) { 184 if (DBG) Log.d(TAG, "Allowlist " + device + " for BT OPP"); 185 Intent intent = new Intent(ACTION_ALLOWLIST_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 allowlist for a while longer 216 if (mIncoming && mRemoteDevice != null) allowlistOppDevice(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, 347 PendingIntent.FLAG_ONE_SHOT | PendingIntent.FLAG_IMMUTABLE, null); 348 349 notBuilder.setContentIntent(contentIntent); 350 } 351 } else if (mState == STATE_FAILED) { 352 notBuilder.setAutoCancel(false); 353 notBuilder.setSmallIcon(mIncoming ? android.R.drawable.stat_sys_download_done : 354 android.R.drawable.stat_sys_upload_done); 355 notBuilder.setTicker(mContext.getString(R.string.beam_failed)); 356 notBuilder.setContentTitle(mContext.getString(R.string.beam_failed)); 357 } else if (mState == STATE_CANCELLED || mState == STATE_CANCELLING) { 358 notBuilder.setAutoCancel(false); 359 notBuilder.setSmallIcon(mIncoming ? android.R.drawable.stat_sys_download_done : 360 android.R.drawable.stat_sys_upload_done); 361 notBuilder.setTicker(mContext.getString(R.string.beam_canceled)); 362 notBuilder.setContentTitle(mContext.getString(R.string.beam_canceled)); 363 } else { 364 return; 365 } 366 367 mNotificationManager.notify(null, mTransferId, notBuilder.build()); 368 } 369 updateStateAndNotification(int newState)370 void updateStateAndNotification(int newState) { 371 this.mState = newState; 372 this.mLastUpdate = SystemClock.elapsedRealtime(); 373 374 mHandler.removeMessages(MSG_TRANSFER_TIMEOUT); 375 if (isRunning()) { 376 // Update timeout timer if we're still running 377 mHandler.sendEmptyMessageDelayed(MSG_TRANSFER_TIMEOUT, ALIVE_CHECK_MS); 378 } 379 380 updateNotification(); 381 382 if ((mState == STATE_SUCCESS || mState == STATE_FAILED || mState == STATE_CANCELLED) 383 && !mCalledBack) { 384 mCalledBack = true; 385 // Notify that we're done with this transfer 386 mCallback.onTransferComplete(this, mState == STATE_SUCCESS); 387 } 388 } 389 processFiles()390 void processFiles() { 391 // Check the amount of files we received in this transfer; 392 // If more than one, create a separate directory for it. 393 String extRoot = Environment.getExternalStorageDirectory().getPath(); 394 File beamPath = new File(extRoot + "/" + BEAM_DIR); 395 396 if (!checkMediaStorage(beamPath) || mUris.size() == 0) { 397 Log.e(TAG, "Media storage not valid or no uris received."); 398 updateStateAndNotification(STATE_FAILED); 399 return; 400 } 401 402 if (mUris.size() > 1) { 403 beamPath = generateMultiplePath(extRoot + "/" + BEAM_DIR + "/"); 404 if (!beamPath.isDirectory() && !beamPath.mkdir()) { 405 Log.e(TAG, "Failed to create multiple path " + beamPath.toString()); 406 updateStateAndNotification(STATE_FAILED); 407 return; 408 } 409 } 410 411 for (int i = 0; i < mUris.size(); i++) { 412 Uri uri = mUris.get(i); 413 String mimeType = mTransferMimeTypes.get(i); 414 415 File srcFile = new File(uri.getPath()); 416 417 File dstFile = generateUniqueDestination(beamPath.getAbsolutePath(), 418 uri.getLastPathSegment()); 419 Log.d(TAG, "Renaming from " + srcFile); 420 if (!srcFile.renameTo(dstFile)) { 421 if (DBG) Log.d(TAG, "Failed to rename from " + srcFile + " to " + dstFile); 422 srcFile.delete(); 423 return; 424 } else { 425 mPaths.add(dstFile.getAbsolutePath()); 426 mMimeTypes.put(dstFile.getAbsolutePath(), mimeType); 427 if (DBG) Log.d(TAG, "Did successful rename from " + srcFile + " to " + dstFile); 428 } 429 } 430 431 // We can either add files to the media provider, or provide an ACTION_VIEW 432 // intent to the file directly. We base this decision on the mime type 433 // of the first file; if it's media the platform can deal with, 434 // use the media provider, if it's something else, just launch an ACTION_VIEW 435 // on the file. 436 String mimeType = mMimeTypes.get(mPaths.get(0)); 437 if (mimeType.startsWith("image/") || mimeType.startsWith("video/") || 438 mimeType.startsWith("audio/")) { 439 String[] arrayPaths = new String[mPaths.size()]; 440 MediaScannerConnection.scanFile(mContext, mPaths.toArray(arrayPaths), null, this); 441 updateStateAndNotification(STATE_W4_MEDIA_SCANNER); 442 } else { 443 // We're done. 444 updateStateAndNotification(STATE_SUCCESS); 445 } 446 447 } 448 handleMessage(Message msg)449 public boolean handleMessage(Message msg) { 450 if (msg.what == MSG_NEXT_TRANSFER_TIMER) { 451 // We didn't receive a new transfer in time, finalize this one 452 if (mIncoming) { 453 processFiles(); 454 } else { 455 updateStateAndNotification(mSuccessCount > 0 ? STATE_SUCCESS : STATE_FAILED); 456 } 457 return true; 458 } else if (msg.what == MSG_TRANSFER_TIMEOUT) { 459 // No update on this transfer for a while, fail it. 460 if (DBG) Log.d(TAG, "Transfer timed out for id: " + Integer.toString(mTransferId)); 461 updateStateAndNotification(STATE_FAILED); 462 } 463 return false; 464 } 465 onScanCompleted(String path, Uri uri)466 public synchronized void onScanCompleted(String path, Uri uri) { 467 if (DBG) Log.d(TAG, "Scan completed, path " + path + " uri " + uri); 468 if (uri != null) { 469 mMediaUris.put(path, uri); 470 } 471 mUrisScanned++; 472 if (mUrisScanned == mPaths.size()) { 473 // We're done 474 updateStateAndNotification(STATE_SUCCESS); 475 } 476 } 477 478 buildViewIntent()479 Intent buildViewIntent() { 480 if (mPaths.size() == 0) return null; 481 482 Intent viewIntent = new Intent(Intent.ACTION_VIEW); 483 484 String filePath = mPaths.get(0); 485 Uri mediaUri = mMediaUris.get(filePath); 486 Uri uri = mediaUri != null ? mediaUri : 487 FileProvider.getUriForFile(mContext, "com.google.android.nfc.fileprovider", 488 new File(filePath)); 489 viewIntent.setDataAndTypeAndNormalize(uri, mMimeTypes.get(filePath)); 490 viewIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK | 491 Intent.FLAG_GRANT_READ_URI_PERMISSION | Intent.FLAG_GRANT_WRITE_URI_PERMISSION); 492 return viewIntent; 493 } 494 buildCancelIntent()495 PendingIntent buildCancelIntent() { 496 Intent intent = new Intent(BeamStatusReceiver.ACTION_CANCEL_HANDOVER_TRANSFER); 497 intent.setPackage("com.android.nfc"); 498 intent.putExtra(BeamStatusReceiver.EXTRA_ADDRESS, mRemoteDevice.getAddress()); 499 intent.putExtra(BeamStatusReceiver.EXTRA_INCOMING, mIncoming ? 500 BeamStatusReceiver.DIRECTION_INCOMING : BeamStatusReceiver.DIRECTION_OUTGOING); 501 PendingIntent pi = PendingIntent.getBroadcast(mContext, mTransferId, intent, 502 PendingIntent.FLAG_ONE_SHOT); 503 504 return pi; 505 } 506 checkMediaStorage(File path)507 static boolean checkMediaStorage(File path) { 508 if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) { 509 if (!path.isDirectory() && !path.mkdir()) { 510 Log.e(TAG, "Not dir or not mkdir " + path.getAbsolutePath()); 511 return false; 512 } 513 return true; 514 } else { 515 Log.e(TAG, "External storage not mounted, can't store file."); 516 return false; 517 } 518 } 519 generateUniqueDestination(String path, String fileName)520 static File generateUniqueDestination(String path, String fileName) { 521 int dotIndex = fileName.lastIndexOf("."); 522 String extension = null; 523 String fileNameWithoutExtension = null; 524 if (dotIndex < 0) { 525 extension = ""; 526 fileNameWithoutExtension = fileName; 527 } else { 528 extension = fileName.substring(dotIndex); 529 fileNameWithoutExtension = fileName.substring(0, dotIndex); 530 } 531 File dstFile = new File(path + File.separator + fileName); 532 int count = 0; 533 while (dstFile.exists()) { 534 dstFile = new File(path + File.separator + fileNameWithoutExtension + "-" + 535 Integer.toString(count) + extension); 536 count++; 537 } 538 return dstFile; 539 } 540 generateMultiplePath(String beamRoot)541 static File generateMultiplePath(String beamRoot) { 542 // Generate a unique directory with the date 543 String format = "yyyy-MM-dd"; 544 SimpleDateFormat sdf = new SimpleDateFormat(format, Locale.US); 545 String newPath = beamRoot + "beam-" + sdf.format(new Date()); 546 File newFile = new File(newPath); 547 int count = 0; 548 while (newFile.exists()) { 549 newPath = beamRoot + "beam-" + sdf.format(new Date()) + "-" + 550 Integer.toString(count); 551 newFile = new File(newPath); 552 count++; 553 } 554 return newFile; 555 } 556 } 557