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 android.support.v4.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 BLUETOOTH_PACKAGE = "com.android.bluetooth";
109 
110     static final String ACTION_WHITELIST_DEVICE =
111             "android.btopp.intent.action.WHITELIST_DEVICE";
112 
113     static final String ACTION_STOP_BLUETOOTH_TRANSFER =
114             "android.btopp.intent.action.STOP_HANDOVER_TRANSFER";
115 
116     final boolean mIncoming;  // whether this is an incoming transfer
117 
118     final int mTransferId; // Unique ID of this transfer used for notifications
119     int mBluetoothTransferId; // ID of this transfer in Bluetooth namespace
120 
121     final PendingIntent mCancelIntent;
122     final Context mContext;
123     final Handler mHandler;
124     final NotificationManager mNotificationManager;
125     final BluetoothDevice mRemoteDevice;
126     final Callback mCallback;
127     final boolean mRemoteActivating;
128 
129     // Variables below are only accessed on the main thread
130     int mState;
131     int mCurrentCount;
132     int mSuccessCount;
133     int mTotalCount;
134     int mDataLinkType;
135     boolean mCalledBack;
136     Long mLastUpdate; // Last time an event occurred for this transfer
137     float mProgress; // Progress in range [0..1]
138     ArrayList<Uri> mUris; // Received uris from transport
139     ArrayList<String> mTransferMimeTypes; // Mime-types received from transport
140     Uri[] mOutgoingUris; // URIs to send
141     ArrayList<String> mPaths; // Raw paths on the filesystem for Beam-stored files
142     HashMap<String, String> mMimeTypes; // Mime-types associated with each path
143     HashMap<String, Uri> mMediaUris; // URIs found by the media scanner for each path
144     int mUrisScanned;
145     Long mStartTime;
146 
BeamTransferManager(Context context, Callback callback, BeamTransferRecord pendingTransfer, boolean incoming)147     public BeamTransferManager(Context context, Callback callback,
148                                BeamTransferRecord pendingTransfer, boolean incoming) {
149         mContext = context;
150         mCallback = callback;
151         mRemoteDevice = pendingTransfer.remoteDevice;
152         mIncoming = incoming;
153         mTransferId = pendingTransfer.id;
154         mBluetoothTransferId = -1;
155         mDataLinkType = pendingTransfer.dataLinkType;
156         mRemoteActivating = pendingTransfer.remoteActivating;
157         mStartTime = 0L;
158         // For incoming transfers, count can be set later
159         mTotalCount = (pendingTransfer.uris != null) ? pendingTransfer.uris.length : 0;
160         mLastUpdate = SystemClock.elapsedRealtime();
161         mProgress = 0.0f;
162         mState = STATE_NEW;
163         mUris = pendingTransfer.uris == null
164                 ? new ArrayList<Uri>()
165                 : new ArrayList<Uri>(Arrays.asList(pendingTransfer.uris));
166         mTransferMimeTypes = new ArrayList<String>();
167         mMimeTypes = new HashMap<String, String>();
168         mPaths = new ArrayList<String>();
169         mMediaUris = new HashMap<String, Uri>();
170         mCancelIntent = buildCancelIntent();
171         mUrisScanned = 0;
172         mCurrentCount = 0;
173         mSuccessCount = 0;
174         mOutgoingUris = pendingTransfer.uris;
175         mHandler = new Handler(Looper.getMainLooper(), this);
176         mHandler.sendEmptyMessageDelayed(MSG_TRANSFER_TIMEOUT, ALIVE_CHECK_MS);
177         mNotificationManager = (NotificationManager) mContext.getSystemService(
178                 Context.NOTIFICATION_SERVICE);
179         NotificationChannel notificationChannel = new NotificationChannel(
180                 BEAM_NOTIFICATION_CHANNEL, mContext.getString(R.string.app_name),
181                 NotificationManager.IMPORTANCE_HIGH);
182         mNotificationManager.createNotificationChannel(notificationChannel);
183     }
184 
whitelistOppDevice(BluetoothDevice device)185     void whitelistOppDevice(BluetoothDevice device) {
186         if (DBG) Log.d(TAG, "Whitelisting " + device + " for BT OPP");
187         Intent intent = new Intent(ACTION_WHITELIST_DEVICE);
188         intent.setPackage(BLUETOOTH_PACKAGE);
189         intent.putExtra(BluetoothDevice.EXTRA_DEVICE, device);
190         mContext.sendBroadcastAsUser(intent, UserHandle.CURRENT);
191     }
192 
start()193     public void start() {
194         if (mStartTime > 0) {
195             // already started
196             return;
197         }
198 
199         mStartTime = System.currentTimeMillis();
200 
201         if (!mIncoming) {
202             if (mDataLinkType == BeamTransferRecord.DATA_LINK_TYPE_BLUETOOTH) {
203                 new BluetoothOppHandover(mContext, mRemoteDevice, mUris, mRemoteActivating).start();
204             }
205         }
206     }
207 
updateFileProgress(float progress)208     public void updateFileProgress(float progress) {
209         if (!isRunning()) return; // Ignore when we're no longer running
210 
211         mHandler.removeMessages(MSG_NEXT_TRANSFER_TIMER);
212 
213         this.mProgress = progress;
214 
215         // We're still receiving data from this device - keep it in
216         // the whitelist for a while longer
217         if (mIncoming && mRemoteDevice != null) whitelistOppDevice(mRemoteDevice);
218 
219         updateStateAndNotification(STATE_IN_PROGRESS);
220     }
221 
setBluetoothTransferId(int id)222     public synchronized void setBluetoothTransferId(int id) {
223         if (mBluetoothTransferId == -1 && id != -1) {
224             mBluetoothTransferId = id;
225             if (mState == STATE_CANCELLING) {
226                 sendBluetoothCancelIntentAndUpdateState();
227             }
228         }
229     }
230 
finishTransfer(boolean success, Uri uri, String mimeType)231     public void finishTransfer(boolean success, Uri uri, String mimeType) {
232         if (!isRunning()) return; // Ignore when we're no longer running
233 
234         mCurrentCount++;
235         if (success && uri != null) {
236             mSuccessCount++;
237             if (DBG) Log.d(TAG, "Transfer success, uri " + uri + " mimeType " + mimeType);
238             mProgress = 0.0f;
239             if (mimeType == null) {
240                 mimeType = MimeTypeUtil.getMimeTypeForUri(mContext, uri);
241             }
242             if (mimeType != null) {
243                 mUris.add(uri);
244                 mTransferMimeTypes.add(mimeType);
245             } else {
246                 if (DBG) Log.d(TAG, "Could not get mimeType for file.");
247             }
248         } else {
249             Log.e(TAG, "Handover transfer failed");
250             // Do wait to see if there's another file coming.
251         }
252         mHandler.removeMessages(MSG_NEXT_TRANSFER_TIMER);
253         if (mCurrentCount == mTotalCount) {
254             if (mIncoming) {
255                 processFiles();
256             } else {
257                 updateStateAndNotification(mSuccessCount > 0 ? STATE_SUCCESS : STATE_FAILED);
258             }
259         } else {
260             mHandler.sendEmptyMessageDelayed(MSG_NEXT_TRANSFER_TIMER, WAIT_FOR_NEXT_TRANSFER_MS);
261             updateStateAndNotification(STATE_W4_NEXT_TRANSFER);
262         }
263     }
264 
isRunning()265     public boolean isRunning() {
266         if (mState != STATE_NEW && mState != STATE_IN_PROGRESS && mState != STATE_W4_NEXT_TRANSFER
267             && mState != STATE_CANCELLING) {
268             return false;
269         } else {
270             return true;
271         }
272     }
273 
setObjectCount(int objectCount)274     public void setObjectCount(int objectCount) {
275         mTotalCount = objectCount;
276     }
277 
cancel()278     void cancel() {
279         if (!isRunning()) return;
280 
281         // Delete all files received so far
282         for (Uri uri : mUris) {
283             File file = new File(uri.getPath());
284             if (file.exists()) file.delete();
285         }
286 
287         if (mBluetoothTransferId != -1) {
288             // we know the ID, we can cancel immediately
289             sendBluetoothCancelIntentAndUpdateState();
290         } else {
291             updateStateAndNotification(STATE_CANCELLING);
292         }
293 
294     }
295 
sendBluetoothCancelIntentAndUpdateState()296     private void sendBluetoothCancelIntentAndUpdateState() {
297         Intent cancelIntent = new Intent(ACTION_STOP_BLUETOOTH_TRANSFER);
298         cancelIntent.setPackage(BLUETOOTH_PACKAGE);
299         cancelIntent.putExtra(BeamStatusReceiver.EXTRA_TRANSFER_ID, mBluetoothTransferId);
300         mContext.sendBroadcast(cancelIntent);
301         updateStateAndNotification(STATE_CANCELLED);
302     }
303 
updateNotification()304     void updateNotification() {
305         Builder notBuilder = new Notification.Builder(mContext, BEAM_NOTIFICATION_CHANNEL);
306         notBuilder.setColor(mContext.getResources().getColor(
307                 com.android.internal.R.color.system_notification_accent_color));
308         notBuilder.setWhen(mStartTime);
309         notBuilder.setVisibility(Notification.VISIBILITY_PUBLIC);
310         notBuilder.setOnlyAlertOnce(true);
311         String beamString;
312         if (mIncoming) {
313             beamString = mContext.getString(R.string.beam_progress);
314         } else {
315             beamString = mContext.getString(R.string.beam_outgoing);
316         }
317         if (mState == STATE_NEW || mState == STATE_IN_PROGRESS ||
318                 mState == STATE_W4_NEXT_TRANSFER || mState == STATE_W4_MEDIA_SCANNER) {
319             notBuilder.setAutoCancel(false);
320             notBuilder.setSmallIcon(mIncoming ? android.R.drawable.stat_sys_download :
321                     android.R.drawable.stat_sys_upload);
322             notBuilder.setTicker(beamString);
323             notBuilder.setContentTitle(beamString);
324             notBuilder.addAction(R.drawable.ic_menu_cancel_holo_dark,
325                     mContext.getString(R.string.cancel), mCancelIntent);
326             float progress = 0;
327             if (mTotalCount > 0) {
328                 float progressUnit = 1.0f / mTotalCount;
329                 progress = (float) mCurrentCount * progressUnit + mProgress * progressUnit;
330             }
331             if (mTotalCount > 0 && progress > 0) {
332                 notBuilder.setProgress(100, (int) (100 * progress), false);
333             } else {
334                 notBuilder.setProgress(100, 0, true);
335             }
336         } else if (mState == STATE_SUCCESS) {
337             notBuilder.setAutoCancel(true);
338             notBuilder.setSmallIcon(mIncoming ? android.R.drawable.stat_sys_download_done :
339                     android.R.drawable.stat_sys_upload_done);
340             notBuilder.setTicker(mContext.getString(R.string.beam_complete));
341             notBuilder.setContentTitle(mContext.getString(R.string.beam_complete));
342 
343             if (mIncoming) {
344                 notBuilder.setContentText(mContext.getString(R.string.beam_tap_to_view));
345                 Intent viewIntent = buildViewIntent();
346                 PendingIntent contentIntent = PendingIntent.getActivity(
347                         mContext, mTransferId, viewIntent, 0, 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.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 
557