blob: a647dcc2d4b904adaa6525ce0ff45080246c87e6 [file] [log] [blame]
Mike Lockwoodd21eac92010-07-03 00:44:05 -04001/*
2 * Copyright (C) 2010 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
Mike Lockwood0cd01362010-12-30 11:54:33 -050017package android.mtp;
Mike Lockwoodd21eac92010-07-03 00:44:05 -040018
Mike Lockwood56c85242014-03-07 13:29:08 -080019import android.content.BroadcastReceiver;
Jeff Sharkey60cfad82016-01-05 17:30:57 -070020import android.content.ContentProviderClient;
Mike Lockwoodd815f792010-07-12 08:49:01 -040021import android.content.ContentValues;
Jeff Sharkey60cfad82016-01-05 17:30:57 -070022import android.content.Context;
Mike Lockwood2837eef2010-08-31 16:25:12 -040023import android.content.Intent;
Mike Lockwood56c85242014-03-07 13:29:08 -080024import android.content.IntentFilter;
Mike Lockwood775de952011-03-05 17:34:11 -050025import android.content.SharedPreferences;
Mike Lockwoodd21eac92010-07-03 00:44:05 -040026import android.database.Cursor;
Mike Lockwood59e3f0d2010-09-02 14:57:30 -040027import android.database.sqlite.SQLiteDatabase;
Mike Lockwood0cd01362010-12-30 11:54:33 -050028import android.media.MediaScanner;
Mike Lockwoodd21eac92010-07-03 00:44:05 -040029import android.net.Uri;
Mike Lockwood56c85242014-03-07 13:29:08 -080030import android.os.BatteryManager;
Mike Lockwoodd21eac92010-07-03 00:44:05 -040031import android.os.RemoteException;
Jerry Zhang13bb2f42016-12-14 15:39:29 -080032import android.os.SystemProperties;
Jerry Zhangf9c5c252017-08-16 18:07:51 -070033import android.os.storage.StorageVolume;
Mike Lockwooda3156052010-11-20 12:28:27 -050034import android.provider.MediaStore;
Mike Lockwood9a2046f2010-08-03 15:30:09 -040035import android.provider.MediaStore.Audio;
Mike Lockwood3b2a62e2010-09-08 12:47:57 -040036import android.provider.MediaStore.Files;
Mike Lockwoodae078f72010-09-26 12:35:51 -040037import android.provider.MediaStore.MediaColumns;
Mike Lockwoodd21eac92010-07-03 00:44:05 -040038import android.util.Log;
Mike Lockwoodea93fa12010-12-07 10:41:35 -080039import android.view.Display;
40import android.view.WindowManager;
Mike Lockwoodd21eac92010-07-03 00:44:05 -040041
Jeff Sharkey60cfad82016-01-05 17:30:57 -070042import dalvik.system.CloseGuard;
43
Jerry Zhangf9c5c252017-08-16 18:07:51 -070044import com.google.android.collect.Sets;
45
Mike Lockwood5ebac832010-10-12 11:33:47 -040046import java.io.File;
Jerry Zhangf9c5c252017-08-16 18:07:51 -070047import java.nio.file.Path;
48import java.nio.file.Paths;
49import java.util.ArrayList;
50import java.util.Arrays;
Mike Lockwood7d7fb632010-12-01 18:46:23 -050051import java.util.HashMap;
Jerry Zhangf9c5c252017-08-16 18:07:51 -070052import java.util.Iterator;
dujin.chafe464a72011-11-22 12:13:33 +090053import java.util.Locale;
Jeff Sharkey60cfad82016-01-05 17:30:57 -070054import java.util.concurrent.atomic.AtomicBoolean;
Jerry Zhangf9c5c252017-08-16 18:07:51 -070055import java.util.stream.IntStream;
56import java.util.stream.Stream;
Mike Lockwood5ebac832010-10-12 11:33:47 -040057
Mike Lockwoodd21eac92010-07-03 00:44:05 -040058/**
Jerry Zhangf9c5c252017-08-16 18:07:51 -070059 * MtpDatabase provides an interface for MTP operations that MtpServer can use. To do this, it uses
60 * MtpStorageManager for filesystem operations and MediaProvider to get media metadata. File
61 * operations are also reflected in MediaProvider if possible.
62 * operations
Mike Lockwoodd21eac92010-07-03 00:44:05 -040063 * {@hide}
64 */
Jeff Sharkey60cfad82016-01-05 17:30:57 -070065public class MtpDatabase implements AutoCloseable {
Jerry Zhangf9c5c252017-08-16 18:07:51 -070066 private static final String TAG = MtpDatabase.class.getSimpleName();
Mike Lockwoodd21eac92010-07-03 00:44:05 -040067
Mike Lockwood2837eef2010-08-31 16:25:12 -040068 private final Context mContext;
Jeff Sharkey60cfad82016-01-05 17:30:57 -070069 private final ContentProviderClient mMediaProvider;
Mike Lockwoodd21eac92010-07-03 00:44:05 -040070 private final String mVolumeName;
71 private final Uri mObjectsUri;
Jeff Sharkey60cfad82016-01-05 17:30:57 -070072 private final MediaScanner mMediaScanner;
73
74 private final AtomicBoolean mClosed = new AtomicBoolean();
75 private final CloseGuard mCloseGuard = CloseGuard.get();
76
Jerry Zhangf9c5c252017-08-16 18:07:51 -070077 private final HashMap<String, MtpStorage> mStorageMap = new HashMap<>();
Mike Lockwoodd21eac92010-07-03 00:44:05 -040078
Mike Lockwood7d7fb632010-12-01 18:46:23 -050079 // cached property groups for single properties
Jerry Zhangf9c5c252017-08-16 18:07:51 -070080 private final HashMap<Integer, MtpPropertyGroup> mPropertyGroupsByProperty = new HashMap<>();
Mike Lockwood7d7fb632010-12-01 18:46:23 -050081
82 // cached property groups for all properties for a given format
Jerry Zhangf9c5c252017-08-16 18:07:51 -070083 private final HashMap<Integer, MtpPropertyGroup> mPropertyGroupsByFormat = new HashMap<>();
Mike Lockwood2837eef2010-08-31 16:25:12 -040084
Mike Lockwood775de952011-03-05 17:34:11 -050085 // SharedPreferences for writable MTP device properties
86 private SharedPreferences mDeviceProperties;
Mike Lockwood59e3f0d2010-09-02 14:57:30 -040087
Jerry Zhangf9c5c252017-08-16 18:07:51 -070088 // Cached device properties
Mike Lockwood56c85242014-03-07 13:29:08 -080089 private int mBatteryLevel;
90 private int mBatteryScale;
Jerry Zhang13bb2f42016-12-14 15:39:29 -080091 private int mDeviceType;
92
Jerry Zhangf9c5c252017-08-16 18:07:51 -070093 private MtpServer mServer;
94 private MtpStorageManager mManager;
95
96 private static final String PATH_WHERE = Files.FileColumns.DATA + "=?";
97 private static final String[] ID_PROJECTION = new String[] {Files.FileColumns._ID};
98 private static final String[] PATH_PROJECTION = new String[] {Files.FileColumns.DATA};
99 private static final String NO_MEDIA = ".nomedia";
100
Mike Lockwoodd21eac92010-07-03 00:44:05 -0400101 static {
102 System.loadLibrary("media_jni");
103 }
104
Jerry Zhangf9c5c252017-08-16 18:07:51 -0700105 private static final int[] PLAYBACK_FORMATS = {
106 // allow transferring arbitrary files
Mike Lockwoode5211692010-09-08 13:50:45 -0400107 MtpConstants.FORMAT_UNDEFINED,
Mike Lockwood12b8a992010-09-23 21:33:29 -0400108
Mike Lockwood792ec842010-09-09 15:30:10 -0400109 MtpConstants.FORMAT_ASSOCIATION,
Mike Lockwood12b8a992010-09-23 21:33:29 -0400110 MtpConstants.FORMAT_TEXT,
111 MtpConstants.FORMAT_HTML,
112 MtpConstants.FORMAT_WAV,
113 MtpConstants.FORMAT_MP3,
114 MtpConstants.FORMAT_MPEG,
115 MtpConstants.FORMAT_EXIF_JPEG,
116 MtpConstants.FORMAT_TIFF_EP,
bo huang240582e2012-02-27 16:27:00 +0800117 MtpConstants.FORMAT_BMP,
Mike Lockwood12b8a992010-09-23 21:33:29 -0400118 MtpConstants.FORMAT_GIF,
119 MtpConstants.FORMAT_JFIF,
120 MtpConstants.FORMAT_PNG,
121 MtpConstants.FORMAT_TIFF,
122 MtpConstants.FORMAT_WMA,
123 MtpConstants.FORMAT_OGG,
124 MtpConstants.FORMAT_AAC,
125 MtpConstants.FORMAT_MP4_CONTAINER,
126 MtpConstants.FORMAT_MP2,
127 MtpConstants.FORMAT_3GP_CONTAINER,
Mike Lockwood792ec842010-09-09 15:30:10 -0400128 MtpConstants.FORMAT_ABSTRACT_AV_PLAYLIST,
Mike Lockwood12b8a992010-09-23 21:33:29 -0400129 MtpConstants.FORMAT_WPL_PLAYLIST,
130 MtpConstants.FORMAT_M3U_PLAYLIST,
131 MtpConstants.FORMAT_PLS_PLAYLIST,
132 MtpConstants.FORMAT_XML_DOCUMENT,
Glenn Kastenf9f223e2011-01-13 11:17:00 -0800133 MtpConstants.FORMAT_FLAC,
Jaesung Chung5a8b9622015-12-18 05:50:21 +0100134 MtpConstants.FORMAT_DNG,
Chong Zhang6e18cce2017-08-16 11:57:02 -0700135 MtpConstants.FORMAT_HEIF,
Jerry Zhangf9c5c252017-08-16 18:07:51 -0700136 };
Mike Lockwood4b322ce2010-08-10 07:37:50 -0400137
Jerry Zhangf9c5c252017-08-16 18:07:51 -0700138 private static final int[] FILE_PROPERTIES = {
Mike Lockwood5367ab62010-08-30 13:23:02 -0400139 MtpConstants.PROPERTY_STORAGE_ID,
140 MtpConstants.PROPERTY_OBJECT_FORMAT,
Mike Lockwoodd3bfecb2010-09-23 23:04:28 -0400141 MtpConstants.PROPERTY_PROTECTION_STATUS,
Mike Lockwood5367ab62010-08-30 13:23:02 -0400142 MtpConstants.PROPERTY_OBJECT_SIZE,
143 MtpConstants.PROPERTY_OBJECT_FILE_NAME,
Mike Lockwoodd3bfecb2010-09-23 23:04:28 -0400144 MtpConstants.PROPERTY_DATE_MODIFIED,
Mike Lockwoodd3bfecb2010-09-23 23:04:28 -0400145 MtpConstants.PROPERTY_PERSISTENT_UID,
Jerry Zhangf9c5c252017-08-16 18:07:51 -0700146 MtpConstants.PROPERTY_PARENT_OBJECT,
Mike Lockwoodd3bfecb2010-09-23 23:04:28 -0400147 MtpConstants.PROPERTY_NAME,
Mike Lockwood71827742015-01-23 10:50:08 -0800148 MtpConstants.PROPERTY_DISPLAY_NAME,
Mike Lockwoodae078f72010-09-26 12:35:51 -0400149 MtpConstants.PROPERTY_DATE_ADDED,
150 };
151
Jerry Zhangf9c5c252017-08-16 18:07:51 -0700152 private static final int[] AUDIO_PROPERTIES = {
Mike Lockwoodae078f72010-09-26 12:35:51 -0400153 MtpConstants.PROPERTY_ARTIST,
154 MtpConstants.PROPERTY_ALBUM_NAME,
155 MtpConstants.PROPERTY_ALBUM_ARTIST,
156 MtpConstants.PROPERTY_TRACK,
157 MtpConstants.PROPERTY_ORIGINAL_RELEASE_DATE,
158 MtpConstants.PROPERTY_DURATION,
159 MtpConstants.PROPERTY_GENRE,
160 MtpConstants.PROPERTY_COMPOSER,
Mike Lockwood92b53bc2014-03-13 14:51:29 -0700161 MtpConstants.PROPERTY_AUDIO_WAVE_CODEC,
162 MtpConstants.PROPERTY_BITRATE_TYPE,
163 MtpConstants.PROPERTY_AUDIO_BITRATE,
164 MtpConstants.PROPERTY_NUMBER_OF_CHANNELS,
165 MtpConstants.PROPERTY_SAMPLE_RATE,
Mike Lockwoodae078f72010-09-26 12:35:51 -0400166 };
167
Jerry Zhangf9c5c252017-08-16 18:07:51 -0700168 private static final int[] VIDEO_PROPERTIES = {
Mike Lockwoodae078f72010-09-26 12:35:51 -0400169 MtpConstants.PROPERTY_ARTIST,
170 MtpConstants.PROPERTY_ALBUM_NAME,
171 MtpConstants.PROPERTY_DURATION,
172 MtpConstants.PROPERTY_DESCRIPTION,
173 };
174
Jerry Zhangf9c5c252017-08-16 18:07:51 -0700175 private static final int[] IMAGE_PROPERTIES = {
Mike Lockwoodae078f72010-09-26 12:35:51 -0400176 MtpConstants.PROPERTY_DESCRIPTION,
177 };
178
Jerry Zhangf9c5c252017-08-16 18:07:51 -0700179 private static final int[] DEVICE_PROPERTIES = {
180 MtpConstants.DEVICE_PROPERTY_SYNCHRONIZATION_PARTNER,
181 MtpConstants.DEVICE_PROPERTY_DEVICE_FRIENDLY_NAME,
182 MtpConstants.DEVICE_PROPERTY_IMAGE_SIZE,
183 MtpConstants.DEVICE_PROPERTY_BATTERY_LEVEL,
184 MtpConstants.DEVICE_PROPERTY_PERCEIVED_DEVICE_TYPE,
185 };
186
Mike Lockwoodae078f72010-09-26 12:35:51 -0400187 private int[] getSupportedObjectProperties(int format) {
188 switch (format) {
189 case MtpConstants.FORMAT_MP3:
190 case MtpConstants.FORMAT_WAV:
191 case MtpConstants.FORMAT_WMA:
192 case MtpConstants.FORMAT_OGG:
193 case MtpConstants.FORMAT_AAC:
Jerry Zhangf9c5c252017-08-16 18:07:51 -0700194 return IntStream.concat(Arrays.stream(FILE_PROPERTIES),
195 Arrays.stream(AUDIO_PROPERTIES)).toArray();
Mike Lockwoodae078f72010-09-26 12:35:51 -0400196 case MtpConstants.FORMAT_MPEG:
197 case MtpConstants.FORMAT_3GP_CONTAINER:
198 case MtpConstants.FORMAT_WMV:
Jerry Zhangf9c5c252017-08-16 18:07:51 -0700199 return IntStream.concat(Arrays.stream(FILE_PROPERTIES),
200 Arrays.stream(VIDEO_PROPERTIES)).toArray();
Mike Lockwoodae078f72010-09-26 12:35:51 -0400201 case MtpConstants.FORMAT_EXIF_JPEG:
202 case MtpConstants.FORMAT_GIF:
203 case MtpConstants.FORMAT_PNG:
204 case MtpConstants.FORMAT_BMP:
Jaesung Chung5a8b9622015-12-18 05:50:21 +0100205 case MtpConstants.FORMAT_DNG:
Chong Zhang6e18cce2017-08-16 11:57:02 -0700206 case MtpConstants.FORMAT_HEIF:
Jerry Zhangf9c5c252017-08-16 18:07:51 -0700207 return IntStream.concat(Arrays.stream(FILE_PROPERTIES),
208 Arrays.stream(IMAGE_PROPERTIES)).toArray();
Mike Lockwoodae078f72010-09-26 12:35:51 -0400209 default:
210 return FILE_PROPERTIES;
211 }
Mike Lockwood4b322ce2010-08-10 07:37:50 -0400212 }
213
214 private int[] getSupportedDeviceProperties() {
Jerry Zhangf9c5c252017-08-16 18:07:51 -0700215 return DEVICE_PROPERTIES;
216 }
217
218 private int[] getSupportedPlaybackFormats() {
219 return PLAYBACK_FORMATS;
220 }
221
222 private int[] getSupportedCaptureFormats() {
223 // no capture formats yet
224 return null;
225 }
226
227 private BroadcastReceiver mBatteryReceiver = new BroadcastReceiver() {
228 @Override
229 public void onReceive(Context context, Intent intent) {
230 String action = intent.getAction();
231 if (action.equals(Intent.ACTION_BATTERY_CHANGED)) {
232 mBatteryScale = intent.getIntExtra(BatteryManager.EXTRA_SCALE, 0);
233 int newLevel = intent.getIntExtra(BatteryManager.EXTRA_LEVEL, 0);
234 if (newLevel != mBatteryLevel) {
235 mBatteryLevel = newLevel;
236 if (mServer != null) {
237 // send device property changed event
238 mServer.sendDevicePropertyChanged(
239 MtpConstants.DEVICE_PROPERTY_BATTERY_LEVEL);
240 }
241 }
242 }
243 }
244 };
245
246 public MtpDatabase(Context context, Context userContext, String volumeName,
247 String[] subDirectories) {
248 native_setup();
249 mContext = context;
250 mMediaProvider = userContext.getContentResolver()
251 .acquireContentProviderClient(MediaStore.AUTHORITY);
252 mVolumeName = volumeName;
253 mObjectsUri = Files.getMtpObjectsUri(volumeName);
254 mMediaScanner = new MediaScanner(context, mVolumeName);
255 mManager = new MtpStorageManager(new MtpStorageManager.MtpNotifier() {
256 @Override
257 public void sendObjectAdded(int id) {
258 if (MtpDatabase.this.mServer != null)
259 MtpDatabase.this.mServer.sendObjectAdded(id);
260 }
261
262 @Override
263 public void sendObjectRemoved(int id) {
264 if (MtpDatabase.this.mServer != null)
265 MtpDatabase.this.mServer.sendObjectRemoved(id);
266 }
267 }, subDirectories == null ? null : Sets.newHashSet(subDirectories));
268
269 initDeviceProperties(context);
270 mDeviceType = SystemProperties.getInt("sys.usb.mtp.device_type", 0);
271 mCloseGuard.open("close");
272 }
273
274 public void setServer(MtpServer server) {
275 mServer = server;
276 // always unregister before registering
277 try {
278 mContext.unregisterReceiver(mBatteryReceiver);
279 } catch (IllegalArgumentException e) {
280 // wasn't previously registered, ignore
281 }
282 // register for battery notifications when we are connected
283 if (server != null) {
284 mContext.registerReceiver(mBatteryReceiver,
285 new IntentFilter(Intent.ACTION_BATTERY_CHANGED));
286 }
287 }
288
289 @Override
290 public void close() {
291 mManager.close();
292 mCloseGuard.close();
293 if (mClosed.compareAndSet(false, true)) {
294 mMediaScanner.close();
295 mMediaProvider.close();
296 native_finalize();
297 }
298 }
299
300 @Override
301 protected void finalize() throws Throwable {
302 try {
303 if (mCloseGuard != null) {
304 mCloseGuard.warnIfOpen();
305 }
306 close();
307 } finally {
308 super.finalize();
309 }
310 }
311
312 public void addStorage(StorageVolume storage) {
313 MtpStorage mtpStorage = mManager.addMtpStorage(storage);
314 mStorageMap.put(storage.getPath(), mtpStorage);
315 mServer.addStorage(mtpStorage);
316 }
317
318 public void removeStorage(StorageVolume storage) {
319 MtpStorage mtpStorage = mStorageMap.get(storage.getPath());
320 if (mtpStorage == null) {
321 return;
322 }
323 mServer.removeStorage(mtpStorage);
324 mManager.removeMtpStorage(mtpStorage);
325 mStorageMap.remove(storage.getPath());
326 }
327
328 private void initDeviceProperties(Context context) {
329 final String devicePropertiesName = "device-properties";
330 mDeviceProperties = context.getSharedPreferences(devicePropertiesName,
331 Context.MODE_PRIVATE);
332 File databaseFile = context.getDatabasePath(devicePropertiesName);
333
334 if (databaseFile.exists()) {
335 // for backward compatibility - read device properties from sqlite database
336 // and migrate them to shared prefs
337 SQLiteDatabase db = null;
338 Cursor c = null;
339 try {
340 db = context.openOrCreateDatabase("device-properties", Context.MODE_PRIVATE, null);
341 if (db != null) {
342 c = db.query("properties", new String[]{"_id", "code", "value"},
343 null, null, null, null, null);
344 if (c != null) {
345 SharedPreferences.Editor e = mDeviceProperties.edit();
346 while (c.moveToNext()) {
347 String name = c.getString(1);
348 String value = c.getString(2);
349 e.putString(name, value);
350 }
351 e.commit();
352 }
353 }
354 } catch (Exception e) {
355 Log.e(TAG, "failed to migrate device properties", e);
356 } finally {
357 if (c != null) c.close();
358 if (db != null) db.close();
359 }
360 context.deleteDatabase(devicePropertiesName);
361 }
362 }
363
364 private int beginSendObject(String path, int format, int parent, int storageId) {
365 MtpStorageManager.MtpObject parentObj =
366 parent == 0 ? mManager.getStorageRoot(storageId) : mManager.getObject(parent);
367 if (parentObj == null) {
368 return -1;
369 }
370
371 Path objPath = Paths.get(path);
372 return mManager.beginSendObject(parentObj, objPath.getFileName().toString(), format);
373 }
374
375 private void endSendObject(int handle, boolean succeeded) {
376 MtpStorageManager.MtpObject obj = mManager.getObject(handle);
377 if (obj == null || !mManager.endSendObject(obj, succeeded)) {
378 Log.e(TAG, "Failed to successfully end send object");
379 return;
380 }
381 // Add the new file to MediaProvider
382 if (succeeded) {
383 String path = obj.getPath().toString();
384 int format = obj.getFormat();
385 // Get parent info from MediaProvider, since the id is different from MTP's
386 ContentValues values = new ContentValues();
387 values.put(Files.FileColumns.DATA, path);
388 values.put(Files.FileColumns.FORMAT, format);
389 values.put(Files.FileColumns.SIZE, obj.getSize());
390 values.put(Files.FileColumns.DATE_MODIFIED, obj.getModifiedTime());
391 try {
392 if (obj.getParent().isRoot()) {
393 values.put(Files.FileColumns.PARENT, 0);
394 } else {
395 int parentId = findInMedia(obj.getParent().getPath());
396 if (parentId != -1) {
397 values.put(Files.FileColumns.PARENT, parentId);
398 } else {
399 // The parent isn't in MediaProvider. Don't add the new file.
400 return;
401 }
402 }
403
404 Uri uri = mMediaProvider.insert(mObjectsUri, values);
405 if (uri != null) {
406 rescanFile(path, Integer.parseInt(uri.getPathSegments().get(2)), format);
407 }
408 } catch (RemoteException e) {
409 Log.e(TAG, "RemoteException in beginSendObject", e);
410 }
411 }
412 }
413
414 private void rescanFile(String path, int handle, int format) {
415 // handle abstract playlists separately
416 // they do not exist in the file system so don't use the media scanner here
417 if (format == MtpConstants.FORMAT_ABSTRACT_AV_PLAYLIST) {
418 // extract name from path
419 String name = path;
420 int lastSlash = name.lastIndexOf('/');
421 if (lastSlash >= 0) {
422 name = name.substring(lastSlash + 1);
423 }
424 // strip trailing ".pla" from the name
425 if (name.endsWith(".pla")) {
426 name = name.substring(0, name.length() - 4);
427 }
428
429 ContentValues values = new ContentValues(1);
430 values.put(Audio.Playlists.DATA, path);
431 values.put(Audio.Playlists.NAME, name);
432 values.put(Files.FileColumns.FORMAT, format);
433 values.put(Files.FileColumns.DATE_MODIFIED, System.currentTimeMillis() / 1000);
434 values.put(MediaColumns.MEDIA_SCANNER_NEW_OBJECT_ID, handle);
435 try {
436 mMediaProvider.insert(
437 Audio.Playlists.EXTERNAL_CONTENT_URI, values);
438 } catch (RemoteException e) {
439 Log.e(TAG, "RemoteException in endSendObject", e);
440 }
441 } else {
442 mMediaScanner.scanMtpFile(path, handle, format);
443 }
444 }
445
446 private int[] getObjectList(int storageID, int format, int parent) {
447 Stream<MtpStorageManager.MtpObject> objectStream = mManager.getObjects(parent,
448 format, storageID);
449 if (objectStream == null) {
450 return null;
451 }
452 return objectStream.mapToInt(MtpStorageManager.MtpObject::getId).toArray();
453 }
454
455 private int getNumObjects(int storageID, int format, int parent) {
456 Stream<MtpStorageManager.MtpObject> objectStream = mManager.getObjects(parent,
457 format, storageID);
458 if (objectStream == null) {
459 return -1;
460 }
461 return (int) objectStream.count();
Mike Lockwood4b322ce2010-08-10 07:37:50 -0400462 }
463
Daichi Hirono486ad2e2016-02-29 17:28:47 +0900464 private MtpPropertyList getObjectPropertyList(int handle, int format, int property,
Jerry Zhangf9c5c252017-08-16 18:07:51 -0700465 int groupCode, int depth) {
Mike Lockwoode2ad6ec2010-10-14 18:03:25 -0400466 // FIXME - implement group support
Jerry Zhangf9c5c252017-08-16 18:07:51 -0700467 if (property == 0) {
468 if (groupCode == 0) {
469 return new MtpPropertyList(MtpConstants.RESPONSE_PARAMETER_NOT_SUPPORTED);
470 }
471 return new MtpPropertyList(MtpConstants.RESPONSE_SPECIFICATION_BY_GROUP_UNSUPPORTED);
472 }
473 if (depth == 0xFFFFFFFF && (handle == 0 || handle == 0xFFFFFFFF)) {
474 // request all objects starting at root
475 handle = 0xFFFFFFFF;
476 depth = 0;
477 }
478 if (!(depth == 0 || depth == 1)) {
479 // we only support depth 0 and 1
480 // depth 0: single object, depth 1: immediate children
481 return new MtpPropertyList(MtpConstants.RESPONSE_SPECIFICATION_BY_DEPTH_UNSUPPORTED);
482 }
483 Stream<MtpStorageManager.MtpObject> objectStream = Stream.of();
484 if (handle == 0xFFFFFFFF) {
485 // All objects are requested
486 objectStream = mManager.getObjects(0, format, 0xFFFFFFFF);
487 if (objectStream == null) {
488 return new MtpPropertyList(MtpConstants.RESPONSE_INVALID_OBJECT_HANDLE);
489 }
490 } else if (handle != 0) {
491 // Add the requested object if format matches
492 MtpStorageManager.MtpObject obj = mManager.getObject(handle);
493 if (obj == null) {
494 return new MtpPropertyList(MtpConstants.RESPONSE_INVALID_OBJECT_HANDLE);
495 }
496 if (obj.getFormat() == format || format == 0) {
497 objectStream = Stream.of(obj);
498 }
499 }
500 if (handle == 0 || depth == 1) {
501 if (handle == 0) {
502 handle = 0xFFFFFFFF;
503 }
504 // Get the direct children of root or this object.
505 Stream<MtpStorageManager.MtpObject> childStream = mManager.getObjects(handle, format,
506 0xFFFFFFFF);
507 if (childStream == null) {
508 return new MtpPropertyList(MtpConstants.RESPONSE_INVALID_OBJECT_HANDLE);
509 }
510 objectStream = Stream.concat(objectStream, childStream);
Mike Lockwoode2ad6ec2010-10-14 18:03:25 -0400511 }
Mike Lockwoode2ad6ec2010-10-14 18:03:25 -0400512
Jerry Zhangf9c5c252017-08-16 18:07:51 -0700513 MtpPropertyList ret = new MtpPropertyList(MtpConstants.RESPONSE_OK);
Mike Lockwood7d7fb632010-12-01 18:46:23 -0500514 MtpPropertyGroup propertyGroup;
Jerry Zhangf9c5c252017-08-16 18:07:51 -0700515 Iterator<MtpStorageManager.MtpObject> iter = objectStream.iterator();
516 while (iter.hasNext()) {
517 MtpStorageManager.MtpObject obj = iter.next();
518 if (property == 0xffffffff) {
519 // Get all properties supported by this object
520 propertyGroup = mPropertyGroupsByFormat.get(obj.getFormat());
521 if (propertyGroup == null) {
522 int[] propertyList = getSupportedObjectProperties(format);
523 propertyGroup = new MtpPropertyGroup(mMediaProvider, mVolumeName,
524 propertyList);
525 mPropertyGroupsByFormat.put(format, propertyGroup);
526 }
527 } else {
528 // Get this property value
529 final int[] propertyList = new int[]{property};
530 propertyGroup = mPropertyGroupsByProperty.get(property);
531 if (propertyGroup == null) {
532 propertyGroup = new MtpPropertyGroup(mMediaProvider, mVolumeName,
533 propertyList);
534 mPropertyGroupsByProperty.put(property, propertyGroup);
535 }
Mike Lockwood71827742015-01-23 10:50:08 -0800536 }
Jerry Zhangf9c5c252017-08-16 18:07:51 -0700537 int err = propertyGroup.getPropertyList(obj, ret);
538 if (err != MtpConstants.RESPONSE_OK) {
539 return new MtpPropertyList(err);
Mike Lockwoode2ad6ec2010-10-14 18:03:25 -0400540 }
541 }
Jerry Zhangf9c5c252017-08-16 18:07:51 -0700542 return ret;
Mike Lockwoode2ad6ec2010-10-14 18:03:25 -0400543 }
544
Mike Lockwood5ebac832010-10-12 11:33:47 -0400545 private int renameFile(int handle, String newName) {
Jerry Zhangf9c5c252017-08-16 18:07:51 -0700546 MtpStorageManager.MtpObject obj = mManager.getObject(handle);
547 if (obj == null) {
Mike Lockwood5ebac832010-10-12 11:33:47 -0400548 return MtpConstants.RESPONSE_INVALID_OBJECT_HANDLE;
549 }
Jerry Zhangf9c5c252017-08-16 18:07:51 -0700550 Path oldPath = obj.getPath();
Mike Lockwood73e56d92011-12-01 16:58:41 -0500551
Mike Lockwood5ebac832010-10-12 11:33:47 -0400552 // now rename the file. make sure this succeeds before updating database
Jerry Zhangf9c5c252017-08-16 18:07:51 -0700553 if (!mManager.beginRenameObject(obj, newName))
Mike Lockwood5ebac832010-10-12 11:33:47 -0400554 return MtpConstants.RESPONSE_GENERAL_ERROR;
Jerry Zhangf9c5c252017-08-16 18:07:51 -0700555 Path newPath = obj.getPath();
556 boolean success = oldPath.toFile().renameTo(newPath.toFile());
557 if (!mManager.endRenameObject(obj, oldPath.getFileName().toString(), success)) {
558 Log.e(TAG, "Failed to end rename object");
Mike Lockwood5ebac832010-10-12 11:33:47 -0400559 }
Mike Lockwood5ebac832010-10-12 11:33:47 -0400560 if (!success) {
561 return MtpConstants.RESPONSE_GENERAL_ERROR;
562 }
563
Jerry Zhangf9c5c252017-08-16 18:07:51 -0700564 // finally update MediaProvider
Mike Lockwood5ebac832010-10-12 11:33:47 -0400565 ContentValues values = new ContentValues();
Jerry Zhangf9c5c252017-08-16 18:07:51 -0700566 values.put(Files.FileColumns.DATA, newPath.toString());
567 String[] whereArgs = new String[]{oldPath.toString()};
Mike Lockwood5ebac832010-10-12 11:33:47 -0400568 try {
Mike Lockwood6a6a3af2010-10-12 14:19:51 -0400569 // note - we are relying on a special case in MediaProvider.update() to update
570 // the paths for all children in the case where this is a directory.
Jerry Zhangf9c5c252017-08-16 18:07:51 -0700571 mMediaProvider.update(mObjectsUri, values, PATH_WHERE, whereArgs);
Mike Lockwood5ebac832010-10-12 11:33:47 -0400572 } catch (RemoteException e) {
573 Log.e(TAG, "RemoteException in mMediaProvider.update", e);
574 }
Mike Lockwood5ebac832010-10-12 11:33:47 -0400575
Marco Nelissenca78f3d2012-01-27 09:43:20 -0800576 // check if nomedia status changed
Jerry Zhangf9c5c252017-08-16 18:07:51 -0700577 if (obj.isDir()) {
Marco Nelissenca78f3d2012-01-27 09:43:20 -0800578 // for directories, check if renamed from something hidden to something non-hidden
Jerry Zhangf9c5c252017-08-16 18:07:51 -0700579 if (oldPath.getFileName().startsWith(".") && !newPath.startsWith(".")) {
Marco Nelissenca78f3d2012-01-27 09:43:20 -0800580 // directory was unhidden
581 try {
Jerry Zhangf9c5c252017-08-16 18:07:51 -0700582 mMediaProvider.call(MediaStore.UNHIDE_CALL, newPath.toString(), null);
Marco Nelissenca78f3d2012-01-27 09:43:20 -0800583 } catch (RemoteException e) {
584 Log.e(TAG, "failed to unhide/rescan for " + newPath);
585 }
586 }
587 } else {
588 // for files, check if renamed from .nomedia to something else
Jerry Zhangf9c5c252017-08-16 18:07:51 -0700589 if (oldPath.getFileName().toString().toLowerCase(Locale.US).equals(NO_MEDIA)
590 && !newPath.getFileName().toString().toLowerCase(Locale.US).equals(NO_MEDIA)) {
Marco Nelissenca78f3d2012-01-27 09:43:20 -0800591 try {
Jerry Zhangf9c5c252017-08-16 18:07:51 -0700592 mMediaProvider.call(MediaStore.UNHIDE_CALL,
593 oldPath.getParent().toString(), null);
Marco Nelissenca78f3d2012-01-27 09:43:20 -0800594 } catch (RemoteException e) {
595 Log.e(TAG, "failed to unhide/rescan for " + newPath);
596 }
597 }
598 }
Mike Lockwood5ebac832010-10-12 11:33:47 -0400599 return MtpConstants.RESPONSE_OK;
600 }
601
Jerry Zhangf9c5c252017-08-16 18:07:51 -0700602 private int beginMoveObject(int handle, int newParent, int newStorage) {
603 MtpStorageManager.MtpObject obj = mManager.getObject(handle);
604 MtpStorageManager.MtpObject parent = newParent == 0 ?
605 mManager.getStorageRoot(newStorage) : mManager.getObject(newParent);
606 if (obj == null || parent == null)
607 return MtpConstants.RESPONSE_INVALID_OBJECT_HANDLE;
Jerry Zhang952558d42017-09-26 17:49:52 -0700608
Jerry Zhangf9c5c252017-08-16 18:07:51 -0700609 boolean allowed = mManager.beginMoveObject(obj, parent);
610 return allowed ? MtpConstants.RESPONSE_OK : MtpConstants.RESPONSE_GENERAL_ERROR;
611 }
612
613 private void endMoveObject(int oldParent, int newParent, int oldStorage, int newStorage,
614 int objId, boolean success) {
615 MtpStorageManager.MtpObject oldParentObj = oldParent == 0 ?
616 mManager.getStorageRoot(oldStorage) : mManager.getObject(oldParent);
617 MtpStorageManager.MtpObject newParentObj = newParent == 0 ?
618 mManager.getStorageRoot(newStorage) : mManager.getObject(newParent);
619 MtpStorageManager.MtpObject obj = mManager.getObject(objId);
620 String name = obj.getName();
621 if (newParentObj == null || oldParentObj == null
622 ||!mManager.endMoveObject(oldParentObj, newParentObj, name, success)) {
623 Log.e(TAG, "Failed to end move object");
624 return;
Jerry Zhang952558d42017-09-26 17:49:52 -0700625 }
626
Jerry Zhangf9c5c252017-08-16 18:07:51 -0700627 obj = mManager.getObject(objId);
628 if (!success || obj == null)
629 return;
630 // Get parent info from MediaProvider, since the id is different from MTP's
Jerry Zhang952558d42017-09-26 17:49:52 -0700631 ContentValues values = new ContentValues();
Jerry Zhangf9c5c252017-08-16 18:07:51 -0700632 Path path = newParentObj.getPath().resolve(name);
633 Path oldPath = oldParentObj.getPath().resolve(name);
634 values.put(Files.FileColumns.DATA, path.toString());
635 if (obj.getParent().isRoot()) {
636 values.put(Files.FileColumns.PARENT, 0);
637 } else {
638 int parentId = findInMedia(path.getParent());
639 if (parentId != -1) {
640 values.put(Files.FileColumns.PARENT, parentId);
641 } else {
642 // The new parent isn't in MediaProvider, so delete the object instead
643 deleteFromMedia(oldPath, obj.isDir());
644 return;
645 }
646 }
647 // update MediaProvider
648 Cursor c = null;
649 String[] whereArgs = new String[]{oldPath.toString()};
Jerry Zhang952558d42017-09-26 17:49:52 -0700650 try {
Jerry Zhangf9c5c252017-08-16 18:07:51 -0700651 int parentId = -1;
652 if (!oldParentObj.isRoot()) {
653 parentId = findInMedia(oldPath.getParent());
654 }
655 if (oldParentObj.isRoot() || parentId != -1) {
656 // Old parent exists in MediaProvider - perform a move
657 // note - we are relying on a special case in MediaProvider.update() to update
658 // the paths for all children in the case where this is a directory.
659 mMediaProvider.update(mObjectsUri, values, PATH_WHERE, whereArgs);
660 } else {
661 // Old parent doesn't exist - add the object
662 values.put(Files.FileColumns.FORMAT, obj.getFormat());
663 values.put(Files.FileColumns.SIZE, obj.getSize());
664 values.put(Files.FileColumns.DATE_MODIFIED, obj.getModifiedTime());
665 Uri uri = mMediaProvider.insert(mObjectsUri, values);
666 if (uri != null) {
667 rescanFile(path.toString(),
668 Integer.parseInt(uri.getPathSegments().get(2)), obj.getFormat());
669 }
670 }
Jerry Zhang952558d42017-09-26 17:49:52 -0700671 } catch (RemoteException e) {
672 Log.e(TAG, "RemoteException in mMediaProvider.update", e);
673 }
Jerry Zhangf9c5c252017-08-16 18:07:51 -0700674 }
675
676 private int beginCopyObject(int handle, int newParent, int newStorage) {
677 MtpStorageManager.MtpObject obj = mManager.getObject(handle);
678 MtpStorageManager.MtpObject parent = newParent == 0 ?
679 mManager.getStorageRoot(newStorage) : mManager.getObject(newParent);
680 if (obj == null || parent == null)
681 return MtpConstants.RESPONSE_INVALID_OBJECT_HANDLE;
682 return mManager.beginCopyObject(obj, parent);
683 }
684
685 private void endCopyObject(int handle, boolean success) {
686 MtpStorageManager.MtpObject obj = mManager.getObject(handle);
687 if (obj == null || !mManager.endCopyObject(obj, success)) {
688 Log.e(TAG, "Failed to end copy object");
689 return;
Jerry Zhang952558d42017-09-26 17:49:52 -0700690 }
Jerry Zhangf9c5c252017-08-16 18:07:51 -0700691 if (!success) {
692 return;
693 }
694 String path = obj.getPath().toString();
695 int format = obj.getFormat();
696 // Get parent info from MediaProvider, since the id is different from MTP's
697 ContentValues values = new ContentValues();
698 values.put(Files.FileColumns.DATA, path);
699 values.put(Files.FileColumns.FORMAT, format);
700 values.put(Files.FileColumns.SIZE, obj.getSize());
701 values.put(Files.FileColumns.DATE_MODIFIED, obj.getModifiedTime());
702 try {
703 if (obj.getParent().isRoot()) {
704 values.put(Files.FileColumns.PARENT, 0);
705 } else {
706 int parentId = findInMedia(obj.getParent().getPath());
707 if (parentId != -1) {
708 values.put(Files.FileColumns.PARENT, parentId);
709 } else {
710 // The parent isn't in MediaProvider. Don't add the new file.
711 return;
712 }
713 }
714 if (obj.isDir()) {
715 mMediaScanner.scanDirectories(new String[]{path});
716 } else {
717 Uri uri = mMediaProvider.insert(mObjectsUri, values);
718 if (uri != null) {
719 rescanFile(path, Integer.parseInt(uri.getPathSegments().get(2)), format);
720 }
721 }
722 } catch (RemoteException e) {
723 Log.e(TAG, "RemoteException in beginSendObject", e);
724 }
Jerry Zhang952558d42017-09-26 17:49:52 -0700725 }
726
Mike Lockwood59e3f0d2010-09-02 14:57:30 -0400727 private int setObjectProperty(int handle, int property,
Jerry Zhangf9c5c252017-08-16 18:07:51 -0700728 long intValue, String stringValue) {
Mike Lockwood5ebac832010-10-12 11:33:47 -0400729 switch (property) {
730 case MtpConstants.PROPERTY_OBJECT_FILE_NAME:
731 return renameFile(handle, stringValue);
732
733 default:
734 return MtpConstants.RESPONSE_OBJECT_PROP_NOT_SUPPORTED;
735 }
Mike Lockwood59e3f0d2010-09-02 14:57:30 -0400736 }
737
738 private int getDeviceProperty(int property, long[] outIntValue, char[] outStringValue) {
Mike Lockwood59e3f0d2010-09-02 14:57:30 -0400739 switch (property) {
740 case MtpConstants.DEVICE_PROPERTY_SYNCHRONIZATION_PARTNER:
741 case MtpConstants.DEVICE_PROPERTY_DEVICE_FRIENDLY_NAME:
Mike Lockwood775de952011-03-05 17:34:11 -0500742 // writable string properties kept in shared preferences
743 String value = mDeviceProperties.getString(Integer.toString(property), "");
744 int length = value.length();
745 if (length > 255) {
746 length = 255;
Mike Lockwood59e3f0d2010-09-02 14:57:30 -0400747 }
Mike Lockwood775de952011-03-05 17:34:11 -0500748 value.getChars(0, length, outStringValue, 0);
749 outStringValue[length] = 0;
750 return MtpConstants.RESPONSE_OK;
Mike Lockwoodea93fa12010-12-07 10:41:35 -0800751 case MtpConstants.DEVICE_PROPERTY_IMAGE_SIZE:
752 // use screen size as max image size
Jerry Zhangf9c5c252017-08-16 18:07:51 -0700753 Display display = ((WindowManager) mContext.getSystemService(
Mike Lockwoodea93fa12010-12-07 10:41:35 -0800754 Context.WINDOW_SERVICE)).getDefaultDisplay();
Dianne Hackborn44bc17c2011-04-20 18:18:51 -0700755 int width = display.getMaximumSizeDimension();
756 int height = display.getMaximumSizeDimension();
Jerry Zhangf9c5c252017-08-16 18:07:51 -0700757 String imageSize = Integer.toString(width) + "x" + Integer.toString(height);
Mike Lockwoodea93fa12010-12-07 10:41:35 -0800758 imageSize.getChars(0, imageSize.length(), outStringValue, 0);
759 outStringValue[imageSize.length()] = 0;
760 return MtpConstants.RESPONSE_OK;
Jerry Zhang13bb2f42016-12-14 15:39:29 -0800761 case MtpConstants.DEVICE_PROPERTY_PERCEIVED_DEVICE_TYPE:
762 outIntValue[0] = mDeviceType;
763 return MtpConstants.RESPONSE_OK;
Jerry Zhangf9c5c252017-08-16 18:07:51 -0700764 case MtpConstants.DEVICE_PROPERTY_BATTERY_LEVEL:
765 outIntValue[0] = mBatteryLevel;
766 outIntValue[1] = mBatteryScale;
767 return MtpConstants.RESPONSE_OK;
Mike Lockwoodea93fa12010-12-07 10:41:35 -0800768 default:
769 return MtpConstants.RESPONSE_DEVICE_PROP_NOT_SUPPORTED;
770 }
Mike Lockwood59e3f0d2010-09-02 14:57:30 -0400771 }
772
773 private int setDeviceProperty(int property, long intValue, String stringValue) {
Mike Lockwood59e3f0d2010-09-02 14:57:30 -0400774 switch (property) {
775 case MtpConstants.DEVICE_PROPERTY_SYNCHRONIZATION_PARTNER:
776 case MtpConstants.DEVICE_PROPERTY_DEVICE_FRIENDLY_NAME:
Mike Lockwood775de952011-03-05 17:34:11 -0500777 // writable string properties kept in shared prefs
778 SharedPreferences.Editor e = mDeviceProperties.edit();
779 e.putString(Integer.toString(property), stringValue);
780 return (e.commit() ? MtpConstants.RESPONSE_OK
781 : MtpConstants.RESPONSE_GENERAL_ERROR);
Mike Lockwood59e3f0d2010-09-02 14:57:30 -0400782 }
783
784 return MtpConstants.RESPONSE_DEVICE_PROP_NOT_SUPPORTED;
785 }
786
Mike Lockwoodd21eac92010-07-03 00:44:05 -0400787 private boolean getObjectInfo(int handle, int[] outStorageFormatParent,
Jerry Zhangf9c5c252017-08-16 18:07:51 -0700788 char[] outName, long[] outCreatedModified) {
789 MtpStorageManager.MtpObject obj = mManager.getObject(handle);
790 if (obj == null) {
791 return false;
Mike Lockwoodd21eac92010-07-03 00:44:05 -0400792 }
Jerry Zhangf9c5c252017-08-16 18:07:51 -0700793 outStorageFormatParent[0] = obj.getStorageId();
794 outStorageFormatParent[1] = obj.getFormat();
795 outStorageFormatParent[2] = obj.getParent().isRoot() ? 0 : obj.getParent().getId();
796
797 int nameLen = Integer.min(obj.getName().length(), 255);
798 obj.getName().getChars(0, nameLen, outName, 0);
799 outName[nameLen] = 0;
800
801 outCreatedModified[0] = obj.getModifiedTime();
802 outCreatedModified[1] = obj.getModifiedTime();
803 return true;
Mike Lockwoodd21eac92010-07-03 00:44:05 -0400804 }
805
Mike Lockwood365e03e2010-12-08 16:08:01 -0800806 private int getObjectFilePath(int handle, char[] outFilePath, long[] outFileLengthFormat) {
Jerry Zhangf9c5c252017-08-16 18:07:51 -0700807 MtpStorageManager.MtpObject obj = mManager.getObject(handle);
808 if (obj == null) {
809 return MtpConstants.RESPONSE_INVALID_OBJECT_HANDLE;
Mike Lockwood01788562010-10-11 11:22:19 -0400810 }
Jerry Zhangf9c5c252017-08-16 18:07:51 -0700811
812 String path = obj.getPath().toString();
813 int pathLen = Integer.min(path.length(), 4096);
814 path.getChars(0, pathLen, outFilePath, 0);
815 outFilePath[pathLen] = 0;
816
817 outFileLengthFormat[0] = obj.getSize();
818 outFileLengthFormat[1] = obj.getFormat();
819 return MtpConstants.RESPONSE_OK;
Mike Lockwoodd21eac92010-07-03 00:44:05 -0400820 }
821
Mike Lockwood71827742015-01-23 10:50:08 -0800822 private int getObjectFormat(int handle) {
Jerry Zhangf9c5c252017-08-16 18:07:51 -0700823 MtpStorageManager.MtpObject obj = mManager.getObject(handle);
824 if (obj == null) {
Mike Lockwood71827742015-01-23 10:50:08 -0800825 return -1;
Mike Lockwood71827742015-01-23 10:50:08 -0800826 }
Jerry Zhangf9c5c252017-08-16 18:07:51 -0700827 return obj.getFormat();
Mike Lockwood71827742015-01-23 10:50:08 -0800828 }
829
Jerry Zhangf9c5c252017-08-16 18:07:51 -0700830 private int beginDeleteObject(int handle) {
831 MtpStorageManager.MtpObject obj = mManager.getObject(handle);
832 if (obj == null) {
833 return MtpConstants.RESPONSE_INVALID_OBJECT_HANDLE;
834 }
835 if (!mManager.beginRemoveObject(obj)) {
836 return MtpConstants.RESPONSE_GENERAL_ERROR;
837 }
838 return MtpConstants.RESPONSE_OK;
839 }
Mike Lockwood55f808c2010-12-14 13:14:29 -0800840
Jerry Zhangf9c5c252017-08-16 18:07:51 -0700841 private void endDeleteObject(int handle, boolean success) {
842 MtpStorageManager.MtpObject obj = mManager.getObject(handle);
843 if (obj == null) {
844 return;
845 }
846 if (!mManager.endRemoveObject(obj, success))
847 Log.e(TAG, "Failed to end remove object");
848 if (success)
849 deleteFromMedia(obj.getPath(), obj.isDir());
850 }
851
852 private int findInMedia(Path path) {
853 int ret = -1;
Mike Lockwood55f808c2010-12-14 13:14:29 -0800854 Cursor c = null;
Mike Lockwoodd21eac92010-07-03 00:44:05 -0400855 try {
Jerry Zhangf9c5c252017-08-16 18:07:51 -0700856 c = mMediaProvider.query(mObjectsUri, ID_PROJECTION, PATH_WHERE,
857 new String[]{path.toString()}, null, null);
Mike Lockwood55f808c2010-12-14 13:14:29 -0800858 if (c != null && c.moveToNext()) {
Jerry Zhangf9c5c252017-08-16 18:07:51 -0700859 ret = c.getInt(0);
Mike Lockwood55f808c2010-12-14 13:14:29 -0800860 }
Jerry Zhangf9c5c252017-08-16 18:07:51 -0700861 } catch (RemoteException e) {
862 Log.e(TAG, "Error finding " + path + " in MediaProvider");
863 } finally {
864 if (c != null)
865 c.close();
866 }
867 return ret;
868 }
Mike Lockwood55f808c2010-12-14 13:14:29 -0800869
Jerry Zhangf9c5c252017-08-16 18:07:51 -0700870 private void deleteFromMedia(Path path, boolean isDir) {
871 try {
872 // Delete the object(s) from MediaProvider, but ignore errors.
873 if (isDir) {
Mike Lockwood55f808c2010-12-14 13:14:29 -0800874 // recursive case - delete all children first
Jerry Zhangf9c5c252017-08-16 18:07:51 -0700875 mMediaProvider.delete(mObjectsUri,
876 // the 'like' makes it use the index, the 'lower()' makes it correct
877 // when the path contains sqlite wildcard characters
878 "_data LIKE ?1 AND lower(substr(_data,1,?2))=lower(?3)",
879 new String[]{path + "/%", Integer.toString(path.toString().length() + 1),
880 path.toString() + "/"});
Mike Lockwood55f808c2010-12-14 13:14:29 -0800881 }
882
Jerry Zhangf9c5c252017-08-16 18:07:51 -0700883 String[] whereArgs = new String[]{path.toString()};
884 if (mMediaProvider.delete(mObjectsUri, PATH_WHERE, whereArgs) > 0) {
885 if (!isDir && path.toString().toLowerCase(Locale.US).endsWith(NO_MEDIA)) {
Marco Nelissenca78f3d2012-01-27 09:43:20 -0800886 try {
Jerry Zhangf9c5c252017-08-16 18:07:51 -0700887 String parentPath = path.getParent().toString();
Jeff Sharkey60cfad82016-01-05 17:30:57 -0700888 mMediaProvider.call(MediaStore.UNHIDE_CALL, parentPath, null);
Marco Nelissenca78f3d2012-01-27 09:43:20 -0800889 } catch (RemoteException e) {
890 Log.e(TAG, "failed to unhide/rescan for " + path);
891 }
892 }
Mike Lockwood59c777a2010-08-02 10:37:41 -0400893 } else {
Jerry Zhangf9c5c252017-08-16 18:07:51 -0700894 Log.i(TAG, "Mediaprovider didn't delete " + path);
Mike Lockwood59c777a2010-08-02 10:37:41 -0400895 }
Jerry Zhangf9c5c252017-08-16 18:07:51 -0700896 } catch (Exception e) {
897 Log.d(TAG, "Failed to delete " + path + " from MediaProvider");
Mike Lockwoodd21eac92010-07-03 00:44:05 -0400898 }
899 }
900
Mike Lockwood9a2046f2010-08-03 15:30:09 -0400901 private int[] getObjectReferences(int handle) {
Jerry Zhangf9c5c252017-08-16 18:07:51 -0700902 MtpStorageManager.MtpObject obj = mManager.getObject(handle);
903 if (obj == null)
904 return null;
905 // Translate this handle to the MediaProvider Handle
906 handle = findInMedia(obj.getPath());
907 if (handle == -1)
908 return null;
Mike Lockwood8490e662010-09-09 14:16:22 -0400909 Uri uri = Files.getMtpReferencesUri(mVolumeName, handle);
Mike Lockwood9a2046f2010-08-03 15:30:09 -0400910 Cursor c = null;
911 try {
Jerry Zhangf9c5c252017-08-16 18:07:51 -0700912 c = mMediaProvider.query(uri, PATH_PROJECTION, null, null, null, null);
Mike Lockwood9a2046f2010-08-03 15:30:09 -0400913 if (c == null) {
914 return null;
915 }
Jerry Zhangf9c5c252017-08-16 18:07:51 -0700916 ArrayList<Integer> result = new ArrayList<>();
917 while (c.moveToNext()) {
918 // Translate result handles back into handles for this session.
919 String refPath = c.getString(0);
920 MtpStorageManager.MtpObject refObj = mManager.getByPath(refPath);
921 if (refObj != null) {
922 result.add(refObj.getId());
923 }
Mike Lockwood9a2046f2010-08-03 15:30:09 -0400924 }
Jerry Zhangf9c5c252017-08-16 18:07:51 -0700925 return result.stream().mapToInt(Integer::intValue).toArray();
Mike Lockwood9a2046f2010-08-03 15:30:09 -0400926 } catch (RemoteException e) {
927 Log.e(TAG, "RemoteException in getObjectList", e);
928 } finally {
929 if (c != null) {
930 c.close();
931 }
932 }
933 return null;
934 }
935
936 private int setObjectReferences(int handle, int[] references) {
Jerry Zhangf9c5c252017-08-16 18:07:51 -0700937 MtpStorageManager.MtpObject obj = mManager.getObject(handle);
938 if (obj == null)
939 return MtpConstants.RESPONSE_INVALID_OBJECT_HANDLE;
940 // Translate this handle to the MediaProvider Handle
941 handle = findInMedia(obj.getPath());
942 if (handle == -1)
943 return MtpConstants.RESPONSE_GENERAL_ERROR;
Mike Lockwood8490e662010-09-09 14:16:22 -0400944 Uri uri = Files.getMtpReferencesUri(mVolumeName, handle);
Jerry Zhangf9c5c252017-08-16 18:07:51 -0700945 ArrayList<ContentValues> valuesList = new ArrayList<>();
946 for (int id : references) {
947 // Translate each reference id to the MediaProvider Id
948 MtpStorageManager.MtpObject refObj = mManager.getObject(id);
949 if (refObj == null)
950 continue;
951 int refHandle = findInMedia(refObj.getPath());
952 if (refHandle == -1)
953 continue;
Mike Lockwood9a2046f2010-08-03 15:30:09 -0400954 ContentValues values = new ContentValues();
Jerry Zhangf9c5c252017-08-16 18:07:51 -0700955 values.put(Files.FileColumns._ID, refHandle);
956 valuesList.add(values);
Mike Lockwood9a2046f2010-08-03 15:30:09 -0400957 }
958 try {
Jerry Zhangf9c5c252017-08-16 18:07:51 -0700959 if (mMediaProvider.bulkInsert(uri, valuesList.toArray(new ContentValues[0])) > 0) {
Mike Lockwood5367ab62010-08-30 13:23:02 -0400960 return MtpConstants.RESPONSE_OK;
Mike Lockwood9a2046f2010-08-03 15:30:09 -0400961 }
962 } catch (RemoteException e) {
963 Log.e(TAG, "RemoteException in setObjectReferences", e);
964 }
Mike Lockwood5367ab62010-08-30 13:23:02 -0400965 return MtpConstants.RESPONSE_GENERAL_ERROR;
Mike Lockwood9a2046f2010-08-03 15:30:09 -0400966 }
967
Mike Lockwoodd21eac92010-07-03 00:44:05 -0400968 // used by the JNI code
Ashok Bhate2e59322013-12-17 19:04:19 +0000969 private long mNativeContext;
Mike Lockwoodd21eac92010-07-03 00:44:05 -0400970
971 private native final void native_setup();
972 private native final void native_finalize();
Mike Lockwoodd21eac92010-07-03 00:44:05 -0400973}