• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * Copyright (c) 2008-2009, Motorola, Inc.
3  *
4  * All rights reserved.
5  *
6  * Redistribution and use in source and binary forms, with or without
7  * modification, are permitted provided that the following conditions are met:
8  *
9  * - Redistributions of source code must retain the above copyright notice,
10  * this list of conditions and the following disclaimer.
11  *
12  * - Redistributions in binary form must reproduce the above copyright notice,
13  * this list of conditions and the following disclaimer in the documentation
14  * and/or other materials provided with the distribution.
15  *
16  * - Neither the name of the Motorola, Inc. nor the names of its contributors
17  * may be used to endorse or promote products derived from this software
18  * without specific prior written permission.
19  *
20  * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
21  * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
22  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
23  * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
24  * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
25  * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
26  * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
27  * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
28  * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
29  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
30  * POSSIBILITY OF SUCH DAMAGE.
31  */
32 
33 package com.android.bluetooth.opp;
34 
35 import com.android.bluetooth.R;
36 import com.google.android.collect.Lists;
37 
38 import android.bluetooth.BluetoothAdapter;
39 import android.bluetooth.BluetoothDevice;
40 import android.net.Uri;
41 import android.content.ContentResolver;
42 import android.content.ContentValues;
43 import android.content.Context;
44 import android.content.ActivityNotFoundException;
45 import android.content.Intent;
46 import android.content.pm.PackageManager;
47 import android.content.pm.ResolveInfo;
48 import android.database.Cursor;
49 import android.os.Environment;
50 import android.util.Log;
51 
52 import java.io.File;
53 import java.io.IOException;
54 import java.util.ArrayList;
55 import java.util.List;
56 import java.util.concurrent.ConcurrentHashMap;
57 
58 /**
59  * This class has some utilities for Opp application;
60  */
61 public class BluetoothOppUtility {
62     private static final String TAG = "BluetoothOppUtility";
63     private static final boolean D = Constants.DEBUG;
64     private static final boolean V = Constants.VERBOSE;
65 
66     private static final ConcurrentHashMap<Uri, BluetoothOppSendFileInfo> sSendFileMap
67             = new ConcurrentHashMap<Uri, BluetoothOppSendFileInfo>();
68 
isBluetoothShareUri(Uri uri)69     public static boolean isBluetoothShareUri(Uri uri) {
70         return uri.toString().startsWith(BluetoothShare.CONTENT_URI.toString());
71     }
72 
queryRecord(Context context, Uri uri)73     public static BluetoothOppTransferInfo queryRecord(Context context, Uri uri) {
74         BluetoothOppTransferInfo info = new BluetoothOppTransferInfo();
75         Cursor cursor = context.getContentResolver().query(uri, null, null, null, null);
76         if (cursor != null) {
77             if (cursor.moveToFirst()) {
78                 fillRecord(context, cursor, info);
79             }
80             cursor.close();
81         } else {
82             info = null;
83             if (V) Log.v(TAG, "BluetoothOppManager Error: not got data from db for uri:" + uri);
84         }
85         return info;
86     }
87 
fillRecord(Context context, Cursor cursor, BluetoothOppTransferInfo info)88     public static void fillRecord(Context context, Cursor cursor, BluetoothOppTransferInfo info) {
89         BluetoothAdapter adapter = BluetoothAdapter.getDefaultAdapter();
90         info.mID = cursor.getInt(cursor.getColumnIndexOrThrow(BluetoothShare._ID));
91         info.mStatus = cursor.getInt(cursor.getColumnIndexOrThrow(BluetoothShare.STATUS));
92         info.mDirection = cursor.getInt(cursor
93                 .getColumnIndexOrThrow(BluetoothShare.DIRECTION));
94         info.mTotalBytes = cursor.getLong(cursor
95                 .getColumnIndexOrThrow(BluetoothShare.TOTAL_BYTES));
96         info.mCurrentBytes = cursor.getLong(cursor
97                 .getColumnIndexOrThrow(BluetoothShare.CURRENT_BYTES));
98         info.mTimeStamp = cursor.getLong(cursor
99                 .getColumnIndexOrThrow(BluetoothShare.TIMESTAMP));
100         info.mDestAddr = cursor.getString(cursor
101                 .getColumnIndexOrThrow(BluetoothShare.DESTINATION));
102 
103         info.mFileName = cursor.getString(cursor
104                 .getColumnIndexOrThrow(BluetoothShare._DATA));
105         if (info.mFileName == null) {
106             info.mFileName = cursor.getString(cursor
107                     .getColumnIndexOrThrow(BluetoothShare.FILENAME_HINT));
108         }
109         if (info.mFileName == null) {
110             info.mFileName = context.getString(R.string.unknown_file);
111         }
112 
113         info.mFileUri = cursor.getString(cursor.getColumnIndexOrThrow(BluetoothShare.URI));
114 
115         if (info.mFileUri != null) {
116             Uri u = Uri.parse(info.mFileUri);
117             info.mFileType = context.getContentResolver().getType(u);
118         } else {
119             Uri u = Uri.parse(info.mFileName);
120             info.mFileType = context.getContentResolver().getType(u);
121         }
122         if (info.mFileType == null) {
123             info.mFileType = cursor.getString(cursor
124                     .getColumnIndexOrThrow(BluetoothShare.MIMETYPE));
125         }
126 
127         BluetoothDevice remoteDevice = adapter.getRemoteDevice(info.mDestAddr);
128         info.mDeviceName =
129                 BluetoothOppManager.getInstance(context).getDeviceName(remoteDevice);
130 
131         int confirmationType = cursor.getInt(
132                 cursor.getColumnIndexOrThrow(BluetoothShare.USER_CONFIRMATION));
133         info.mHandoverInitiated =
134                 confirmationType == BluetoothShare.USER_CONFIRMATION_HANDOVER_CONFIRMED;
135 
136         if (V) Log.v(TAG, "Get data from db:" + info.mFileName + info.mFileType
137                     + info.mDestAddr);
138     }
139 
140     /**
141      * Organize Array list for transfers in one batch
142      */
143     // This function is used when UI show batch transfer. Currently only show single transfer.
queryTransfersInBatch(Context context, Long timeStamp)144     public static ArrayList<String> queryTransfersInBatch(Context context, Long timeStamp) {
145         ArrayList<String> uris = Lists.newArrayList();
146         final String WHERE = BluetoothShare.TIMESTAMP + " == " + timeStamp;
147 
148         Cursor metadataCursor = context.getContentResolver().query(BluetoothShare.CONTENT_URI,
149                 new String[] {
150                     BluetoothShare._DATA
151                 }, WHERE, null, BluetoothShare._ID);
152 
153         if (metadataCursor == null) {
154             return null;
155         }
156 
157         for (metadataCursor.moveToFirst(); !metadataCursor.isAfterLast(); metadataCursor
158                 .moveToNext()) {
159             String fileName = metadataCursor.getString(0);
160             Uri path = Uri.parse(fileName);
161             // If there is no scheme, then it must be a file
162             if (path.getScheme() == null) {
163                 path = Uri.fromFile(new File(fileName));
164             }
165             uris.add(path.toString());
166             if (V) Log.d(TAG, "Uri in this batch: " + path.toString());
167         }
168         metadataCursor.close();
169         return uris;
170     }
171 
172     /**
173      * Open the received file with appropriate application, if can not find
174      * application to handle, display error dialog.
175      */
openReceivedFile(Context context, String fileName, String mimetype, Long timeStamp, Uri uri)176     public static void openReceivedFile(Context context, String fileName, String mimetype,
177             Long timeStamp, Uri uri) {
178         if (fileName == null || mimetype == null) {
179             Log.e(TAG, "ERROR: Para fileName ==null, or mimetype == null");
180             return;
181         }
182 
183         if (!isBluetoothShareUri(uri)) {
184             Log.e(TAG, "Trying to open a file that wasn't transfered over Bluetooth");
185             return;
186         }
187 
188         File f = new File(fileName);
189         if (!f.exists()) {
190             Intent in = new Intent(context, BluetoothOppBtErrorActivity.class);
191             in.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
192             in.putExtra("title", context.getString(R.string.not_exist_file));
193             in.putExtra("content", context.getString(R.string.not_exist_file_desc));
194             context.startActivity(in);
195 
196             // Due to the file is not existing, delete related info in btopp db
197             // to prevent this file from appearing in live folder
198             if (V) Log.d(TAG, "This uri will be deleted: " + uri);
199             context.getContentResolver().delete(uri, null, null);
200             return;
201         }
202 
203         Uri path = BluetoothOppFileProvider.getUriForFile(
204                 context, "com.android.bluetooth.opp.fileprovider", f);
205         if (path == null) {
206             Log.w(TAG, "Cannot get content URI for the shared file");
207             return;
208         }
209         // If there is no scheme, then it must be a file
210         if (path.getScheme() == null) {
211             path = Uri.fromFile(new File(fileName));
212         }
213 
214         if (isRecognizedFileType(context, path, mimetype)) {
215             Intent activityIntent = new Intent(Intent.ACTION_VIEW);
216             activityIntent.setDataAndTypeAndNormalize(path, mimetype);
217 
218             List<ResolveInfo> resInfoList = context.getPackageManager()
219                 .queryIntentActivities(activityIntent,
220                         PackageManager.MATCH_DEFAULT_ONLY);
221 
222             activityIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
223             activityIntent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
224 
225             try {
226                 if (V) Log.d(TAG, "ACTION_VIEW intent sent out: " + path + " / " + mimetype);
227                 context.startActivity(activityIntent);
228             } catch (ActivityNotFoundException ex) {
229                 if (V) Log.d(TAG, "no activity for handling ACTION_VIEW intent:  " + mimetype, ex);
230             }
231         } else {
232             Intent in = new Intent(context, BluetoothOppBtErrorActivity.class);
233             in.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
234             in.putExtra("title", context.getString(R.string.unknown_file));
235             in.putExtra("content", context.getString(R.string.unknown_file_desc));
236             context.startActivity(in);
237         }
238     }
239 
240     /**
241      * To judge if the file type supported (can be handled by some app) by phone
242      * system.
243      */
isRecognizedFileType(Context context, Uri fileUri, String mimetype)244     public static boolean isRecognizedFileType(Context context, Uri fileUri, String mimetype) {
245         boolean ret = true;
246 
247         if (D) Log.d(TAG, "RecognizedFileType() fileUri: " + fileUri + " mimetype: " + mimetype);
248 
249         Intent mimetypeIntent = new Intent(Intent.ACTION_VIEW);
250         mimetypeIntent.setDataAndTypeAndNormalize(fileUri, mimetype);
251         List<ResolveInfo> list = context.getPackageManager().queryIntentActivities(mimetypeIntent,
252                 PackageManager.MATCH_DEFAULT_ONLY);
253 
254         if (list.size() == 0) {
255             if (D) Log.d(TAG, "NO application to handle MIME type " + mimetype);
256             ret = false;
257         }
258         return ret;
259     }
260 
261     /**
262      * update visibility to Hidden
263      */
updateVisibilityToHidden(Context context, Uri uri)264     public static void updateVisibilityToHidden(Context context, Uri uri) {
265         ContentValues updateValues = new ContentValues();
266         updateValues.put(BluetoothShare.VISIBILITY, BluetoothShare.VISIBILITY_HIDDEN);
267         context.getContentResolver().update(uri, updateValues, null, null);
268     }
269 
270     /**
271      * Helper function to build the progress text.
272      */
formatProgressText(long totalBytes, long currentBytes)273     public static String formatProgressText(long totalBytes, long currentBytes) {
274         if (totalBytes <= 0) {
275             return "0%";
276         }
277         long progress = currentBytes * 100 / totalBytes;
278         StringBuilder sb = new StringBuilder();
279         sb.append(progress);
280         sb.append('%');
281         return sb.toString();
282     }
283 
284     /**
285      * Get status description according to status code.
286      */
getStatusDescription(Context context, int statusCode, String deviceName)287     public static String getStatusDescription(Context context, int statusCode, String deviceName) {
288         String ret;
289         if (statusCode == BluetoothShare.STATUS_PENDING) {
290             ret = context.getString(R.string.status_pending);
291         } else if (statusCode == BluetoothShare.STATUS_RUNNING) {
292             ret = context.getString(R.string.status_running);
293         } else if (statusCode == BluetoothShare.STATUS_SUCCESS) {
294             ret = context.getString(R.string.status_success);
295         } else if (statusCode == BluetoothShare.STATUS_NOT_ACCEPTABLE) {
296             ret = context.getString(R.string.status_not_accept);
297         } else if (statusCode == BluetoothShare.STATUS_FORBIDDEN) {
298             ret = context.getString(R.string.status_forbidden);
299         } else if (statusCode == BluetoothShare.STATUS_CANCELED) {
300             ret = context.getString(R.string.status_canceled);
301         } else if (statusCode == BluetoothShare.STATUS_FILE_ERROR) {
302             ret = context.getString(R.string.status_file_error);
303         } else if (statusCode == BluetoothShare.STATUS_ERROR_NO_SDCARD) {
304             ret = context.getString(R.string.status_no_sd_card);
305         } else if (statusCode == BluetoothShare.STATUS_CONNECTION_ERROR) {
306             ret = context.getString(R.string.status_connection_error);
307         } else if (statusCode == BluetoothShare.STATUS_ERROR_SDCARD_FULL) {
308             ret = context.getString(R.string.bt_sm_2_1, deviceName);
309         } else if ((statusCode == BluetoothShare.STATUS_BAD_REQUEST)
310                 || (statusCode == BluetoothShare.STATUS_LENGTH_REQUIRED)
311                 || (statusCode == BluetoothShare.STATUS_PRECONDITION_FAILED)
312                 || (statusCode == BluetoothShare.STATUS_UNHANDLED_OBEX_CODE)
313                 || (statusCode == BluetoothShare.STATUS_OBEX_DATA_ERROR)) {
314             ret = context.getString(R.string.status_protocol_error);
315         } else {
316             ret = context.getString(R.string.status_unknown_error);
317         }
318         return ret;
319     }
320 
321     /**
322      * Retry the failed transfer: Will insert a new transfer session to db
323      */
retryTransfer(Context context, BluetoothOppTransferInfo transInfo)324     public static void retryTransfer(Context context, BluetoothOppTransferInfo transInfo) {
325         ContentValues values = new ContentValues();
326         values.put(BluetoothShare.URI, transInfo.mFileUri);
327         values.put(BluetoothShare.MIMETYPE, transInfo.mFileType);
328         values.put(BluetoothShare.DESTINATION, transInfo.mDestAddr);
329 
330         final Uri contentUri = context.getContentResolver().insert(BluetoothShare.CONTENT_URI,
331                 values);
332         if (V) Log.v(TAG, "Insert contentUri: " + contentUri + "  to device: " +
333                 transInfo.mDeviceName);
334     }
335 
putSendFileInfo(Uri uri, BluetoothOppSendFileInfo sendFileInfo)336     static void putSendFileInfo(Uri uri, BluetoothOppSendFileInfo sendFileInfo) {
337         if (D) Log.d(TAG, "putSendFileInfo: uri=" + uri + " sendFileInfo=" + sendFileInfo);
338         if (sendFileInfo == BluetoothOppSendFileInfo.SEND_FILE_INFO_ERROR) {
339             Log.e(TAG, "putSendFileInfo: bad sendFileInfo, URI: " + uri);
340         }
341         sSendFileMap.put(uri, sendFileInfo);
342     }
343 
getSendFileInfo(Uri uri)344     static BluetoothOppSendFileInfo getSendFileInfo(Uri uri) {
345         if (D) Log.d(TAG, "getSendFileInfo: uri=" + uri);
346         BluetoothOppSendFileInfo info = sSendFileMap.get(uri);
347         return (info != null) ? info : BluetoothOppSendFileInfo.SEND_FILE_INFO_ERROR;
348     }
349 
closeSendFileInfo(Uri uri)350     static void closeSendFileInfo(Uri uri) {
351         if (D) Log.d(TAG, "closeSendFileInfo: uri=" + uri);
352         BluetoothOppSendFileInfo info = sSendFileMap.remove(uri);
353         if (info != null && info.mInputStream != null) {
354             try {
355                 info.mInputStream.close();
356             } catch (IOException ignored) {
357             }
358         }
359     }
360 
361     /**
362      * Checks if the URI is in Environment.getExternalStorageDirectory() as it
363      * is the only directory that is possibly readable by both the sender and
364      * the Bluetooth process.
365      */
isInExternalStorageDir(Uri uri)366     static boolean isInExternalStorageDir(Uri uri) {
367         if (!ContentResolver.SCHEME_FILE.equals(uri.getScheme())) {
368             Log.e(TAG, "Not a file URI: " + uri);
369             return false;
370         }
371         final File file = new File(uri.getCanonicalUri().getPath());
372         return isSameOrSubDirectory(Environment.getExternalStorageDirectory(), file);
373     }
374 
375     /**
376      * Checks, whether the child directory is the same as, or a sub-directory of the base
377      * directory. Neither base nor child should be null.
378      */
isSameOrSubDirectory(File base, File child)379     static boolean isSameOrSubDirectory(File base, File child) {
380         try {
381             base = base.getCanonicalFile();
382             child = child.getCanonicalFile();
383             File parentFile = child;
384             while (parentFile != null) {
385                 if (base.equals(parentFile)) {
386                     return true;
387                 }
388                 parentFile = parentFile.getParentFile();
389             }
390             return false;
391         } catch (IOException ex) {
392             Log.e(TAG, "Error while accessing file", ex);
393             return false;
394         }
395     }
396 }
397