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