summaryrefslogtreecommitdiffstats
path: root/src/com/android/nfc/handover/HandoverTransfer.java
blob: 98b59a6911d8730cf0d57413aa3b83ffa03c5259 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
package com.android.nfc.handover;

import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Notification.Builder;
import android.bluetooth.BluetoothDevice;
import android.content.ContentResolver;
import android.content.Context;
import android.content.Intent;
import android.media.MediaScannerConnection;
import android.net.Uri;
import android.os.Environment;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.os.SystemClock;
import android.os.UserHandle;
import android.util.Log;

import com.android.nfc.R;

import java.io.File;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;

/**
 * A HandoverTransfer object represents a set of files
 * that were received through NFC connection handover
 * from the same source address.
 *
 * For Bluetooth, files are received through OPP, and
 * we have no knowledge how many files will be transferred
 * as part of a single transaction.
 * Hence, a transfer has a notion of being "alive": if
 * the last update to a transfer was within WAIT_FOR_NEXT_TRANSFER_MS
 * milliseconds, we consider a new file transfer from the
 * same source address as part of the same transfer.
 * The corresponding URIs will be grouped in a single folder.
 *
 */
public class HandoverTransfer implements Handler.Callback,
        MediaScannerConnection.OnScanCompletedListener {

    interface Callback {
        void onTransferComplete(HandoverTransfer transfer, boolean success);
    };

    static final String TAG = "HandoverTransfer";

    static final Boolean DBG = true;

    // In the states below we still accept new file transfer
    static final int STATE_NEW = 0;
    static final int STATE_IN_PROGRESS = 1;
    static final int STATE_W4_NEXT_TRANSFER = 2;

    // In the states below no new files are accepted.
    static final int STATE_W4_MEDIA_SCANNER = 3;
    static final int STATE_FAILED = 4;
    static final int STATE_SUCCESS = 5;
    static final int STATE_CANCELLED = 6;

    static final int MSG_NEXT_TRANSFER_TIMER = 0;
    static final int MSG_TRANSFER_TIMEOUT = 1;

    // We need to receive an update within this time period
    // to still consider this transfer to be "alive" (ie
    // a reason to keep the handover transport enabled).
    static final int ALIVE_CHECK_MS = 20000;

    // The amount of time to wait for a new transfer
    // once the current one completes.
    static final int WAIT_FOR_NEXT_TRANSFER_MS = 4000;

    static final String BEAM_DIR = "beam";

    final boolean mIncoming;  // whether this is an incoming transfer
    final int mTransferId; // Unique ID of this transfer used for notifications
    final PendingIntent mCancelIntent;
    final Context mContext;
    final Handler mHandler;
    final NotificationManager mNotificationManager;
    final BluetoothDevice mRemoteDevice;
    final Callback mCallback;

    // Variables below are only accessed on the main thread
    int mState;
    boolean mCalledBack;
    Long mLastUpdate; // Last time an event occurred for this transfer
    float mProgress; // Progress in range [0..1]
    ArrayList<Uri> mBtUris; // Received uris from Bluetooth OPP
    ArrayList<String> mBtMimeTypes; // Mime-types received from Bluetooth OPP

    ArrayList<String> mPaths; // Raw paths on the filesystem for Beam-stored files
    HashMap<String, String> mMimeTypes; // Mime-types associated with each path
    HashMap<String, Uri> mMediaUris; // URIs found by the media scanner for each path
    int mUrisScanned;

    public HandoverTransfer(Context context, Callback callback,
            PendingHandoverTransfer pendingTransfer) {
        mContext = context;
        mCallback = callback;
        mRemoteDevice = pendingTransfer.remoteDevice;
        mIncoming = pendingTransfer.incoming;
        mTransferId = pendingTransfer.id;
        mLastUpdate = SystemClock.elapsedRealtime();
        mProgress = 0.0f;
        mState = STATE_NEW;
        mBtUris = new ArrayList<Uri>();
        mBtMimeTypes = new ArrayList<String>();
        mPaths = new ArrayList<String>();
        mMimeTypes = new HashMap<String, String>();
        mMediaUris = new HashMap<String, Uri>();
        mCancelIntent = buildCancelIntent();
        mUrisScanned = 0;

        mHandler = new Handler(Looper.getMainLooper(), this);
        mHandler.sendEmptyMessageDelayed(MSG_TRANSFER_TIMEOUT, ALIVE_CHECK_MS);
        mNotificationManager = (NotificationManager) mContext.getSystemService(
                Context.NOTIFICATION_SERVICE);
    }

    void whitelistOppDevice(BluetoothDevice device) {
        if (DBG) Log.d(TAG, "Whitelisting " + device + " for BT OPP");
        Intent intent = new Intent(HandoverManager.ACTION_WHITELIST_DEVICE);
        intent.putExtra(BluetoothDevice.EXTRA_DEVICE, device);
        mContext.sendBroadcastAsUser(intent, UserHandle.CURRENT);
    }

    public void updateFileProgress(float progress) {
        if (!isRunning()) return; // Ignore when we're no longer running

        mHandler.removeMessages(MSG_NEXT_TRANSFER_TIMER);

        this.mProgress = progress;

        // We're still receiving data from this device - keep it in
        // the whitelist for a while longer
        if (mIncoming) whitelistOppDevice(mRemoteDevice);

        updateStateAndNotification(STATE_IN_PROGRESS);
    }

    public void finishTransfer(boolean success, Uri uri, String mimeType) {
        if (!isRunning()) return; // Ignore when we're no longer running

        if (success && uri != null) {
            if (DBG) Log.d(TAG, "Transfer success, uri " + uri + " mimeType " + mimeType);
            this.mProgress = 1.0f;
            if (mimeType == null) {
                mimeType = BluetoothOppHandover.getMimeTypeForUri(mContext, uri);
            }
            if (mimeType != null) {
                mBtUris.add(uri);
                mBtMimeTypes.add(mimeType);
            } else {
                if (DBG) Log.d(TAG, "Could not get mimeType for file.");
            }
        } else {
            Log.e(TAG, "Handover transfer failed");
            // Do wait to see if there's another file coming.
        }
        mHandler.removeMessages(MSG_NEXT_TRANSFER_TIMER);
        mHandler.sendEmptyMessageDelayed(MSG_NEXT_TRANSFER_TIMER, WAIT_FOR_NEXT_TRANSFER_MS);
        updateStateAndNotification(STATE_W4_NEXT_TRANSFER);
    }

    public boolean isRunning() {
        if (mState != STATE_NEW && mState != STATE_IN_PROGRESS && mState != STATE_W4_NEXT_TRANSFER) {
            return false;
        } else {
            return true;
        }
    }

    void cancel() {
        if (!isRunning()) return;

        // Delete all files received so far
        for (Uri uri : mBtUris) {
            File file = new File(uri.getPath());
            if (file.exists()) file.delete();
        }

        updateStateAndNotification(STATE_CANCELLED);
    }

    void updateNotification() {
        if (!mIncoming) return; // No notifications for outgoing transfers

        Builder notBuilder = new Notification.Builder(mContext);

        if (mState == STATE_NEW || mState == STATE_IN_PROGRESS ||
                mState == STATE_W4_NEXT_TRANSFER || mState == STATE_W4_MEDIA_SCANNER) {
            notBuilder.setAutoCancel(false);
            notBuilder.setSmallIcon(android.R.drawable.stat_sys_download);
            notBuilder.setTicker(mContext.getString(R.string.beam_progress));
            notBuilder.setContentTitle(mContext.getString(R.string.beam_progress));
            notBuilder.addAction(R.drawable.ic_menu_cancel_holo_dark,
                    mContext.getString(R.string.cancel), mCancelIntent);
            notBuilder.setDeleteIntent(mCancelIntent);
            // We do have progress indication on a per-file basis, but in a multi-file
            // transfer we don't know the total progress. So for now, just show an
            // indeterminate progress bar.
            notBuilder.setProgress(100, 0, true);
        } else if (mState == STATE_SUCCESS) {
            notBuilder.setAutoCancel(true);
            notBuilder.setSmallIcon(android.R.drawable.stat_sys_download_done);
            notBuilder.setTicker(mContext.getString(R.string.beam_complete));
            notBuilder.setContentTitle(mContext.getString(R.string.beam_complete));
            notBuilder.setContentText(mContext.getString(R.string.beam_touch_to_view));

            Intent viewIntent = buildViewIntent();
            PendingIntent contentIntent = PendingIntent.getActivity(
                    mContext, 0, viewIntent, 0, null);

            notBuilder.setContentIntent(contentIntent);
        } else if (mState == STATE_FAILED) {
            notBuilder.setAutoCancel(false);
            notBuilder.setSmallIcon(android.R.drawable.stat_sys_download_done);
            notBuilder.setTicker(mContext.getString(R.string.beam_failed));
            notBuilder.setContentTitle(mContext.getString(R.string.beam_failed));
        } else if (mState == STATE_CANCELLED) {
            notBuilder.setAutoCancel(false);
            notBuilder.setSmallIcon(android.R.drawable.stat_sys_download_done);
            notBuilder.setTicker(mContext.getString(R.string.beam_canceled));
            notBuilder.setContentTitle(mContext.getString(R.string.beam_canceled));
        } else {
            return;
        }

        mNotificationManager.notify(null, mTransferId, notBuilder.build());
    }

    void updateStateAndNotification(int newState) {
        this.mState = newState;
        this.mLastUpdate = SystemClock.elapsedRealtime();

        if (mHandler.hasMessages(MSG_TRANSFER_TIMEOUT)) {
            // Update timeout timer
            mHandler.removeMessages(MSG_TRANSFER_TIMEOUT);
            mHandler.sendEmptyMessageDelayed(MSG_TRANSFER_TIMEOUT, ALIVE_CHECK_MS);
        }

        updateNotification();

        if ((mState == STATE_SUCCESS || mState == STATE_FAILED || mState == STATE_CANCELLED)
                && !mCalledBack) {
            mCalledBack = true;
            // Notify that we're done with this transfer
            mCallback.onTransferComplete(this, mState == STATE_SUCCESS);
        }
    }

    void processFiles() {
        // Check the amount of files we received in this transfer;
        // If more than one, create a separate directory for it.
        String extRoot = Environment.getExternalStorageDirectory().getPath();
        File beamPath = new File(extRoot + "/" + BEAM_DIR);

        if (!checkMediaStorage(beamPath) || mBtUris.size() == 0) {
            Log.e(TAG, "Media storage not valid or no uris received.");
            updateStateAndNotification(STATE_FAILED);
            return;
        }

        if (mBtUris.size() > 1) {
            beamPath = generateMultiplePath(extRoot + "/" + BEAM_DIR + "/");
            if (!beamPath.isDirectory() && !beamPath.mkdir()) {
                Log.e(TAG, "Failed to create multiple path " + beamPath.toString());
                updateStateAndNotification(STATE_FAILED);
                return;
            }
        }

        for (int i = 0; i < mBtUris.size(); i++) {
            Uri uri = mBtUris.get(i);
            String mimeType = mBtMimeTypes.get(i);

            File srcFile = new File(uri.getPath());

            File dstFile = generateUniqueDestination(beamPath.getAbsolutePath(),
                    uri.getLastPathSegment());
            if (!srcFile.renameTo(dstFile)) {
                if (DBG) Log.d(TAG, "Failed to rename from " + srcFile + " to " + dstFile);
                srcFile.delete();
                return;
            } else {
                mPaths.add(dstFile.getAbsolutePath());
                mMimeTypes.put(dstFile.getAbsolutePath(), mimeType);
                if (DBG) Log.d(TAG, "Did successful rename from " + srcFile + " to " + dstFile);
            }
        }

        // We can either add files to the media provider, or provide an ACTION_VIEW
        // intent to the file directly. We base this decision on the mime type
        // of the first file; if it's media the platform can deal with,
        // use the media provider, if it's something else, just launch an ACTION_VIEW
        // on the file.
        String mimeType = mMimeTypes.get(mPaths.get(0));
        if (mimeType.startsWith("image/") || mimeType.startsWith("video/") ||
                mimeType.startsWith("audio/")) {
            String[] arrayPaths = new String[mPaths.size()];
            MediaScannerConnection.scanFile(mContext, mPaths.toArray(arrayPaths), null, this);
            updateStateAndNotification(STATE_W4_MEDIA_SCANNER);
        } else {
            // We're done.
            updateStateAndNotification(STATE_SUCCESS);
        }

    }

    public int getTransferId() {
        return mTransferId;
    }

    public boolean handleMessage(Message msg) {
        if (msg.what == MSG_NEXT_TRANSFER_TIMER) {
            // We didn't receive a new transfer in time, finalize this one
            if (mIncoming) {
                processFiles();
            } else {
                updateStateAndNotification(STATE_SUCCESS);
            }
            return true;
        } else if (msg.what == MSG_TRANSFER_TIMEOUT) {
            // No update on this transfer for a while, check
            // to see if it's still running, and fail it if it is.
            if (isRunning()) {
                updateStateAndNotification(STATE_FAILED);
            }
        }
        return false;
    }

    public synchronized void onScanCompleted(String path, Uri uri) {
        if (DBG) Log.d(TAG, "Scan completed, path " + path + " uri " + uri);
        if (uri != null) {
            mMediaUris.put(path, uri);
        }
        mUrisScanned++;
        if (mUrisScanned == mPaths.size()) {
            // We're done
            updateStateAndNotification(STATE_SUCCESS);
        }
    }

    boolean checkMediaStorage(File path) {
        if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
            if (!path.isDirectory() && !path.mkdir()) {
                Log.e(TAG, "Not dir or not mkdir " + path.getAbsolutePath());
                return false;
            }
            return true;
        } else {
            Log.e(TAG, "External storage not mounted, can't store file.");
            return false;
        }
    }

    Intent buildViewIntent() {
        if (mPaths.size() == 0) return null;

        Intent viewIntent = new Intent(Intent.ACTION_VIEW);

        String filePath = mPaths.get(0);
        Uri mediaUri = mMediaUris.get(filePath);
        Uri uri =  mediaUri != null ? mediaUri :
            Uri.parse(ContentResolver.SCHEME_FILE + "://" + filePath);
        viewIntent.setDataAndTypeAndNormalize(uri, mMimeTypes.get(filePath));
        viewIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        return viewIntent;
    }

    PendingIntent buildCancelIntent() {
        Intent intent = new Intent(HandoverService.ACTION_CANCEL_HANDOVER_TRANSFER);
        intent.putExtra(HandoverService.EXTRA_SOURCE_ADDRESS, mRemoteDevice.getAddress());
        PendingIntent pi = PendingIntent.getBroadcast(mContext, 0, intent, 0);

        return pi;
    }

    File generateUniqueDestination(String path, String fileName) {
        int dotIndex = fileName.lastIndexOf(".");
        String extension = null;
        String fileNameWithoutExtension = null;
        if (dotIndex < 0) {
            extension = "";
            fileNameWithoutExtension = fileName;
        } else {
            extension = fileName.substring(dotIndex);
            fileNameWithoutExtension = fileName.substring(0, dotIndex);
        }
        File dstFile = new File(path + File.separator + fileName);
        int count = 0;
        while (dstFile.exists()) {
            dstFile = new File(path + File.separator + fileNameWithoutExtension + "-" +
                    Integer.toString(count) + extension);
            count++;
        }
        return dstFile;
    }

    File generateMultiplePath(String beamRoot) {
        // Generate a unique directory with the date
        String format = "yyyy-MM-dd";
        SimpleDateFormat sdf = new SimpleDateFormat(format);
        String newPath = beamRoot + "beam-" + sdf.format(new Date());
        File newFile = new File(newPath);
        int count = 0;
        while (newFile.exists()) {
            newPath = beamRoot + "beam-" + sdf.format(new Date()) + "-" +
                    Integer.toString(count);
            newFile = new File(newPath);
            count++;
        }
        return newFile;
    }
}