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